Refactor rt_handle_member_record
[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                                 </enumlist>
525                         </parameter>
526                 </syntax>
527                 <description>
528                         <para>Returns the number of members currently associated with the specified <replaceable>queuename</replaceable>.</para>
529                 </description>
530                 <see-also>
531                         <ref type="application">Queue</ref>
532                         <ref type="application">QueueLog</ref>
533                         <ref type="application">AddQueueMember</ref>
534                         <ref type="application">RemoveQueueMember</ref>
535                         <ref type="application">PauseQueueMember</ref>
536                         <ref type="application">UnpauseQueueMember</ref>
537                         <ref type="function">QUEUE_VARIABLES</ref>
538                         <ref type="function">QUEUE_MEMBER</ref>
539                         <ref type="function">QUEUE_MEMBER_COUNT</ref>
540                         <ref type="function">QUEUE_EXISTS</ref>
541                         <ref type="function">QUEUE_WAITING_COUNT</ref>
542                         <ref type="function">QUEUE_MEMBER_LIST</ref>
543                         <ref type="function">QUEUE_MEMBER_PENALTY</ref>
544                 </see-also>
545         </function>
546         <function name="QUEUE_MEMBER_COUNT" language="en_US">
547                 <synopsis>
548                         Count number of members answering a queue.
549                 </synopsis>
550                 <syntax>
551                         <parameter name="queuename" required="true" />
552                 </syntax>
553                 <description>
554                         <para>Returns the number of members currently associated with the specified <replaceable>queuename</replaceable>.</para>
555                         <warning><para>This function has been deprecated in favor of the <literal>QUEUE_MEMBER()</literal> function</para></warning>
556                 </description>
557                 <see-also>
558                         <ref type="application">Queue</ref>
559                         <ref type="application">QueueLog</ref>
560                         <ref type="application">AddQueueMember</ref>
561                         <ref type="application">RemoveQueueMember</ref>
562                         <ref type="application">PauseQueueMember</ref>
563                         <ref type="application">UnpauseQueueMember</ref>
564                         <ref type="function">QUEUE_VARIABLES</ref>
565                         <ref type="function">QUEUE_MEMBER</ref>
566                         <ref type="function">QUEUE_MEMBER_COUNT</ref>
567                         <ref type="function">QUEUE_EXISTS</ref>
568                         <ref type="function">QUEUE_WAITING_COUNT</ref>
569                         <ref type="function">QUEUE_MEMBER_LIST</ref>
570                         <ref type="function">QUEUE_MEMBER_PENALTY</ref>
571                 </see-also>
572         </function>
573         <function name="QUEUE_EXISTS" language="en_US">
574                 <synopsis>
575                         Check if a named queue exists on this server
576                 </synopsis>
577                 <syntax>
578                         <parameter name="queuename" />
579                 </syntax>
580                 <description>
581                         <para>Returns 1 if the specified queue exists, 0 if it does not</para>
582                 </description>
583                 <see-also>
584                         <ref type="application">Queue</ref>
585                         <ref type="application">QueueLog</ref>
586                         <ref type="application">AddQueueMember</ref>
587                         <ref type="application">RemoveQueueMember</ref>
588                         <ref type="application">PauseQueueMember</ref>
589                         <ref type="application">UnpauseQueueMember</ref>
590                         <ref type="function">QUEUE_VARIABLES</ref>
591                         <ref type="function">QUEUE_MEMBER</ref>
592                         <ref type="function">QUEUE_MEMBER_COUNT</ref>
593                         <ref type="function">QUEUE_EXISTS</ref>
594                         <ref type="function">QUEUE_WAITING_COUNT</ref>
595                         <ref type="function">QUEUE_MEMBER_LIST</ref>
596                         <ref type="function">QUEUE_MEMBER_PENALTY</ref>
597                 </see-also>
598         </function>
599         <function name="QUEUE_WAITING_COUNT" language="en_US">
600                 <synopsis>
601                         Count number of calls currently waiting in a queue.
602                 </synopsis>
603                 <syntax>
604                         <parameter name="queuename" />
605                 </syntax>
606                 <description>
607                         <para>Returns the number of callers currently waiting in the specified <replaceable>queuename</replaceable>.</para>
608                 </description>
609                 <see-also>
610                         <ref type="application">Queue</ref>
611                         <ref type="application">QueueLog</ref>
612                         <ref type="application">AddQueueMember</ref>
613                         <ref type="application">RemoveQueueMember</ref>
614                         <ref type="application">PauseQueueMember</ref>
615                         <ref type="application">UnpauseQueueMember</ref>
616                         <ref type="function">QUEUE_VARIABLES</ref>
617                         <ref type="function">QUEUE_MEMBER</ref>
618                         <ref type="function">QUEUE_MEMBER_COUNT</ref>
619                         <ref type="function">QUEUE_EXISTS</ref>
620                         <ref type="function">QUEUE_WAITING_COUNT</ref>
621                         <ref type="function">QUEUE_MEMBER_LIST</ref>
622                         <ref type="function">QUEUE_MEMBER_PENALTY</ref>
623                 </see-also>
624         </function>
625         <function name="QUEUE_MEMBER_LIST" language="en_US">
626                 <synopsis>
627                         Returns a list of interfaces on a queue.
628                 </synopsis>
629                 <syntax>
630                         <parameter name="queuename" required="true" />
631                 </syntax>
632                 <description>
633                         <para>Returns a comma-separated list of members associated with the specified <replaceable>queuename</replaceable>.</para>
634                 </description>
635                 <see-also>
636                         <ref type="application">Queue</ref>
637                         <ref type="application">QueueLog</ref>
638                         <ref type="application">AddQueueMember</ref>
639                         <ref type="application">RemoveQueueMember</ref>
640                         <ref type="application">PauseQueueMember</ref>
641                         <ref type="application">UnpauseQueueMember</ref>
642                         <ref type="function">QUEUE_VARIABLES</ref>
643                         <ref type="function">QUEUE_MEMBER</ref>
644                         <ref type="function">QUEUE_MEMBER_COUNT</ref>
645                         <ref type="function">QUEUE_EXISTS</ref>
646                         <ref type="function">QUEUE_WAITING_COUNT</ref>
647                         <ref type="function">QUEUE_MEMBER_LIST</ref>
648                         <ref type="function">QUEUE_MEMBER_PENALTY</ref>
649                 </see-also>
650         </function>
651         <function name="QUEUE_MEMBER_PENALTY" language="en_US">
652                 <synopsis>
653                         Gets or sets queue members penalty.
654                 </synopsis>
655                 <syntax>
656                         <parameter name="queuename" required="true" />
657                         <parameter name="interface" required="true" />
658                 </syntax>
659                 <description>
660                         <para>Gets or sets queue members penalty.</para>
661                 </description>
662                 <see-also>
663                         <ref type="application">Queue</ref>
664                         <ref type="application">QueueLog</ref>
665                         <ref type="application">AddQueueMember</ref>
666                         <ref type="application">RemoveQueueMember</ref>
667                         <ref type="application">PauseQueueMember</ref>
668                         <ref type="application">UnpauseQueueMember</ref>
669                         <ref type="function">QUEUE_VARIABLES</ref>
670                         <ref type="function">QUEUE_MEMBER</ref>
671                         <ref type="function">QUEUE_MEMBER_COUNT</ref>
672                         <ref type="function">QUEUE_EXISTS</ref>
673                         <ref type="function">QUEUE_WAITING_COUNT</ref>
674                         <ref type="function">QUEUE_MEMBER_LIST</ref>
675                         <ref type="function">QUEUE_MEMBER_PENALTY</ref>
676                 </see-also>
677         </function>
678         <manager name="Queues" language="en_US">
679                 <synopsis>
680                         Queues.
681                 </synopsis>
682                 <syntax>
683                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
684                 </syntax>
685                 <description>
686                 </description>
687         </manager>
688         <manager name="QueueStatus" language="en_US">
689                 <synopsis>
690                         Show queue status.
691                 </synopsis>
692                 <syntax>
693                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
694                         <parameter name="Queue" />
695                         <parameter name="Member" />
696                 </syntax>
697                 <description>
698                 </description>
699         </manager>
700         <manager name="QueueSummary" language="en_US">
701                 <synopsis>
702                         Show queue summary.
703                 </synopsis>
704                 <syntax>
705                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
706                         <parameter name="Queue" />
707                 </syntax>
708                 <description>
709                 </description>
710         </manager>
711         <manager name="QueueAdd" language="en_US">
712                 <synopsis>
713                         Add interface to queue.
714                 </synopsis>
715                 <syntax>
716                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
717                         <parameter name="Queue" required="true" />
718                         <parameter name="Interface" required="true" />
719                         <parameter name="Penalty" />
720                         <parameter name="Paused" />
721                         <parameter name="MemberName" />
722                         <parameter name="StateInterface" />
723                 </syntax>
724                 <description>
725                 </description>
726         </manager>
727         <manager name="QueueRemove" language="en_US">
728                 <synopsis>
729                         Remove interface from queue.
730                 </synopsis>
731                 <syntax>
732                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
733                         <parameter name="Queue" required="true" />
734                         <parameter name="Interface" required="true" />
735                 </syntax>
736                 <description>
737                 </description>
738         </manager>
739         <manager name="QueuePause" language="en_US">
740                 <synopsis>
741                         Makes a queue member temporarily unavailable.
742                 </synopsis>
743                 <syntax>
744                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
745                         <parameter name="Interface" required="true" />
746                         <parameter name="Paused" required="true" />
747                         <parameter name="Queue" />
748                         <parameter name="Reason" />
749                 </syntax>
750                 <description>
751                 </description>
752         </manager>
753         <manager name="QueueLog" language="en_US">
754                 <synopsis>
755                         Adds custom entry in queue_log.
756                 </synopsis>
757                 <syntax>
758                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
759                         <parameter name="Queue" required="true" />
760                         <parameter name="Event" required="true" />
761                         <parameter name="Uniqueid" />
762                         <parameter name="Interface" />
763                         <parameter name="Message" />
764                 </syntax>
765                 <description>
766                 </description>
767         </manager>
768         <manager name="QueuePenalty" language="en_US">
769                 <synopsis>
770                         Set the penalty for a queue member.
771                 </synopsis>
772                 <syntax>
773                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
774                         <parameter name="Interface" required="true" />
775                         <parameter name="Penalty" required="true" />
776                         <parameter name="Queue" />
777                 </syntax>
778                 <description>
779                 </description>
780         </manager>
781         <manager name="QueueRule" language="en_US">
782                 <synopsis>
783                         Queue Rules.
784                 </synopsis>
785                 <syntax>
786                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
787                         <parameter name="Rule" />
788                 </syntax>
789                 <description>
790                 </description>
791         </manager>
792         <manager name="QueueReload" language="en_US">
793                 <synopsis>
794                         Reload a queue, queues, or any sub-section of a queue or queues.
795                 </synopsis>
796                 <syntax>
797                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
798                         <parameter name="Queue" />
799                         <parameter name="Members">
800                                 <enumlist>
801                                         <enum name="yes" />
802                                         <enum name="no" />
803                                 </enumlist>
804                         </parameter>
805                         <parameter name="Rules">
806                                 <enumlist>
807                                         <enum name="yes" />
808                                         <enum name="no" />
809                                 </enumlist>
810                         </parameter>
811                         <parameter name="Parameters">
812                                 <enumlist>
813                                         <enum name="yes" />
814                                         <enum name="no" />
815                                 </enumlist>
816                         </parameter>
817                 </syntax>
818                 <description>
819                 </description>
820         </manager>
821         <manager name="QueueReset" language="en_US">
822                 <synopsis>
823                         Reset queue statistics.
824                 </synopsis>
825                 <syntax>
826                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
827                         <parameter name="Queue" />
828                 </syntax>
829                 <description>
830                 </description>
831         </manager>
832  ***/
833
834 enum {
835         QUEUE_STRATEGY_RINGALL = 0,
836         QUEUE_STRATEGY_LEASTRECENT,
837         QUEUE_STRATEGY_FEWESTCALLS,
838         QUEUE_STRATEGY_RANDOM,
839         QUEUE_STRATEGY_RRMEMORY,
840         QUEUE_STRATEGY_LINEAR,
841         QUEUE_STRATEGY_WRANDOM,
842         QUEUE_STRATEGY_RRORDERED,
843 };
844
845 enum {
846      QUEUE_AUTOPAUSE_OFF = 0,
847      QUEUE_AUTOPAUSE_ON,
848      QUEUE_AUTOPAUSE_ALL
849 };
850
851 enum queue_reload_mask {
852         QUEUE_RELOAD_PARAMETERS = (1 << 0),
853         QUEUE_RELOAD_MEMBER = (1 << 1),
854         QUEUE_RELOAD_RULES = (1 << 2),
855         QUEUE_RESET_STATS = (1 << 3),
856 };
857
858 static const struct strategy {
859         int strategy;
860         const char *name;
861 } strategies[] = {
862         { QUEUE_STRATEGY_RINGALL, "ringall" },
863         { QUEUE_STRATEGY_LEASTRECENT, "leastrecent" },
864         { QUEUE_STRATEGY_FEWESTCALLS, "fewestcalls" },
865         { QUEUE_STRATEGY_RANDOM, "random" },
866         { QUEUE_STRATEGY_RRMEMORY, "rrmemory" },
867         { QUEUE_STRATEGY_RRMEMORY, "roundrobin" },
868         { QUEUE_STRATEGY_LINEAR, "linear" },
869         { QUEUE_STRATEGY_WRANDOM, "wrandom"},
870         { QUEUE_STRATEGY_RRORDERED, "rrordered"},
871 };
872
873 static const struct autopause {
874         int autopause;
875         const char *name;
876 } autopausesmodes [] = {
877         { QUEUE_AUTOPAUSE_OFF,"no" },
878         { QUEUE_AUTOPAUSE_ON, "yes" },
879         { QUEUE_AUTOPAUSE_ALL,"all" },
880 };
881
882
883 static struct ast_taskprocessor *devicestate_tps;
884
885 #define DEFAULT_RETRY           5
886 #define DEFAULT_TIMEOUT         15
887 #define RECHECK                 1               /*!< Recheck every second to see we we're at the top yet */
888 #define MAX_PERIODIC_ANNOUNCEMENTS 10           /*!< The maximum periodic announcements we can have */
889 #define DEFAULT_MIN_ANNOUNCE_FREQUENCY 15       /*!< The minimum number of seconds between position announcements \
890                                                      The default value of 15 provides backwards compatibility */
891 #define MAX_QUEUE_BUCKETS 53
892
893 #define RES_OKAY        0               /*!< Action completed */
894 #define RES_EXISTS      (-1)            /*!< Entry already exists */
895 #define RES_OUTOFMEMORY (-2)            /*!< Out of memory */
896 #define RES_NOSUCHQUEUE (-3)            /*!< No such queue */
897 #define RES_NOT_DYNAMIC (-4)            /*!< Member is not dynamic */
898
899 static char *app = "Queue";
900
901 static char *app_aqm = "AddQueueMember" ;
902
903 static char *app_rqm = "RemoveQueueMember" ;
904
905 static char *app_pqm = "PauseQueueMember" ;
906
907 static char *app_upqm = "UnpauseQueueMember" ;
908
909 static char *app_ql = "QueueLog" ;
910
911 /*! \brief Persistent Members astdb family */
912 static const char * const pm_family = "Queue/PersistentMembers";
913 /* The maximum length of each persistent member queue database entry */
914 #define PM_MAX_LEN 8192
915
916 /*! \brief queues.conf [general] option */
917 static int queue_persistent_members = 0;
918
919 /*! \brief queues.conf per-queue weight option */
920 static int use_weight = 0;
921
922 /*! \brief queues.conf [general] option */
923 static int autofill_default = 1;
924
925 /*! \brief queues.conf [general] option */
926 static int montype_default = 0;
927
928 /*! \brief queues.conf [general] option */
929 static int shared_lastcall = 1;
930
931 /*! \brief Subscription to device state change events */
932 static struct ast_event_sub *device_state_sub;
933
934 /*! \brief queues.conf [general] option */
935 static int update_cdr = 0;
936
937 enum queue_result {
938         QUEUE_UNKNOWN = 0,
939         QUEUE_TIMEOUT = 1,
940         QUEUE_JOINEMPTY = 2,
941         QUEUE_LEAVEEMPTY = 3,
942         QUEUE_JOINUNAVAIL = 4,
943         QUEUE_LEAVEUNAVAIL = 5,
944         QUEUE_FULL = 6,
945         QUEUE_CONTINUE = 7,
946 };
947
948 static const struct {
949         enum queue_result id;
950         char *text;
951 } queue_results[] = {
952         { QUEUE_UNKNOWN, "UNKNOWN" },
953         { QUEUE_TIMEOUT, "TIMEOUT" },
954         { QUEUE_JOINEMPTY,"JOINEMPTY" },
955         { QUEUE_LEAVEEMPTY, "LEAVEEMPTY" },
956         { QUEUE_JOINUNAVAIL, "JOINUNAVAIL" },
957         { QUEUE_LEAVEUNAVAIL, "LEAVEUNAVAIL" },
958         { QUEUE_FULL, "FULL" },
959         { QUEUE_CONTINUE, "CONTINUE" },
960 };
961
962 enum queue_timeout_priority {
963         TIMEOUT_PRIORITY_APP,
964         TIMEOUT_PRIORITY_CONF,
965 };
966
967 /*! \brief We define a custom "local user" structure because we
968  *  use it not only for keeping track of what is in use but
969  *  also for keeping track of who we're dialing.
970  *
971  *  There are two "links" defined in this structure, q_next and call_next.
972  *  q_next links ALL defined callattempt structures into a linked list. call_next is
973  *  a link which allows for a subset of the callattempts to be traversed. This subset
974  *  is used in wait_for_answer so that irrelevant callattempts are not traversed. This
975  *  also is helpful so that queue logs are always accurate in the case where a call to 
976  *  a member times out, especially if using the ringall strategy. 
977 */
978
979 struct callattempt {
980         struct callattempt *q_next;
981         struct callattempt *call_next;
982         struct ast_channel *chan;
983         char interface[256];
984         int stillgoing;
985         int metric;
986         time_t lastcall;
987         struct call_queue *lastqueue;
988         struct member *member;
989         /*! Saved connected party info from an AST_CONTROL_CONNECTED_LINE. */
990         struct ast_party_connected_line connected;
991         /*! TRUE if an AST_CONTROL_CONNECTED_LINE update was saved to the connected element. */
992         unsigned int pending_connected_update:1;
993         /*! TRUE if caller id is not available for connected line */
994         unsigned int dial_callerid_absent:1;
995         struct ast_aoc_decoded *aoc_s_rate_list;
996 };
997
998
999 struct queue_ent {
1000         struct call_queue *parent;             /*!< What queue is our parent */
1001         char moh[80];                          /*!< Name of musiconhold to be used */
1002         char announce[PATH_MAX];               /*!< Announcement to play for member when call is answered */
1003         char context[AST_MAX_CONTEXT];         /*!< Context when user exits queue */
1004         char digits[AST_MAX_EXTENSION];        /*!< Digits entered while in queue */
1005         int valid_digits;                      /*!< Digits entered correspond to valid extension. Exited */
1006         int pos;                               /*!< Where we are in the queue */
1007         int prio;                              /*!< Our priority */
1008         int last_pos_said;                     /*!< Last position we told the user */
1009         int ring_when_ringing;                 /*!< Should we only use ring indication when a channel is ringing? */
1010         time_t last_periodic_announce_time;    /*!< The last time we played a periodic announcement */
1011         int last_periodic_announce_sound;      /*!< The last periodic announcement we made */
1012         time_t last_pos;                       /*!< Last time we told the user their position */
1013         int opos;                              /*!< Where we started in the queue */
1014         int handled;                           /*!< Whether our call was handled */
1015         int pending;                           /*!< Non-zero if we are attempting to call a member */
1016         int max_penalty;                       /*!< Limit the members that can take this call to this penalty or lower */
1017         int min_penalty;                       /*!< Limit the members that can take this call to this penalty or higher */
1018         int linpos;                            /*!< If using linear strategy, what position are we at? */
1019         int linwrapped;                        /*!< Is the linpos wrapped? */
1020         time_t start;                          /*!< When we started holding */
1021         time_t expire;                         /*!< When this entry should expire (time out of queue) */
1022         int cancel_answered_elsewhere;         /*!< Whether we should force the CAE flag on this call (C) option*/
1023         struct ast_channel *chan;              /*!< Our channel */
1024         AST_LIST_HEAD_NOLOCK(,penalty_rule) qe_rules; /*!< Local copy of the queue's penalty rules */
1025         struct penalty_rule *pr;               /*!< Pointer to the next penalty rule to implement */
1026         struct queue_ent *next;                /*!< The next queue entry */
1027 };
1028
1029 struct member {
1030         char interface[80];                  /*!< Technology/Location to dial to reach this member*/
1031         char state_exten[AST_MAX_EXTENSION]; /*!< Extension to get state from (if using hint) */
1032         char state_context[AST_MAX_CONTEXT]; /*!< Context to use when getting state (if using hint) */
1033         char state_interface[80];            /*!< Technology/Location from which to read devicestate changes */
1034         char membername[80];                 /*!< Member name to use in queue logs */
1035         int penalty;                         /*!< Are we a last resort? */
1036         int calls;                           /*!< Number of calls serviced by this member */
1037         int dynamic;                         /*!< Are we dynamically added? */
1038         int realtime;                        /*!< Is this member realtime? */
1039         int status;                          /*!< Status of queue member */
1040         int paused;                          /*!< Are we paused (not accepting calls)? */
1041         time_t lastcall;                     /*!< When last successful call was hungup */
1042         struct call_queue *lastqueue;        /*!< Last queue we received a call */
1043         unsigned int dead:1;                 /*!< Used to detect members deleted in realtime */
1044         unsigned int delme:1;                /*!< Flag to delete entry on reload */
1045         char rt_uniqueid[80];                /*!< Unique id of realtime member entry */
1046 };
1047
1048 enum empty_conditions {
1049         QUEUE_EMPTY_PENALTY = (1 << 0),
1050         QUEUE_EMPTY_PAUSED = (1 << 1),
1051         QUEUE_EMPTY_INUSE = (1 << 2),
1052         QUEUE_EMPTY_RINGING = (1 << 3),
1053         QUEUE_EMPTY_UNAVAILABLE = (1 << 4),
1054         QUEUE_EMPTY_INVALID = (1 << 5),
1055         QUEUE_EMPTY_UNKNOWN = (1 << 6),
1056         QUEUE_EMPTY_WRAPUP = (1 << 7),
1057 };
1058
1059 /* values used in multi-bit flags in call_queue */
1060 #define ANNOUNCEHOLDTIME_ALWAYS 1
1061 #define ANNOUNCEHOLDTIME_ONCE 2
1062 #define QUEUE_EVENT_VARIABLES 3
1063
1064 struct penalty_rule {
1065         int time;                           /*!< Number of seconds that need to pass before applying this rule */
1066         int max_value;                      /*!< The amount specified in the penalty rule for max penalty */
1067         int min_value;                      /*!< The amount specified in the penalty rule for min penalty */
1068         int max_relative;                   /*!< Is the max adjustment relative? 1 for relative, 0 for absolute */
1069         int min_relative;                   /*!< Is the min adjustment relative? 1 for relative, 0 for absolute */
1070         AST_LIST_ENTRY(penalty_rule) list;  /*!< Next penalty_rule */
1071 };
1072
1073 #define ANNOUNCEPOSITION_YES 1 /*!< We announce position */
1074 #define ANNOUNCEPOSITION_NO 2 /*!< We don't announce position */
1075 #define ANNOUNCEPOSITION_MORE_THAN 3 /*!< We say "Currently there are more than <limit>" */
1076 #define ANNOUNCEPOSITION_LIMIT 4 /*!< We not announce position more than <limit> */
1077
1078 struct call_queue {
1079         AST_DECLARE_STRING_FIELDS(
1080                 /*! Queue name */
1081                 AST_STRING_FIELD(name);
1082                 /*! Music on Hold class */
1083                 AST_STRING_FIELD(moh);
1084                 /*! Announcement to play when call is answered */
1085                 AST_STRING_FIELD(announce);
1086                 /*! Exit context */
1087                 AST_STRING_FIELD(context);
1088                 /*! Macro to run upon member connection */
1089                 AST_STRING_FIELD(membermacro);
1090                 /*! Gosub to run upon member connection */
1091                 AST_STRING_FIELD(membergosub);
1092                 /*! Default rule to use if none specified in call to Queue() */
1093                 AST_STRING_FIELD(defaultrule);
1094                 /*! Sound file: "Your call is now first in line" (def. queue-youarenext) */
1095                 AST_STRING_FIELD(sound_next);
1096                 /*! Sound file: "There are currently" (def. queue-thereare) */
1097                 AST_STRING_FIELD(sound_thereare);
1098                 /*! Sound file: "calls waiting to speak to a representative." (def. queue-callswaiting) */
1099                 AST_STRING_FIELD(sound_calls);
1100                 /*! Sound file: "Currently there are more than" (def. queue-quantity1) */
1101                 AST_STRING_FIELD(queue_quantity1);
1102                 /*! Sound file: "callers waiting to speak with a representative" (def. queue-quantity2) */
1103                 AST_STRING_FIELD(queue_quantity2);
1104                 /*! Sound file: "The current estimated total holdtime is" (def. queue-holdtime) */
1105                 AST_STRING_FIELD(sound_holdtime);
1106                 /*! Sound file: "minutes." (def. queue-minutes) */
1107                 AST_STRING_FIELD(sound_minutes);
1108                 /*! Sound file: "minute." (def. queue-minute) */
1109                 AST_STRING_FIELD(sound_minute);
1110                 /*! Sound file: "seconds." (def. queue-seconds) */
1111                 AST_STRING_FIELD(sound_seconds);
1112                 /*! Sound file: "Thank you for your patience." (def. queue-thankyou) */
1113                 AST_STRING_FIELD(sound_thanks);
1114                 /*! Sound file: Custom announce for caller, no default */
1115                 AST_STRING_FIELD(sound_callerannounce);
1116                 /*! Sound file: "Hold time" (def. queue-reporthold) */
1117                 AST_STRING_FIELD(sound_reporthold);
1118         );
1119         /*! Sound files: Custom announce, no default */
1120         struct ast_str *sound_periodicannounce[MAX_PERIODIC_ANNOUNCEMENTS];
1121         unsigned int dead:1;
1122         unsigned int eventwhencalled:2;
1123         unsigned int ringinuse:1;
1124         unsigned int setinterfacevar:1;
1125         unsigned int setqueuevar:1;
1126         unsigned int setqueueentryvar:1;
1127         unsigned int reportholdtime:1;
1128         unsigned int wrapped:1;
1129         unsigned int timeoutrestart:1;
1130         unsigned int announceholdtime:2;
1131         unsigned int announceposition:3;
1132         int strategy:4;
1133         unsigned int maskmemberstatus:1;
1134         unsigned int realtime:1;
1135         unsigned int found:1;
1136         unsigned int relativeperiodicannounce:1;
1137         enum empty_conditions joinempty;
1138         enum empty_conditions leavewhenempty;
1139         int announcepositionlimit;          /*!< How many positions we announce? */
1140         int announcefrequency;              /*!< How often to announce their position */
1141         int minannouncefrequency;           /*!< The minimum number of seconds between position announcements (def. 15) */
1142         int periodicannouncefrequency;      /*!< How often to play periodic announcement */
1143         int numperiodicannounce;            /*!< The number of periodic announcements configured */
1144         int randomperiodicannounce;         /*!< Are periodic announcments randomly chosen */
1145         int roundingseconds;                /*!< How many seconds do we round to? */
1146         int holdtime;                       /*!< Current avg holdtime, based on an exponential average */
1147         int talktime;                       /*!< Current avg talktime, based on the same exponential average */
1148         int callscompleted;                 /*!< Number of queue calls completed */
1149         int callsabandoned;                 /*!< Number of queue calls abandoned */
1150         int servicelevel;                   /*!< seconds setting for servicelevel*/
1151         int callscompletedinsl;             /*!< Number of calls answered with servicelevel*/
1152         char monfmt[8];                     /*!< Format to use when recording calls */
1153         int montype;                        /*!< Monitor type  Monitor vs. MixMonitor */
1154         int count;                          /*!< How many entries */
1155         int maxlen;                         /*!< Max number of entries */
1156         int wrapuptime;                     /*!< Wrapup Time */
1157         int penaltymemberslimit;            /*!< Disregard penalty when queue has fewer than this many members */
1158
1159         int retry;                          /*!< Retry calling everyone after this amount of time */
1160         int timeout;                        /*!< How long to wait for an answer */
1161         int weight;                         /*!< Respective weight */
1162         int autopause;                      /*!< Auto pause queue members if they fail to answer */
1163         int timeoutpriority;                /*!< Do we allow a fraction of the timeout to occur for a ring? */
1164
1165         /* Queue strategy things */
1166         int rrpos;                          /*!< Round Robin - position */
1167         int memberdelay;                    /*!< Seconds to delay connecting member to caller */
1168         int autofill;                       /*!< Ignore the head call status and ring an available agent */
1169         
1170         struct ao2_container *members;             /*!< Head of the list of members */
1171         /*! 
1172          * \brief Number of members _logged in_
1173          * \note There will be members in the members container that are not logged
1174          *       in, so this can not simply be replaced with ao2_container_count(). 
1175          */
1176         int membercount;
1177         struct queue_ent *head;             /*!< Head of the list of callers */
1178         AST_LIST_ENTRY(call_queue) list;    /*!< Next call queue */
1179         AST_LIST_HEAD_NOLOCK(, penalty_rule) rules; /*!< The list of penalty rules to invoke */
1180 };
1181
1182 struct rule_list {
1183         char name[80];
1184         AST_LIST_HEAD_NOLOCK(,penalty_rule) rules;
1185         AST_LIST_ENTRY(rule_list) list;
1186 };
1187
1188 static AST_LIST_HEAD_STATIC(rule_lists, rule_list);
1189
1190 static struct ao2_container *queues;
1191
1192 static void update_realtime_members(struct call_queue *q);
1193 static int set_member_paused(const char *queuename, const char *interface, const char *reason, int paused);
1194
1195 static void queue_transfer_fixup(void *data, struct ast_channel *old_chan, struct ast_channel *new_chan); 
1196 /*! \brief sets the QUEUESTATUS channel variable */
1197 static void set_queue_result(struct ast_channel *chan, enum queue_result res)
1198 {
1199         int i;
1200
1201         for (i = 0; i < ARRAY_LEN(queue_results); i++) {
1202                 if (queue_results[i].id == res) {
1203                         pbx_builtin_setvar_helper(chan, "QUEUESTATUS", queue_results[i].text);
1204                         return;
1205                 }
1206         }
1207 }
1208
1209 static const char *int2strat(int strategy)
1210 {
1211         int x;
1212
1213         for (x = 0; x < ARRAY_LEN(strategies); x++) {
1214                 if (strategy == strategies[x].strategy)
1215                         return strategies[x].name;
1216         }
1217
1218         return "<unknown>";
1219 }
1220
1221 static int strat2int(const char *strategy)
1222 {
1223         int x;
1224
1225         for (x = 0; x < ARRAY_LEN(strategies); x++) {
1226                 if (!strcasecmp(strategy, strategies[x].name))
1227                         return strategies[x].strategy;
1228         }
1229
1230         return -1;
1231 }
1232
1233 static int autopause2int(const char *autopause)
1234 {
1235         int x;
1236         /*This 'double check' that default value is OFF */
1237         if (ast_strlen_zero(autopause))
1238                 return QUEUE_AUTOPAUSE_OFF;
1239
1240         /*This 'double check' is to ensure old values works */
1241         if(ast_true(autopause))
1242                 return QUEUE_AUTOPAUSE_ON;
1243
1244         for (x = 0; x < ARRAY_LEN(autopausesmodes); x++) {
1245                 if (!strcasecmp(autopause, autopausesmodes[x].name))
1246                         return autopausesmodes[x].autopause;
1247         }
1248
1249         /*This 'double check' that default value is OFF */
1250         return QUEUE_AUTOPAUSE_OFF;
1251 }
1252
1253 static int queue_hash_cb(const void *obj, const int flags)
1254 {
1255         const struct call_queue *q = obj;
1256
1257         return ast_str_case_hash(q->name);
1258 }
1259
1260 static int queue_cmp_cb(void *obj, void *arg, int flags)
1261 {
1262         struct call_queue *q = obj, *q2 = arg;
1263         return !strcasecmp(q->name, q2->name) ? CMP_MATCH | CMP_STOP : 0;
1264 }
1265
1266 #ifdef REF_DEBUG_ONLY_QUEUES
1267 #define queue_ref(a)    __ao2_ref_debug(a,1,"",__FILE__,__LINE__,__PRETTY_FUNCTION__)
1268 #define queue_unref(a)  __ao2_ref_debug(a,-1,"",__FILE__,__LINE__,__PRETTY_FUNCTION__)
1269 #define queue_t_ref(a,b)        __ao2_ref_debug(a,1,b,__FILE__,__LINE__,__PRETTY_FUNCTION__)
1270 #define queue_t_unref(a,b)      __ao2_ref_debug(a,-1,b,__FILE__,__LINE__,__PRETTY_FUNCTION__)
1271 #define queues_t_link(c,q,tag)  __ao2_link_debug(c,q,tag,__FILE__,__LINE__,__PRETTY_FUNCTION__)
1272 #define queues_t_unlink(c,q,tag)        __ao2_unlink_debug(c,q,tag,__FILE__,__LINE__,__PRETTY_FUNCTION__)
1273 #else
1274 #define queue_t_ref(a,b)        queue_ref(a)
1275 #define queue_t_unref(a,b)      queue_unref(a)
1276 #define queues_t_link(c,q,tag)  ao2_t_link(c,q,tag)
1277 #define queues_t_unlink(c,q,tag)        ao2_t_unlink(c,q,tag)
1278 static inline struct call_queue *queue_ref(struct call_queue *q)
1279 {
1280         ao2_ref(q, 1);
1281         return q;
1282 }
1283
1284 static inline struct call_queue *queue_unref(struct call_queue *q)
1285 {
1286         ao2_ref(q, -1);
1287         return q;
1288 }
1289 #endif
1290
1291 /*! \brief Set variables of queue */
1292 static void set_queue_variables(struct call_queue *q, struct ast_channel *chan)
1293 {
1294         char interfacevar[256]="";
1295         float sl = 0;
1296
1297         ao2_lock(q);
1298
1299         if (q->setqueuevar) {
1300                 sl = 0;
1301                 if (q->callscompleted > 0) 
1302                         sl = 100 * ((float) q->callscompletedinsl / (float) q->callscompleted);
1303
1304                 snprintf(interfacevar, sizeof(interfacevar),
1305                         "QUEUENAME=%s,QUEUEMAX=%d,QUEUESTRATEGY=%s,QUEUECALLS=%d,QUEUEHOLDTIME=%d,QUEUETALKTIME=%d,QUEUECOMPLETED=%d,QUEUEABANDONED=%d,QUEUESRVLEVEL=%d,QUEUESRVLEVELPERF=%2.1f",
1306                         q->name, q->maxlen, int2strat(q->strategy), q->count, q->holdtime, q->talktime, q->callscompleted, q->callsabandoned,  q->servicelevel, sl);
1307
1308                 ao2_unlock(q);
1309         
1310                 pbx_builtin_setvar_multiple(chan, interfacevar); 
1311         } else {
1312                 ao2_unlock(q);
1313         }
1314 }
1315
1316 /*! \brief Insert the 'new' entry after the 'prev' entry of queue 'q' */
1317 static inline void insert_entry(struct call_queue *q, struct queue_ent *prev, struct queue_ent *new, int *pos)
1318 {
1319         struct queue_ent *cur;
1320
1321         if (!q || !new)
1322                 return;
1323         if (prev) {
1324                 cur = prev->next;
1325                 prev->next = new;
1326         } else {
1327                 cur = q->head;
1328                 q->head = new;
1329         }
1330         new->next = cur;
1331
1332         /* every queue_ent must have a reference to it's parent call_queue, this
1333          * reference does not go away until the end of the queue_ent's life, meaning
1334          * that even when the queue_ent leaves the call_queue this ref must remain. */
1335         queue_ref(q);
1336         new->parent = q;
1337         new->pos = ++(*pos);
1338         new->opos = *pos;
1339 }
1340
1341 /*! \brief Check if members are available
1342  *
1343  * This function checks to see if members are available to be called. If any member
1344  * is available, the function immediately returns 0. If no members are available,
1345  * then -1 is returned.
1346  */
1347 static int get_member_status(struct call_queue *q, int max_penalty, int min_penalty, enum empty_conditions conditions)
1348 {
1349         struct member *member;
1350         struct ao2_iterator mem_iter;
1351
1352         ao2_lock(q);
1353         mem_iter = ao2_iterator_init(q->members, 0);
1354         for (; (member = ao2_iterator_next(&mem_iter)); ao2_ref(member, -1)) {
1355                 if ((max_penalty && (member->penalty > max_penalty)) || (min_penalty && (member->penalty < min_penalty))) {
1356                         if (conditions & QUEUE_EMPTY_PENALTY) {
1357                                 ast_debug(4, "%s is unavailable because his penalty is not between %d and %d\n", member->membername, min_penalty, max_penalty);
1358                                 continue;
1359                         }
1360                 }
1361
1362                 switch (member->status) {
1363                 case AST_DEVICE_INVALID:
1364                         if (conditions & QUEUE_EMPTY_INVALID) {
1365                                 ast_debug(4, "%s is unavailable because his device state is 'invalid'\n", member->membername);
1366                                 break;
1367                         }
1368                         goto default_case;
1369                 case AST_DEVICE_UNAVAILABLE:
1370                         if (conditions & QUEUE_EMPTY_UNAVAILABLE) {
1371                                 ast_debug(4, "%s is unavailable because his device state is 'unavailable'\n", member->membername);
1372                                 break;
1373                         }
1374                         goto default_case;
1375                 case AST_DEVICE_INUSE:
1376                         if (conditions & QUEUE_EMPTY_INUSE) {
1377                                 ast_debug(4, "%s is unavailable because his device state is 'inuse'\n", member->membername);
1378                                 break;
1379                         }
1380                         goto default_case;
1381                 case AST_DEVICE_RINGING:
1382                         if (conditions & QUEUE_EMPTY_RINGING) {
1383                                 ast_debug(4, "%s is unavailable because his device state is 'ringing'\n", member->membername);
1384                                 break;
1385                         }
1386                         goto default_case;
1387                 case AST_DEVICE_UNKNOWN:
1388                         if (conditions & QUEUE_EMPTY_UNKNOWN) {
1389                                 ast_debug(4, "%s is unavailable because his device state is 'unknown'\n", member->membername);
1390                                 break;
1391                         }
1392                         /* Fall-through */
1393                 default:
1394                 default_case:
1395                         if (member->paused && (conditions & QUEUE_EMPTY_PAUSED)) {
1396                                 ast_debug(4, "%s is unavailable because he is paused'\n", member->membername);
1397                                 break;
1398                         } else if ((conditions & QUEUE_EMPTY_WRAPUP) && member->lastcall && q->wrapuptime && (time(NULL) - q->wrapuptime < member->lastcall)) {
1399                                 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);
1400                                 break;
1401                         } else {
1402                                 ao2_unlock(q);
1403                                 ao2_ref(member, -1);
1404                                 ao2_iterator_destroy(&mem_iter);
1405                                 ast_debug(4, "%s is available.\n", member->membername);
1406                                 return 0;
1407                         }
1408                         break;
1409                 }
1410         }
1411         ao2_iterator_destroy(&mem_iter);
1412
1413         ao2_unlock(q);
1414         return -1;
1415 }
1416
1417 struct statechange {
1418         AST_LIST_ENTRY(statechange) entry;
1419         int state;
1420         char dev[0];
1421 };
1422
1423 /*! \brief set a member's status based on device state of that member's state_interface.
1424  *  
1425  * Lock interface list find sc, iterate through each queues queue_member list for member to
1426  * update state inside queues
1427 */
1428 static int update_status(struct call_queue *q, struct member *m, const int status)
1429 {
1430         m->status = status;
1431
1432         if (q->maskmemberstatus)
1433                 return 0;
1434
1435         manager_event(EVENT_FLAG_AGENT, "QueueMemberStatus",
1436                 "Queue: %s\r\n"
1437                 "Location: %s\r\n"
1438                 "MemberName: %s\r\n"
1439                 "Membership: %s\r\n"
1440                 "Penalty: %d\r\n"
1441                 "CallsTaken: %d\r\n"
1442                 "LastCall: %d\r\n"
1443                 "Status: %d\r\n"
1444                 "Paused: %d\r\n",
1445                 q->name, m->interface, m->membername, m->dynamic ? "dynamic" : m->realtime ? "realtime" : "static",
1446                 m->penalty, m->calls, (int)m->lastcall, m->status, m->paused
1447         );
1448
1449         return 0;
1450 }
1451
1452 /*! \brief set a member's status based on device state of that member's interface*/
1453 static int handle_statechange(void *datap)
1454 {
1455         struct statechange *sc = datap;
1456         struct ao2_iterator miter, qiter;
1457         struct member *m;
1458         struct call_queue *q;
1459         char interface[80], *slash_pos;
1460         int found = 0;
1461
1462         qiter = ao2_iterator_init(queues, 0);
1463         while ((q = ao2_t_iterator_next(&qiter, "Iterate over queues"))) {
1464                 ao2_lock(q);
1465
1466                 miter = ao2_iterator_init(q->members, 0);
1467                 for (; (m = ao2_iterator_next(&miter)); ao2_ref(m, -1)) {
1468                         ast_copy_string(interface, m->state_interface, sizeof(interface));
1469
1470                         if ((slash_pos = strchr(interface, '/')))
1471                                 if (!strncasecmp(interface, "Local/", 6) && (slash_pos = strchr(slash_pos + 1, '/')))
1472                                         *slash_pos = '\0';
1473
1474                         if (!strcasecmp(interface, sc->dev)) {
1475                                 found = 1;
1476                                 update_status(q, m, sc->state);
1477                                 ao2_ref(m, -1);
1478                                 break;
1479                         }
1480                 }
1481                 ao2_iterator_destroy(&miter);
1482
1483                 ao2_unlock(q);
1484                 queue_t_unref(q, "Done with iterator");
1485         }
1486         ao2_iterator_destroy(&qiter);
1487
1488         if (found)
1489                 ast_debug(1, "Device '%s' changed to state '%d' (%s)\n", sc->dev, sc->state, ast_devstate2str(sc->state));
1490         else
1491                 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));
1492
1493         ast_free(sc);
1494         return 0;
1495 }
1496
1497 static void device_state_cb(const struct ast_event *event, void *unused)
1498 {
1499         enum ast_device_state state;
1500         const char *device;
1501         struct statechange *sc;
1502         size_t datapsize;
1503
1504         state = ast_event_get_ie_uint(event, AST_EVENT_IE_STATE);
1505         device = ast_event_get_ie_str(event, AST_EVENT_IE_DEVICE);
1506
1507         if (ast_strlen_zero(device)) {
1508                 ast_log(LOG_ERROR, "Received invalid event that had no device IE\n");
1509                 return;
1510         }
1511         datapsize = sizeof(*sc) + strlen(device) + 1;
1512         if (!(sc = ast_calloc(1, datapsize))) {
1513                 ast_log(LOG_ERROR, "failed to calloc a state change struct\n");
1514                 return;
1515         }
1516         sc->state = state;
1517         strcpy(sc->dev, device);
1518         if (ast_taskprocessor_push(devicestate_tps, handle_statechange, sc) < 0) {
1519                 ast_free(sc);
1520         }
1521 }
1522
1523 /*! \brief Helper function which converts from extension state to device state values */
1524 static int extensionstate2devicestate(int state)
1525 {
1526         switch (state) {
1527         case AST_EXTENSION_NOT_INUSE:
1528                 state = AST_DEVICE_NOT_INUSE;
1529                 break;
1530         case AST_EXTENSION_INUSE:
1531                 state = AST_DEVICE_INUSE;
1532                 break;
1533         case AST_EXTENSION_BUSY:
1534                 state = AST_DEVICE_BUSY;
1535                 break;
1536         case AST_EXTENSION_RINGING:
1537                 state = AST_DEVICE_RINGING;
1538                 break;
1539         case AST_EXTENSION_ONHOLD:
1540                 state = AST_DEVICE_ONHOLD;
1541                 break;
1542         case AST_EXTENSION_UNAVAILABLE:
1543                 state = AST_DEVICE_UNAVAILABLE;
1544                 break;
1545         case AST_EXTENSION_REMOVED:
1546         case AST_EXTENSION_DEACTIVATED:
1547         default:
1548                 state = AST_DEVICE_INVALID;
1549                 break;
1550         }
1551
1552         return state;
1553 }
1554
1555 static int extension_state_cb(char *context, char *exten, enum ast_extension_states state, void *data)
1556 {
1557         struct ao2_iterator miter, qiter;
1558         struct member *m;
1559         struct call_queue *q;
1560         int found = 0, device_state = extensionstate2devicestate(state);
1561
1562         qiter = ao2_iterator_init(queues, 0);
1563         while ((q = ao2_t_iterator_next(&qiter, "Iterate through queues"))) {
1564                 ao2_lock(q);
1565
1566                 miter = ao2_iterator_init(q->members, 0);
1567                 for (; (m = ao2_iterator_next(&miter)); ao2_ref(m, -1)) {
1568                         if (!strcmp(m->state_context, context) && !strcmp(m->state_exten, exten)) {
1569                                 update_status(q, m, device_state);
1570                                 ao2_ref(m, -1);
1571                                 found = 1;
1572                                 break;
1573                         }
1574                 }
1575                 ao2_iterator_destroy(&miter);
1576
1577                 ao2_unlock(q);
1578                 queue_t_unref(q, "Done with iterator");
1579         }
1580         ao2_iterator_destroy(&qiter);
1581
1582         if (found) {
1583                 ast_debug(1, "Extension '%s@%s' changed to state '%d' (%s)\n", exten, context, device_state, ast_devstate2str(device_state));
1584         } else {
1585                 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",
1586                           exten, context, device_state, ast_devstate2str(device_state));
1587         }
1588
1589         return 0;
1590 }
1591
1592 /*! \brief Return the current state of a member */
1593 static int get_queue_member_status(struct member *cur)
1594 {
1595         return ast_strlen_zero(cur->state_exten) ? ast_device_state(cur->state_interface) : extensionstate2devicestate(ast_extension_state(NULL, cur->state_context, cur->state_exten));
1596 }
1597
1598 /*! \brief allocate space for new queue member and set fields based on parameters passed */
1599 static struct member *create_queue_member(const char *interface, const char *membername, int penalty, int paused, const char *state_interface)
1600 {
1601         struct member *cur;
1602         
1603         if ((cur = ao2_alloc(sizeof(*cur), NULL))) {
1604                 cur->penalty = penalty;
1605                 cur->paused = paused;
1606                 ast_copy_string(cur->interface, interface, sizeof(cur->interface));
1607                 if (!ast_strlen_zero(state_interface))
1608                         ast_copy_string(cur->state_interface, state_interface, sizeof(cur->state_interface));
1609                 else
1610                         ast_copy_string(cur->state_interface, interface, sizeof(cur->state_interface));
1611                 if (!ast_strlen_zero(membername))
1612                         ast_copy_string(cur->membername, membername, sizeof(cur->membername));
1613                 else
1614                         ast_copy_string(cur->membername, interface, sizeof(cur->membername));
1615                 if (!strchr(cur->interface, '/'))
1616                         ast_log(LOG_WARNING, "No location at interface '%s'\n", interface);
1617                 if (!strncmp(cur->state_interface, "hint:", 5)) {
1618                         char *tmp = ast_strdupa(cur->state_interface), *context = tmp;
1619                         char *exten = strsep(&context, "@") + 5;
1620
1621                         ast_copy_string(cur->state_exten, exten, sizeof(cur->state_exten));
1622                         ast_copy_string(cur->state_context, S_OR(context, "default"), sizeof(cur->state_context));
1623                 }
1624                 cur->status = get_queue_member_status(cur);
1625         }
1626
1627         return cur;
1628 }
1629
1630
1631 static int compress_char(const char c)
1632 {
1633         if (c < 32)
1634                 return 0;
1635         else if (c > 96)
1636                 return c - 64;
1637         else
1638                 return c - 32;
1639 }
1640
1641 static int member_hash_fn(const void *obj, const int flags)
1642 {
1643         const struct member *mem = obj;
1644         const char *chname = strchr(mem->interface, '/');
1645         int ret = 0, i;
1646         if (!chname)
1647                 chname = mem->interface;
1648         for (i = 0; i < 5 && chname[i]; i++)
1649                 ret += compress_char(chname[i]) << (i * 6);
1650         return ret;
1651 }
1652
1653 static int member_cmp_fn(void *obj1, void *obj2, int flags)
1654 {
1655         struct member *mem1 = obj1, *mem2 = obj2;
1656         return strcasecmp(mem1->interface, mem2->interface) ? 0 : CMP_MATCH | CMP_STOP;
1657 }
1658
1659 /*! 
1660  * \brief Initialize Queue default values.
1661  * \note the queue's lock  must be held before executing this function
1662 */
1663 static void init_queue(struct call_queue *q)
1664 {
1665         int i;
1666         struct penalty_rule *pr_iter;
1667
1668         q->dead = 0;
1669         q->retry = DEFAULT_RETRY;
1670         q->timeout = DEFAULT_TIMEOUT;
1671         q->maxlen = 0;
1672         q->announcefrequency = 0;
1673         q->minannouncefrequency = DEFAULT_MIN_ANNOUNCE_FREQUENCY;
1674         q->announceholdtime = 1;
1675         q->announcepositionlimit = 10; /* Default 10 positions */
1676         q->announceposition = ANNOUNCEPOSITION_YES; /* Default yes */
1677         q->roundingseconds = 0; /* Default - don't announce seconds */
1678         q->servicelevel = 0;
1679         q->ringinuse = 1;
1680         q->setinterfacevar = 0;
1681         q->setqueuevar = 0;
1682         q->setqueueentryvar = 0;
1683         q->autofill = autofill_default;
1684         q->montype = montype_default;
1685         q->monfmt[0] = '\0';
1686         q->reportholdtime = 0;
1687         q->wrapuptime = 0;
1688         q->penaltymemberslimit = 0;
1689         q->joinempty = 0;
1690         q->leavewhenempty = 0;
1691         q->memberdelay = 0;
1692         q->maskmemberstatus = 0;
1693         q->eventwhencalled = 0;
1694         q->weight = 0;
1695         q->timeoutrestart = 0;
1696         q->periodicannouncefrequency = 0;
1697         q->randomperiodicannounce = 0;
1698         q->numperiodicannounce = 0;
1699         q->autopause = QUEUE_AUTOPAUSE_OFF;
1700         q->timeoutpriority = TIMEOUT_PRIORITY_APP;
1701         if (!q->members) {
1702                 if (q->strategy == QUEUE_STRATEGY_LINEAR || q->strategy == QUEUE_STRATEGY_RRORDERED)
1703                         /* linear strategy depends on order, so we have to place all members in a single bucket */
1704                         q->members = ao2_container_alloc(1, member_hash_fn, member_cmp_fn);
1705                 else
1706                         q->members = ao2_container_alloc(37, member_hash_fn, member_cmp_fn);
1707         }
1708         q->found = 1;
1709
1710         ast_string_field_set(q, sound_next, "queue-youarenext");
1711         ast_string_field_set(q, sound_thereare, "queue-thereare");
1712         ast_string_field_set(q, sound_calls, "queue-callswaiting");
1713         ast_string_field_set(q, queue_quantity1, "queue-quantity1");
1714         ast_string_field_set(q, queue_quantity2, "queue-quantity2");
1715         ast_string_field_set(q, sound_holdtime, "queue-holdtime");
1716         ast_string_field_set(q, sound_minutes, "queue-minutes");
1717         ast_string_field_set(q, sound_minute, "queue-minute");
1718         ast_string_field_set(q, sound_seconds, "queue-seconds");
1719         ast_string_field_set(q, sound_thanks, "queue-thankyou");
1720         ast_string_field_set(q, sound_reporthold, "queue-reporthold");
1721
1722         if ((q->sound_periodicannounce[0] = ast_str_create(32)))
1723                 ast_str_set(&q->sound_periodicannounce[0], 0, "queue-periodic-announce");
1724
1725         for (i = 1; i < MAX_PERIODIC_ANNOUNCEMENTS; i++) {
1726                 if (q->sound_periodicannounce[i])
1727                         ast_str_set(&q->sound_periodicannounce[i], 0, "%s", "");
1728         }
1729
1730         while ((pr_iter = AST_LIST_REMOVE_HEAD(&q->rules,list)))
1731                 ast_free(pr_iter);
1732 }
1733
1734 static void clear_queue(struct call_queue *q)
1735 {
1736         q->holdtime = 0;
1737         q->callscompleted = 0;
1738         q->callsabandoned = 0;
1739         q->callscompletedinsl = 0;
1740         q->talktime = 0;
1741
1742         if (q->members) {
1743                 struct member *mem;
1744                 struct ao2_iterator mem_iter = ao2_iterator_init(q->members, 0);
1745                 while ((mem = ao2_iterator_next(&mem_iter))) {
1746                         mem->calls = 0;
1747                         mem->lastcall = 0;
1748                         ao2_ref(mem, -1);
1749                 }
1750                 ao2_iterator_destroy(&mem_iter);
1751         }
1752 }
1753
1754 /*! 
1755  * \brief Change queue penalty by adding rule.
1756  *
1757  * Check rule for errors with time or fomatting, see if rule is relative to rest 
1758  * of queue, iterate list of rules to find correct insertion point, insert and return.
1759  * \retval -1 on failure
1760  * \retval 0 on success 
1761  * \note Call this with the rule_lists locked 
1762 */
1763 static int insert_penaltychange (const char *list_name, const char *content, const int linenum)
1764 {
1765         char *timestr, *maxstr, *minstr, *contentdup;
1766         struct penalty_rule *rule = NULL, *rule_iter;
1767         struct rule_list *rl_iter;
1768         int penaltychangetime, inserted = 0;
1769
1770         if (!(rule = ast_calloc(1, sizeof(*rule)))) {
1771                 return -1;
1772         }
1773
1774         contentdup = ast_strdupa(content);
1775         
1776         if (!(maxstr = strchr(contentdup, ','))) {
1777                 ast_log(LOG_WARNING, "Improperly formatted penaltychange rule at line %d. Ignoring.\n", linenum);
1778                 ast_free(rule);
1779                 return -1;
1780         }
1781
1782         *maxstr++ = '\0';
1783         timestr = contentdup;
1784
1785         if ((penaltychangetime = atoi(timestr)) < 0) {
1786                 ast_log(LOG_WARNING, "Improper time parameter specified for penaltychange rule at line %d. Ignoring.\n", linenum);
1787                 ast_free(rule);
1788                 return -1;
1789         }
1790
1791         rule->time = penaltychangetime;
1792
1793         if ((minstr = strchr(maxstr,',')))
1794                 *minstr++ = '\0';
1795         
1796         /* The last check will evaluate true if either no penalty change is indicated for a given rule
1797          * OR if a min penalty change is indicated but no max penalty change is */
1798         if (*maxstr == '+' || *maxstr == '-' || *maxstr == '\0') {
1799                 rule->max_relative = 1;
1800         }
1801
1802         rule->max_value = atoi(maxstr);
1803
1804         if (!ast_strlen_zero(minstr)) {
1805                 if (*minstr == '+' || *minstr == '-')
1806                         rule->min_relative = 1;
1807                 rule->min_value = atoi(minstr);
1808         } else /*there was no minimum specified, so assume this means no change*/
1809                 rule->min_relative = 1;
1810
1811         /*We have the rule made, now we need to insert it where it belongs*/
1812         AST_LIST_TRAVERSE(&rule_lists, rl_iter, list){
1813                 if (strcasecmp(rl_iter->name, list_name))
1814                         continue;
1815
1816                 AST_LIST_TRAVERSE_SAFE_BEGIN(&rl_iter->rules, rule_iter, list) {
1817                         if (rule->time < rule_iter->time) {
1818                                 AST_LIST_INSERT_BEFORE_CURRENT(rule, list);
1819                                 inserted = 1;
1820                                 break;
1821                         }
1822                 }
1823                 AST_LIST_TRAVERSE_SAFE_END;
1824         
1825                 if (!inserted) {
1826                         AST_LIST_INSERT_TAIL(&rl_iter->rules, rule, list);
1827                 }
1828         }
1829
1830         return 0;
1831 }
1832
1833 static void parse_empty_options(const char *value, enum empty_conditions *empty, int joinempty)
1834 {
1835         char *value_copy = ast_strdupa(value);
1836         char *option = NULL;
1837         while ((option = strsep(&value_copy, ","))) {
1838                 if (!strcasecmp(option, "paused")) {
1839                         *empty |= QUEUE_EMPTY_PAUSED;
1840                 } else if (!strcasecmp(option, "penalty")) {
1841                         *empty |= QUEUE_EMPTY_PENALTY;
1842                 } else if (!strcasecmp(option, "inuse")) {
1843                         *empty |= QUEUE_EMPTY_INUSE;
1844                 } else if (!strcasecmp(option, "ringing")) {
1845                         *empty |= QUEUE_EMPTY_RINGING;
1846                 } else if (!strcasecmp(option, "invalid")) {
1847                         *empty |= QUEUE_EMPTY_INVALID;
1848                 } else if (!strcasecmp(option, "wrapup")) {
1849                         *empty |= QUEUE_EMPTY_WRAPUP;
1850                 } else if (!strcasecmp(option, "unavailable")) {
1851                         *empty |= QUEUE_EMPTY_UNAVAILABLE;
1852                 } else if (!strcasecmp(option, "unknown")) {
1853                         *empty |= QUEUE_EMPTY_UNKNOWN;
1854                 } else if (!strcasecmp(option, "loose")) {
1855                         *empty = (QUEUE_EMPTY_PENALTY | QUEUE_EMPTY_INVALID);
1856                 } else if (!strcasecmp(option, "strict")) {
1857                         *empty = (QUEUE_EMPTY_PENALTY | QUEUE_EMPTY_INVALID | QUEUE_EMPTY_PAUSED | QUEUE_EMPTY_UNAVAILABLE);
1858                 } else if ((ast_false(option) && joinempty) || (ast_true(option) && !joinempty)) {
1859                         *empty = (QUEUE_EMPTY_PENALTY | QUEUE_EMPTY_INVALID | QUEUE_EMPTY_PAUSED);
1860                 } else if ((ast_false(option) && !joinempty) || (ast_true(option) && joinempty)) {
1861                         *empty = 0;
1862                 } else {
1863                         ast_log(LOG_WARNING, "Unknown option %s for '%s'\n", option, joinempty ? "joinempty" : "leavewhenempty");
1864                 }
1865         }
1866 }
1867
1868 /*! \brief Configure a queue parameter.
1869  * 
1870  * The failunknown flag is set for config files (and static realtime) to show
1871  * errors for unknown parameters. It is cleared for dynamic realtime to allow
1872  *  extra fields in the tables.
1873  * \note For error reporting, line number is passed for .conf static configuration,
1874  * for Realtime queues, linenum is -1.
1875 */
1876 static void queue_set_param(struct call_queue *q, const char *param, const char *val, int linenum, int failunknown)
1877 {
1878         if (!strcasecmp(param, "musicclass") || 
1879                 !strcasecmp(param, "music") || !strcasecmp(param, "musiconhold")) {
1880                 ast_string_field_set(q, moh, val);
1881         } else if (!strcasecmp(param, "announce")) {
1882                 ast_string_field_set(q, announce, val);
1883         } else if (!strcasecmp(param, "context")) {
1884                 ast_string_field_set(q, context, val);
1885         } else if (!strcasecmp(param, "timeout")) {
1886                 q->timeout = atoi(val);
1887                 if (q->timeout < 0)
1888                         q->timeout = DEFAULT_TIMEOUT;
1889         } else if (!strcasecmp(param, "ringinuse")) {
1890                 q->ringinuse = ast_true(val);
1891         } else if (!strcasecmp(param, "setinterfacevar")) {
1892                 q->setinterfacevar = ast_true(val);
1893         } else if (!strcasecmp(param, "setqueuevar")) {
1894                 q->setqueuevar = ast_true(val);
1895         } else if (!strcasecmp(param, "setqueueentryvar")) {
1896                 q->setqueueentryvar = ast_true(val);
1897         } else if (!strcasecmp(param, "monitor-format")) {
1898                 ast_copy_string(q->monfmt, val, sizeof(q->monfmt));
1899         } else if (!strcasecmp(param, "membermacro")) {
1900                 ast_string_field_set(q, membermacro, val);
1901         } else if (!strcasecmp(param, "membergosub")) {
1902                 ast_string_field_set(q, membergosub, val);
1903         } else if (!strcasecmp(param, "queue-youarenext")) {
1904                 ast_string_field_set(q, sound_next, val);
1905         } else if (!strcasecmp(param, "queue-thereare")) {
1906                 ast_string_field_set(q, sound_thereare, val);
1907         } else if (!strcasecmp(param, "queue-callswaiting")) {
1908                 ast_string_field_set(q, sound_calls, val);
1909         } else if (!strcasecmp(param, "queue-quantity1")) {
1910                 ast_string_field_set(q, queue_quantity1, val);
1911         } else if (!strcasecmp(param, "queue-quantity2")) {
1912                 ast_string_field_set(q, queue_quantity2, val);
1913         } else if (!strcasecmp(param, "queue-holdtime")) {
1914                 ast_string_field_set(q, sound_holdtime, val);
1915         } else if (!strcasecmp(param, "queue-minutes")) {
1916                 ast_string_field_set(q, sound_minutes, val);
1917         } else if (!strcasecmp(param, "queue-minute")) {
1918                 ast_string_field_set(q, sound_minute, val);
1919         } else if (!strcasecmp(param, "queue-seconds")) {
1920                 ast_string_field_set(q, sound_seconds, val);
1921         } else if (!strcasecmp(param, "queue-thankyou")) {
1922                 ast_string_field_set(q, sound_thanks, val);
1923         } else if (!strcasecmp(param, "queue-callerannounce")) {
1924                 ast_string_field_set(q, sound_callerannounce, val);
1925         } else if (!strcasecmp(param, "queue-reporthold")) {
1926                 ast_string_field_set(q, sound_reporthold, val);
1927         } else if (!strcasecmp(param, "announce-frequency")) {
1928                 q->announcefrequency = atoi(val);
1929         } else if (!strcasecmp(param, "min-announce-frequency")) {
1930                 q->minannouncefrequency = atoi(val);
1931                 ast_debug(1, "%s=%s for queue '%s'\n", param, val, q->name);
1932         } else if (!strcasecmp(param, "announce-round-seconds")) {
1933                 q->roundingseconds = atoi(val);
1934                 /* Rounding to any other values just doesn't make sense... */
1935                 if (!(q->roundingseconds == 0 || q->roundingseconds == 5 || q->roundingseconds == 10
1936                         || q->roundingseconds == 15 || q->roundingseconds == 20 || q->roundingseconds == 30)) {
1937                         if (linenum >= 0) {
1938                                 ast_log(LOG_WARNING, "'%s' isn't a valid value for %s "
1939                                         "using 0 instead for queue '%s' at line %d of queues.conf\n",
1940                                         val, param, q->name, linenum);
1941                         } else {
1942                                 ast_log(LOG_WARNING, "'%s' isn't a valid value for %s "
1943                                         "using 0 instead for queue '%s'\n", val, param, q->name);
1944                         }
1945                         q->roundingseconds=0;
1946                 }
1947         } else if (!strcasecmp(param, "announce-holdtime")) {
1948                 if (!strcasecmp(val, "once"))
1949                         q->announceholdtime = ANNOUNCEHOLDTIME_ONCE;
1950                 else if (ast_true(val))
1951                         q->announceholdtime = ANNOUNCEHOLDTIME_ALWAYS;
1952                 else
1953                         q->announceholdtime = 0;
1954         } else if (!strcasecmp(param, "announce-position")) {
1955                 if (!strcasecmp(val, "limit"))
1956                         q->announceposition = ANNOUNCEPOSITION_LIMIT;
1957                 else if (!strcasecmp(val, "more"))
1958                         q->announceposition = ANNOUNCEPOSITION_MORE_THAN;
1959                 else if (ast_true(val))
1960                         q->announceposition = ANNOUNCEPOSITION_YES;
1961                 else
1962                         q->announceposition = ANNOUNCEPOSITION_NO;
1963         } else if (!strcasecmp(param, "announce-position-limit")) {
1964                 q->announcepositionlimit = atoi(val);
1965         } else if (!strcasecmp(param, "periodic-announce")) {
1966                 if (strchr(val, ',')) {
1967                         char *s, *buf = ast_strdupa(val);
1968                         unsigned int i = 0;
1969
1970                         while ((s = strsep(&buf, ",|"))) {
1971                                 if (!q->sound_periodicannounce[i])
1972                                         q->sound_periodicannounce[i] = ast_str_create(16);
1973                                 ast_str_set(&q->sound_periodicannounce[i], 0, "%s", s);
1974                                 i++;
1975                                 if (i == MAX_PERIODIC_ANNOUNCEMENTS)
1976                                         break;
1977                         }
1978                         q->numperiodicannounce = i;
1979                 } else {
1980                         ast_str_set(&q->sound_periodicannounce[0], 0, "%s", val);
1981                         q->numperiodicannounce = 1;
1982                 }
1983         } else if (!strcasecmp(param, "periodic-announce-frequency")) {
1984                 q->periodicannouncefrequency = atoi(val);
1985         } else if (!strcasecmp(param, "relative-periodic-announce")) {
1986                 q->relativeperiodicannounce = ast_true(val);
1987         } else if (!strcasecmp(param, "random-periodic-announce")) {
1988                 q->randomperiodicannounce = ast_true(val);
1989         } else if (!strcasecmp(param, "retry")) {
1990                 q->retry = atoi(val);
1991                 if (q->retry <= 0)
1992                         q->retry = DEFAULT_RETRY;
1993         } else if (!strcasecmp(param, "wrapuptime")) {
1994                 q->wrapuptime = atoi(val);
1995         } else if (!strcasecmp(param, "penaltymemberslimit")) {
1996                 if ((sscanf(val, "%10d", &q->penaltymemberslimit) != 1)) {
1997                         q->penaltymemberslimit = 0;
1998                 }
1999         } else if (!strcasecmp(param, "autofill")) {
2000                 q->autofill = ast_true(val);
2001         } else if (!strcasecmp(param, "monitor-type")) {
2002                 if (!strcasecmp(val, "mixmonitor"))
2003                         q->montype = 1;
2004         } else if (!strcasecmp(param, "autopause")) {
2005                 q->autopause = autopause2int(val);
2006         } else if (!strcasecmp(param, "maxlen")) {
2007                 q->maxlen = atoi(val);
2008                 if (q->maxlen < 0)
2009                         q->maxlen = 0;
2010         } else if (!strcasecmp(param, "servicelevel")) {
2011                 q->servicelevel= atoi(val);
2012         } else if (!strcasecmp(param, "strategy")) {
2013                 int strategy;
2014
2015                 /* We are a static queue and already have set this, no need to do it again */
2016                 if (failunknown) {
2017                         return;
2018                 }
2019                 strategy = strat2int(val);
2020                 if (strategy < 0) {
2021                         ast_log(LOG_WARNING, "'%s' isn't a valid strategy for queue '%s', using ringall instead\n",
2022                                 val, q->name);
2023                         q->strategy = QUEUE_STRATEGY_RINGALL;
2024                 }
2025                 if (strategy == q->strategy) {
2026                         return;
2027                 }
2028                 if (strategy == QUEUE_STRATEGY_LINEAR) {
2029                         ast_log(LOG_WARNING, "Changing to the linear strategy currently requires asterisk to be restarted.\n");
2030                         return;
2031                 }
2032                 q->strategy = strategy;
2033         } else if (!strcasecmp(param, "joinempty")) {
2034                 parse_empty_options(val, &q->joinempty, 1);
2035         } else if (!strcasecmp(param, "leavewhenempty")) {
2036                 parse_empty_options(val, &q->leavewhenempty, 0);
2037         } else if (!strcasecmp(param, "eventmemberstatus")) {
2038                 q->maskmemberstatus = !ast_true(val);
2039         } else if (!strcasecmp(param, "eventwhencalled")) {
2040                 if (!strcasecmp(val, "vars")) {
2041                         q->eventwhencalled = QUEUE_EVENT_VARIABLES;
2042                 } else {
2043                         q->eventwhencalled = ast_true(val) ? 1 : 0;
2044                 }
2045         } else if (!strcasecmp(param, "reportholdtime")) {
2046                 q->reportholdtime = ast_true(val);
2047         } else if (!strcasecmp(param, "memberdelay")) {
2048                 q->memberdelay = atoi(val);
2049         } else if (!strcasecmp(param, "weight")) {
2050                 q->weight = atoi(val);
2051         } else if (!strcasecmp(param, "timeoutrestart")) {
2052                 q->timeoutrestart = ast_true(val);
2053         } else if (!strcasecmp(param, "defaultrule")) {
2054                 ast_string_field_set(q, defaultrule, val);
2055         } else if (!strcasecmp(param, "timeoutpriority")) {
2056                 if (!strcasecmp(val, "conf")) {
2057                         q->timeoutpriority = TIMEOUT_PRIORITY_CONF;
2058                 } else {
2059                         q->timeoutpriority = TIMEOUT_PRIORITY_APP;
2060                 }
2061         } else if (failunknown) {
2062                 if (linenum >= 0) {
2063                         ast_log(LOG_WARNING, "Unknown keyword in queue '%s': %s at line %d of queues.conf\n",
2064                                 q->name, param, linenum);
2065                 } else {
2066                         ast_log(LOG_WARNING, "Unknown keyword in queue '%s': %s\n", q->name, param);
2067                 }
2068         }
2069 }
2070
2071 /*!
2072  * \brief Find rt member record to update otherwise create one.
2073  *
2074  * Search for member in queue, if found update penalty/paused state,
2075  * if no member exists create one flag it as a RT member and add to queue member list.
2076 */
2077 static void rt_handle_member_record(struct call_queue *q, char *interface, struct ast_config *member_config)
2078 {
2079         struct member *m;
2080         struct ao2_iterator mem_iter;
2081         int penalty = 0;
2082         int paused  = 0;
2083         int found = 0;
2084
2085         const char *config_val;
2086         const char *rt_uniqueid = ast_variable_retrieve(member_config, interface, "uniqueid");
2087         const char *membername = S_OR(ast_variable_retrieve(member_config, interface, "membername"), interface);
2088         const char *state_interface = S_OR(ast_variable_retrieve(member_config, interface, "state_interface"), interface);
2089         const char *penalty_str = ast_variable_retrieve(member_config, interface, "penalty");
2090         const char *paused_str = ast_variable_retrieve(member_config, interface, "paused");
2091
2092         if (ast_strlen_zero(rt_uniqueid)) {
2093                 ast_log(LOG_WARNING, "Realtime field uniqueid is empty for member %s\n", S_OR(membername, "NULL"));
2094                 return;
2095         }
2096
2097         if (penalty_str) {
2098                 penalty = atoi(penalty_str);
2099                 if (penalty < 0)
2100                         penalty = 0;
2101         }
2102
2103         if (paused_str) {
2104                 paused = atoi(paused_str);
2105                 if (paused < 0)
2106                         paused = 0;
2107         }
2108
2109         /* Find member by realtime uniqueid and update */
2110         mem_iter = ao2_iterator_init(q->members, 0);
2111         while ((m = ao2_iterator_next(&mem_iter))) {
2112                 if (!strcasecmp(m->rt_uniqueid, rt_uniqueid)) {
2113                         m->dead = 0;    /* Do not delete this one. */
2114                         ast_copy_string(m->rt_uniqueid, rt_uniqueid, sizeof(m->rt_uniqueid));
2115                         if (paused_str)
2116                                 m->paused = paused;
2117                         if (strcasecmp(state_interface, m->state_interface)) {
2118                                 ast_copy_string(m->state_interface, state_interface, sizeof(m->state_interface));
2119                         }          
2120                         m->penalty = penalty;
2121                         found = 1;
2122                         ao2_ref(m, -1);
2123                         break;
2124                 }
2125                 ao2_ref(m, -1);
2126         }
2127         ao2_iterator_destroy(&mem_iter);
2128
2129         /* Create a new member */
2130         if (!found) {
2131                 if ((m = create_queue_member(interface, membername, penalty, paused, state_interface))) {
2132                         m->dead = 0;
2133                         m->realtime = 1;
2134                         ast_copy_string(m->rt_uniqueid, rt_uniqueid, sizeof(m->rt_uniqueid));
2135                         ast_queue_log(q->name, "REALTIME", m->interface, "ADDMEMBER", "%s", "");
2136                         ao2_link(q->members, m);
2137                         ao2_ref(m, -1);
2138                         m = NULL;
2139                         q->membercount++;
2140                 }
2141         }
2142 }
2143
2144 /*! \brief Iterate through queue's member list and delete them */
2145 static void free_members(struct call_queue *q, int all)
2146 {
2147         /* Free non-dynamic members */
2148         struct member *cur;
2149         struct ao2_iterator mem_iter = ao2_iterator_init(q->members, 0);
2150
2151         while ((cur = ao2_iterator_next(&mem_iter))) {
2152                 if (all || !cur->dynamic) {
2153                         ao2_unlink(q->members, cur);
2154                         q->membercount--;
2155                 }
2156                 ao2_ref(cur, -1);
2157         }
2158         ao2_iterator_destroy(&mem_iter);
2159 }
2160
2161 /*! \brief Free queue's member list then its string fields */
2162 static void destroy_queue(void *obj)
2163 {
2164         struct call_queue *q = obj;
2165         int i;
2166
2167         free_members(q, 1);
2168         ast_string_field_free_memory(q);
2169         for (i = 0; i < MAX_PERIODIC_ANNOUNCEMENTS; i++) {
2170                 if (q->sound_periodicannounce[i])
2171                         free(q->sound_periodicannounce[i]);
2172         }
2173         ao2_ref(q->members, -1);
2174 }
2175
2176 static struct call_queue *alloc_queue(const char *queuename)
2177 {
2178         struct call_queue *q;
2179
2180         if ((q = ao2_t_alloc(sizeof(*q), destroy_queue, "Allocate queue"))) {
2181                 if (ast_string_field_init(q, 64)) {
2182                         queue_t_unref(q, "String field allocation failed");
2183                         return NULL;
2184                 }
2185                 ast_string_field_set(q, name, queuename);
2186         }
2187         return q;
2188 }
2189
2190 /*!
2191  * \brief Reload a single queue via realtime.
2192  *
2193  * Check for statically defined queue first, check if deleted RT queue,
2194  * check for new RT queue, if queue vars are not defined init them with defaults.
2195  * reload RT queue vars, set RT queue members dead and reload them, return finished queue.
2196  * \retval the queue, 
2197  * \retval NULL if it doesn't exist.
2198  * \note Should be called with the "queues" container locked. 
2199 */
2200 static struct call_queue *find_queue_by_name_rt(const char *queuename, struct ast_variable *queue_vars, struct ast_config *member_config)
2201 {
2202         struct ast_variable *v;
2203         struct call_queue *q, tmpq = {
2204                 .name = queuename,      
2205         };
2206         struct member *m;
2207         struct ao2_iterator mem_iter;
2208         char *interface = NULL;
2209         const char *tmp_name;
2210         char *tmp;
2211         char tmpbuf[64];        /* Must be longer than the longest queue param name. */
2212
2213         /* Static queues override realtime. */
2214         if ((q = ao2_t_find(queues, &tmpq, OBJ_POINTER, "Check if static queue exists"))) {
2215                 ao2_lock(q);
2216                 if (!q->realtime) {
2217                         if (q->dead) {
2218                                 ao2_unlock(q);
2219                                 queue_t_unref(q, "Queue is dead; can't return it");
2220                                 return NULL;
2221                         } else {
2222                                 ast_log(LOG_WARNING, "Static queue '%s' already exists. Not loading from realtime\n", q->name);
2223                                 ao2_unlock(q);
2224                                 return q;
2225                         }
2226                 }
2227         } else if (!member_config)
2228                 /* Not found in the list, and it's not realtime ... */
2229                 return NULL;
2230
2231         /* Check if queue is defined in realtime. */
2232         if (!queue_vars) {
2233                 /* Delete queue from in-core list if it has been deleted in realtime. */
2234                 if (q) {
2235                         /*! \note Hmm, can't seem to distinguish a DB failure from a not
2236                            found condition... So we might delete an in-core queue
2237                            in case of DB failure. */
2238                         ast_debug(1, "Queue %s not found in realtime.\n", queuename);
2239
2240                         q->dead = 1;
2241                         /* Delete if unused (else will be deleted when last caller leaves). */
2242                         queues_t_unlink(queues, q, "Unused; removing from container");
2243                         ao2_unlock(q);
2244                         queue_t_unref(q, "Queue is dead; can't return it");
2245                 }
2246                 return NULL;
2247         }
2248
2249         /* Create a new queue if an in-core entry does not exist yet. */
2250         if (!q) {
2251                 struct ast_variable *tmpvar = NULL;
2252                 if (!(q = alloc_queue(queuename)))
2253                         return NULL;
2254                 ao2_lock(q);
2255                 clear_queue(q);
2256                 q->realtime = 1;
2257                 q->membercount = 0;
2258                 /*Before we initialize the queue, we need to set the strategy, so that linear strategy
2259                  * will allocate the members properly
2260                  */
2261                 for (tmpvar = queue_vars; tmpvar; tmpvar = tmpvar->next) {
2262                         if (!strcasecmp(tmpvar->name, "strategy")) {
2263                                 q->strategy = strat2int(tmpvar->value);
2264                                 if (q->strategy < 0) {
2265                                         ast_log(LOG_WARNING, "'%s' isn't a valid strategy for queue '%s', using ringall instead\n",
2266                                         tmpvar->value, q->name);
2267                                         q->strategy = QUEUE_STRATEGY_RINGALL;
2268                                 }
2269                                 break;
2270                         }
2271                 }
2272                 /* We traversed all variables and didn't find a strategy */
2273                 if (!tmpvar)
2274                         q->strategy = QUEUE_STRATEGY_RINGALL;
2275                 queues_t_link(queues, q, "Add queue to container");
2276         }
2277         init_queue(q);          /* Ensure defaults for all parameters not set explicitly. */
2278
2279         memset(tmpbuf, 0, sizeof(tmpbuf));
2280         for (v = queue_vars; v; v = v->next) {
2281                 /* Convert to dashes `-' from underscores `_' as the latter are more SQL friendly. */
2282                 if ((tmp = strchr(v->name, '_'))) {
2283                         ast_copy_string(tmpbuf, v->name, sizeof(tmpbuf));
2284                         tmp_name = tmpbuf;
2285                         tmp = tmpbuf;
2286                         while ((tmp = strchr(tmp, '_')))
2287                                 *tmp++ = '-';
2288                 } else
2289                         tmp_name = v->name;
2290
2291                 /* NULL values don't get returned from realtime; blank values should
2292                  * still get set.  If someone doesn't want a value to be set, they
2293                  * should set the realtime column to NULL, not blank. */
2294                 queue_set_param(q, tmp_name, v->value, -1, 0);
2295         }
2296
2297         /* Temporarily set realtime members dead so we can detect deleted ones. 
2298          * Also set the membercount correctly for realtime*/
2299         mem_iter = ao2_iterator_init(q->members, 0);
2300         while ((m = ao2_iterator_next(&mem_iter))) {
2301                 q->membercount++;
2302                 if (m->realtime)
2303                         m->dead = 1;
2304                 ao2_ref(m, -1);
2305         }
2306         ao2_iterator_destroy(&mem_iter);
2307
2308         while ((interface = ast_category_browse(member_config, interface))) {
2309                 rt_handle_member_record(q, interface, member_config);
2310         }
2311
2312         /* Delete all realtime members that have been deleted in DB. */
2313         mem_iter = ao2_iterator_init(q->members, 0);
2314         while ((m = ao2_iterator_next(&mem_iter))) {
2315                 if (m->dead) {
2316                         ast_queue_log(q->name, "REALTIME", m->interface, "REMOVEMEMBER", "%s", "");
2317                         ao2_unlink(q->members, m);
2318                         q->membercount--;
2319                 }
2320                 ao2_ref(m, -1);
2321         }
2322         ao2_iterator_destroy(&mem_iter);
2323
2324         ao2_unlock(q);
2325
2326         return q;
2327 }
2328
2329 static struct call_queue *load_realtime_queue(const char *queuename)
2330 {
2331         struct ast_variable *queue_vars;
2332         struct ast_config *member_config = NULL;
2333         struct call_queue *q = NULL, tmpq = {
2334                 .name = queuename,      
2335         };
2336         int prev_weight = 0;
2337
2338         /* Find the queue in the in-core list first. */
2339         q = ao2_t_find(queues, &tmpq, OBJ_POINTER, "Look for queue in memory first");
2340
2341         if (!q || q->realtime) {
2342                 /*! \note Load from realtime before taking the "queues" container lock, to avoid blocking all
2343                    queue operations while waiting for the DB.
2344
2345                    This will be two separate database transactions, so we might
2346                    see queue parameters as they were before another process
2347                    changed the queue and member list as it was after the change.
2348                    Thus we might see an empty member list when a queue is
2349                    deleted. In practise, this is unlikely to cause a problem. */
2350
2351                 queue_vars = ast_load_realtime("queues", "name", queuename, SENTINEL);
2352                 if (queue_vars) {
2353                         member_config = ast_load_realtime_multientry("queue_members", "interface LIKE", "%", "queue_name", queuename, SENTINEL);
2354                         if (!member_config) {
2355                                 ast_log(LOG_ERROR, "no queue_members defined in your config (extconfig.conf).\n");
2356                                 ast_variables_destroy(queue_vars);
2357                                 return NULL;
2358                         }
2359                 }
2360                 if (q) {
2361                         prev_weight = q->weight ? 1 : 0;
2362                 }
2363
2364                 ao2_lock(queues);
2365
2366                 q = find_queue_by_name_rt(queuename, queue_vars, member_config);
2367                 if (member_config) {
2368                         ast_config_destroy(member_config);
2369                 }
2370                 if (queue_vars) {
2371                         ast_variables_destroy(queue_vars);
2372                 }
2373                 /* update the use_weight value if the queue's has gained or lost a weight */ 
2374                 if (q) {
2375                         if (!q->weight && prev_weight) {
2376                                 ast_atomic_fetchadd_int(&use_weight, -1);
2377                         }
2378                         if (q->weight && !prev_weight) {
2379                                 ast_atomic_fetchadd_int(&use_weight, +1);
2380                         }
2381                 }
2382                 /* Other cases will end up with the proper value for use_weight */
2383                 ao2_unlock(queues);
2384
2385         } else {
2386                 update_realtime_members(q);
2387         }
2388         return q;
2389 }
2390
2391 static int update_realtime_member_field(struct member *mem, const char *queue_name, const char *field, const char *value)
2392 {
2393         int ret = -1;
2394
2395         if (ast_strlen_zero(mem->rt_uniqueid))
2396                 return ret;
2397
2398         if ((ast_update_realtime("queue_members", "uniqueid", mem->rt_uniqueid, field, value, SENTINEL)) > 0)
2399                 ret = 0;
2400
2401         return ret;
2402 }
2403
2404
2405 static void update_realtime_members(struct call_queue *q)
2406 {
2407         struct ast_config *member_config = NULL;
2408         struct member *m;
2409         char *interface = NULL;
2410         struct ao2_iterator mem_iter;
2411
2412         if (!(member_config = ast_load_realtime_multientry("queue_members", "interface LIKE", "%", "queue_name", q->name , SENTINEL))) {
2413                 /*This queue doesn't have realtime members*/
2414                 ast_debug(3, "Queue %s has no realtime members defined. No need for update\n", q->name);
2415                 return;
2416         }
2417
2418         ao2_lock(queues);
2419         ao2_lock(q);
2420         
2421         /* Temporarily set realtime  members dead so we can detect deleted ones.*/ 
2422         mem_iter = ao2_iterator_init(q->members, 0);
2423         while ((m = ao2_iterator_next(&mem_iter))) {
2424                 if (m->realtime)
2425                         m->dead = 1;
2426                 ao2_ref(m, -1);
2427         }
2428         ao2_iterator_destroy(&mem_iter);
2429
2430         while ((interface = ast_category_browse(member_config, interface))) {
2431                 rt_handle_member_record(q, interface, member_config);
2432         }
2433
2434         /* Delete all realtime members that have been deleted in DB. */
2435         mem_iter = ao2_iterator_init(q->members, 0);
2436         while ((m = ao2_iterator_next(&mem_iter))) {
2437                 if (m->dead) {
2438                         ast_queue_log(q->name, "REALTIME", m->interface, "REMOVEMEMBER", "%s", "");
2439                         ao2_unlink(q->members, m);
2440                         q->membercount--;
2441                 }
2442                 ao2_ref(m, -1);
2443         }
2444         ao2_iterator_destroy(&mem_iter);
2445         ao2_unlock(q);
2446         ao2_unlock(queues);
2447         ast_config_destroy(member_config);
2448 }
2449
2450 static int join_queue(char *queuename, struct queue_ent *qe, enum queue_result *reason, int position)
2451 {
2452         struct call_queue *q;
2453         struct queue_ent *cur, *prev = NULL;
2454         int res = -1;
2455         int pos = 0;
2456         int inserted = 0;
2457
2458         if (!(q = load_realtime_queue(queuename)))
2459                 return res;
2460
2461         ao2_lock(queues);
2462         ao2_lock(q);
2463
2464         /* This is our one */
2465         if (q->joinempty) {
2466                 int status = 0;
2467                 if ((status = get_member_status(q, qe->max_penalty, qe->min_penalty, q->joinempty))) {
2468                         *reason = QUEUE_JOINEMPTY;
2469                         ao2_unlock(q);
2470                         ao2_unlock(queues);
2471                         return res;
2472                 }
2473         }
2474         if (*reason == QUEUE_UNKNOWN && q->maxlen && (q->count >= q->maxlen))
2475                 *reason = QUEUE_FULL;
2476         else if (*reason == QUEUE_UNKNOWN) {
2477                 /* There's space for us, put us at the right position inside
2478                  * the queue.
2479                  * Take into account the priority of the calling user */
2480                 inserted = 0;
2481                 prev = NULL;
2482                 cur = q->head;
2483                 while (cur) {
2484                         /* We have higher priority than the current user, enter
2485                          * before him, after all the other users with priority
2486                          * higher or equal to our priority. */
2487                         if ((!inserted) && (qe->prio > cur->prio)) {
2488                                 insert_entry(q, prev, qe, &pos);
2489                                 inserted = 1;
2490                         }
2491                         /* <= is necessary for the position comparison because it may not be possible to enter
2492                          * at our desired position since higher-priority callers may have taken the position we want
2493                          */
2494                         if (!inserted && (qe->prio >= cur->prio) && position && (position <= pos + 1)) {
2495                                 insert_entry(q, prev, qe, &pos);
2496                                 /*pos is incremented inside insert_entry, so don't need to add 1 here*/
2497                                 if (position < pos) {
2498                                         ast_log(LOG_NOTICE, "Asked to be inserted at position %d but forced into position %d due to higher priority callers\n", position, pos);
2499                                 }
2500                                 inserted = 1;
2501                         }
2502                         cur->pos = ++pos;
2503                         prev = cur;
2504                         cur = cur->next;
2505                 }
2506                 /* No luck, join at the end of the queue */
2507                 if (!inserted)
2508                         insert_entry(q, prev, qe, &pos);
2509                 ast_copy_string(qe->moh, q->moh, sizeof(qe->moh));
2510                 ast_copy_string(qe->announce, q->announce, sizeof(qe->announce));
2511                 ast_copy_string(qe->context, q->context, sizeof(qe->context));
2512                 q->count++;
2513                 res = 0;
2514                 ast_manager_event(qe->chan, EVENT_FLAG_CALL, "Join",
2515                         "Channel: %s\r\n"
2516                         "CallerIDNum: %s\r\n"
2517                         "CallerIDName: %s\r\n"
2518                         "ConnectedLineNum: %s\r\n"
2519                         "ConnectedLineName: %s\r\n"
2520                         "Queue: %s\r\n"
2521                         "Position: %d\r\n"
2522                         "Count: %d\r\n"
2523                         "Uniqueid: %s\r\n",
2524                         qe->chan->name,
2525                         S_COR(qe->chan->caller.id.number.valid, qe->chan->caller.id.number.str, "unknown"),/* XXX somewhere else it is <unknown> */
2526                         S_COR(qe->chan->caller.id.name.valid, qe->chan->caller.id.name.str, "unknown"),
2527                         S_COR(qe->chan->connected.id.number.valid, qe->chan->connected.id.number.str, "unknown"),/* XXX somewhere else it is <unknown> */
2528                         S_COR(qe->chan->connected.id.name.valid, qe->chan->connected.id.name.str, "unknown"),
2529                         q->name, qe->pos, q->count, qe->chan->uniqueid );
2530                 ast_debug(1, "Queue '%s' Join, Channel '%s', Position '%d'\n", q->name, qe->chan->name, qe->pos );
2531         }
2532         ao2_unlock(q);
2533         ao2_unlock(queues);
2534
2535         return res;
2536 }
2537
2538 static int play_file(struct ast_channel *chan, const char *filename)
2539 {
2540         int res;
2541
2542         if (ast_strlen_zero(filename)) {
2543                 return 0;
2544         }
2545
2546         if (!ast_fileexists(filename, NULL, chan->language)) {
2547                 return 0;
2548         }
2549
2550         ast_stopstream(chan);
2551
2552         res = ast_streamfile(chan, filename, chan->language);
2553         if (!res)
2554                 res = ast_waitstream(chan, AST_DIGIT_ANY);
2555
2556         ast_stopstream(chan);
2557
2558         return res;
2559 }
2560
2561 /*!
2562  * \brief Check for valid exit from queue via goto
2563  * \retval 0 if failure
2564  * \retval 1 if successful
2565 */
2566 static int valid_exit(struct queue_ent *qe, char digit)
2567 {
2568         int digitlen = strlen(qe->digits);
2569
2570         /* Prevent possible buffer overflow */
2571         if (digitlen < sizeof(qe->digits) - 2) {
2572                 qe->digits[digitlen] = digit;
2573                 qe->digits[digitlen + 1] = '\0';
2574         } else {
2575                 qe->digits[0] = '\0';
2576                 return 0;
2577         }
2578
2579         /* If there's no context to goto, short-circuit */
2580         if (ast_strlen_zero(qe->context))
2581                 return 0;
2582
2583         /* If the extension is bad, then reset the digits to blank */
2584         if (!ast_canmatch_extension(qe->chan, qe->context, qe->digits, 1,
2585                 S_COR(qe->chan->caller.id.number.valid, qe->chan->caller.id.number.str, NULL))) {
2586                 qe->digits[0] = '\0';
2587                 return 0;
2588         }
2589
2590         /* We have an exact match */
2591         if (!ast_goto_if_exists(qe->chan, qe->context, qe->digits, 1)) {
2592                 qe->valid_digits = 1;
2593                 /* Return 1 on a successful goto */
2594                 return 1;
2595         }
2596
2597         return 0;
2598 }
2599
2600 static int say_position(struct queue_ent *qe, int ringing)
2601 {
2602         int res = 0, avgholdmins, avgholdsecs, announceposition = 0;
2603         int say_thanks = 1;
2604         time_t now;
2605
2606         /* Let minannouncefrequency seconds pass between the start of each position announcement */
2607         time(&now);
2608         if ((now - qe->last_pos) < qe->parent->minannouncefrequency)
2609                 return 0;
2610
2611         /* If either our position has changed, or we are over the freq timer, say position */
2612         if ((qe->last_pos_said == qe->pos) && ((now - qe->last_pos) < qe->parent->announcefrequency))
2613                 return 0;
2614
2615         if (ringing) {
2616                 ast_indicate(qe->chan,-1);
2617         } else {
2618                 ast_moh_stop(qe->chan);
2619         }
2620
2621         if (qe->parent->announceposition == ANNOUNCEPOSITION_YES ||
2622                 qe->parent->announceposition == ANNOUNCEPOSITION_MORE_THAN ||
2623                 (qe->parent->announceposition == ANNOUNCEPOSITION_LIMIT &&
2624                 qe->pos <= qe->parent->announcepositionlimit))
2625                         announceposition = 1;
2626
2627
2628         if (announceposition == 1) {
2629                 /* Say we're next, if we are */
2630                 if (qe->pos == 1) {
2631                         res = play_file(qe->chan, qe->parent->sound_next);
2632                         if (res)
2633                                 goto playout;
2634                         else
2635                                 goto posout;
2636                 } else {
2637                         if (qe->parent->announceposition == ANNOUNCEPOSITION_MORE_THAN && qe->pos > qe->parent->announcepositionlimit){
2638                                 /* More than Case*/
2639                                 res = play_file(qe->chan, qe->parent->queue_quantity1);
2640                                 if (res)
2641                                         goto playout;
2642                                 res = ast_say_number(qe->chan, qe->parent->announcepositionlimit, AST_DIGIT_ANY, qe->chan->language, NULL); /* Needs gender */
2643                                 if (res)
2644                                         goto playout;
2645                         } else {
2646                                 /* Normal Case */
2647                                 res = play_file(qe->chan, qe->parent->sound_thereare);
2648                                 if (res)
2649                                         goto playout;
2650                                 res = ast_say_number(qe->chan, qe->pos, AST_DIGIT_ANY, qe->chan->language, NULL); /* Needs gender */
2651                                 if (res)
2652                                         goto playout;
2653                         }
2654                         if (qe->parent->announceposition == ANNOUNCEPOSITION_MORE_THAN && qe->pos > qe->parent->announcepositionlimit){
2655                                 /* More than Case*/
2656                                 res = play_file(qe->chan, qe->parent->queue_quantity2);
2657                                 if (res)
2658                                         goto playout;
2659                         } else {
2660                                 res = play_file(qe->chan, qe->parent->sound_calls);
2661                                 if (res)
2662                                         goto playout;
2663                         }
2664                 }
2665         }
2666         /* Round hold time to nearest minute */
2667         avgholdmins = abs(((qe->parent->holdtime + 30) - (now - qe->start)) / 60);
2668
2669         /* If they have specified a rounding then round the seconds as well */
2670         if (qe->parent->roundingseconds) {
2671                 avgholdsecs = (abs(((qe->parent->holdtime + 30) - (now - qe->start))) - 60 * avgholdmins) / qe->parent->roundingseconds;
2672                 avgholdsecs *= qe->parent->roundingseconds;
2673         } else {
2674                 avgholdsecs = 0;
2675         }
2676
2677         ast_verb(3, "Hold time for %s is %d minute(s) %d seconds\n", qe->parent->name, avgholdmins, avgholdsecs);
2678
2679         /* If the hold time is >1 min, if it's enabled, and if it's not
2680            supposed to be only once and we have already said it, say it */
2681     if ((avgholdmins+avgholdsecs) > 0 && qe->parent->announceholdtime &&
2682         ((qe->parent->announceholdtime == ANNOUNCEHOLDTIME_ONCE && !qe->last_pos) ||
2683         !(qe->parent->announceholdtime == ANNOUNCEHOLDTIME_ONCE))) {
2684                 res = play_file(qe->chan, qe->parent->sound_holdtime);
2685                 if (res)
2686                         goto playout;
2687
2688                 if (avgholdmins >= 1) {
2689                         res = ast_say_number(qe->chan, avgholdmins, AST_DIGIT_ANY, qe->chan->language, NULL);
2690                         if (res)
2691                                 goto playout;
2692
2693                         if (avgholdmins == 1) {
2694                                 res = play_file(qe->chan, qe->parent->sound_minute);
2695                                 if (res)
2696                                         goto playout;
2697                         } else {
2698                                 res = play_file(qe->chan, qe->parent->sound_minutes);
2699                                 if (res)
2700                                         goto playout;
2701                         }
2702                 }
2703                 if (avgholdsecs >= 1) {
2704                         res = ast_say_number(qe->chan, avgholdsecs, AST_DIGIT_ANY, qe->chan->language, NULL);
2705                         if (res)
2706                                 goto playout;
2707
2708                         res = play_file(qe->chan, qe->parent->sound_seconds);
2709                         if (res)
2710                                 goto playout;
2711                 }
2712         } else if (qe->parent->announceholdtime && !qe->parent->announceposition) {
2713                 say_thanks = 0;
2714         }
2715
2716 posout:
2717         if (qe->parent->announceposition) {
2718                 ast_verb(3, "Told %s in %s their queue position (which was %d)\n",
2719                         qe->chan->name, qe->parent->name, qe->pos);
2720         }
2721         if (say_thanks) {
2722                 res = play_file(qe->chan, qe->parent->sound_thanks);
2723         }
2724 playout:
2725
2726         if ((res > 0 && !valid_exit(qe, res)))
2727                 res = 0;
2728
2729         /* Set our last_pos indicators */
2730         qe->last_pos = now;
2731         qe->last_pos_said = qe->pos;
2732
2733         /* Don't restart music on hold if we're about to exit the caller from the queue */
2734         if (!res) {
2735                 if (ringing) {
2736                         ast_indicate(qe->chan, AST_CONTROL_RINGING);
2737                 } else {
2738                         ast_moh_start(qe->chan, qe->moh, NULL);
2739                 }
2740         }
2741         return res;
2742 }
2743
2744 static void recalc_holdtime(struct queue_ent *qe, int newholdtime)
2745 {
2746         int oldvalue;
2747
2748         /* Calculate holdtime using an exponential average */
2749         /* Thanks to SRT for this contribution */
2750         /* 2^2 (4) is the filter coefficient; a higher exponent would give old entries more weight */
2751
2752         ao2_lock(qe->parent);
2753         oldvalue = qe->parent->holdtime;
2754         qe->parent->holdtime = (((oldvalue << 2) - oldvalue) + newholdtime) >> 2;
2755         ao2_unlock(qe->parent);
2756 }
2757
2758 /*! \brief Caller leaving queue.
2759  * 
2760  * Search the queue to find the leaving client, if found remove from queue
2761  * create manager event, move others up the queue.
2762 */
2763 static void leave_queue(struct queue_ent *qe)
2764 {
2765         struct call_queue *q;
2766         struct queue_ent *current, *prev = NULL;
2767         struct penalty_rule *pr_iter;
2768         int pos = 0;
2769
2770         if (!(q = qe->parent))
2771                 return;
2772         queue_t_ref(q, "Copy queue pointer from queue entry");
2773         ao2_lock(q);
2774
2775         prev = NULL;
2776         for (current = q->head; current; current = current->next) {
2777                 if (current == qe) {
2778                         char posstr[20];
2779                         q->count--;
2780
2781                         /* Take us out of the queue */
2782                         ast_manager_event(qe->chan, EVENT_FLAG_CALL, "Leave",
2783                                 "Channel: %s\r\nQueue: %s\r\nCount: %d\r\nPosition: %d\r\nUniqueid: %s\r\n",
2784                                 qe->chan->name, q->name,  q->count, qe->pos, qe->chan->uniqueid);
2785                         ast_debug(1, "Queue '%s' Leave, Channel '%s'\n", q->name, qe->chan->name );
2786                         /* Take us out of the queue */
2787                         if (prev)
2788                                 prev->next = current->next;
2789                         else
2790                                 q->head = current->next;
2791                         /* Free penalty rules */
2792                         while ((pr_iter = AST_LIST_REMOVE_HEAD(&qe->qe_rules, list)))
2793                                 ast_free(pr_iter);
2794                         snprintf(posstr, sizeof(posstr), "%d", qe->pos);
2795                         pbx_builtin_setvar_helper(qe->chan, "QUEUEPOSITION", posstr);
2796                 } else {
2797                         /* Renumber the people after us in the queue based on a new count */
2798                         current->pos = ++pos;
2799                         prev = current;
2800                 }
2801         }
2802         ao2_unlock(q);
2803
2804         /*If the queue is a realtime queue, check to see if it's still defined in real time*/
2805         if (q->realtime) {
2806                 struct ast_variable *var;
2807                 if (!(var = ast_load_realtime("queues", "name", q->name, SENTINEL))) {
2808                         q->dead = 1;
2809                 } else {
2810                         ast_variables_destroy(var);
2811                 }
2812         }
2813
2814         if (q->dead) {  
2815                 /* It's dead and nobody is in it, so kill it */
2816                 queues_t_unlink(queues, q, "Queue is now dead; remove it from the container");
2817         }
2818         /* unref the explicit ref earlier in the function */
2819         queue_t_unref(q, "Expire copied reference");
2820 }
2821
2822 /*!
2823  * \internal
2824  * \brief Destroy the given callattempt structure and free it.
2825  * \since 1.8
2826  *
2827  * \param doomed callattempt structure to destroy.
2828  *
2829  * \return Nothing
2830  */
2831 static void callattempt_free(struct callattempt *doomed)
2832 {
2833         if (doomed->member) {
2834                 ao2_ref(doomed->member, -1);
2835         }
2836         ast_party_connected_line_free(&doomed->connected);
2837         ast_free(doomed);
2838 }
2839
2840 /*! \brief Hang up a list of outgoing calls */
2841 static void hangupcalls(struct callattempt *outgoing, struct ast_channel *exception, int cancel_answered_elsewhere)
2842 {
2843         struct callattempt *oo;
2844
2845         while (outgoing) {
2846                 /* If someone else answered the call we should indicate this in the CANCEL */
2847                 /* Hangup any existing lines we have open */
2848                 if (outgoing->chan && (outgoing->chan != exception)) {
2849                         if (exception || cancel_answered_elsewhere)
2850                                 ast_set_flag(outgoing->chan, AST_FLAG_ANSWERED_ELSEWHERE);
2851                         ast_hangup(outgoing->chan);
2852                 }
2853                 oo = outgoing;
2854                 outgoing = outgoing->q_next;
2855                 ast_aoc_destroy_decoded(oo->aoc_s_rate_list);
2856                 callattempt_free(oo);
2857         }
2858 }
2859
2860 /*!
2861  * \brief Get the number of members available to accept a call.
2862  *
2863  * \note The queue passed in should be locked prior to this function call
2864  *
2865  * \param[in] q The queue for which we are couting the number of available members
2866  * \return Return the number of available members in queue q
2867  */
2868 static int num_available_members(struct call_queue *q)
2869 {
2870         struct member *mem;
2871         int avl = 0;
2872         struct ao2_iterator mem_iter;
2873
2874         mem_iter = ao2_iterator_init(q->members, 0);
2875         while ((mem = ao2_iterator_next(&mem_iter))) {
2876                 switch (mem->status) {
2877                 case AST_DEVICE_INUSE:
2878                         if (!q->ringinuse)
2879                                 break;
2880                         /* else fall through */
2881                 case AST_DEVICE_NOT_INUSE:
2882                 case AST_DEVICE_UNKNOWN:
2883                         if (!mem->paused) {
2884                                 avl++;
2885                         }
2886                         break;
2887                 }
2888                 ao2_ref(mem, -1);
2889
2890                 /* If autofill is not enabled or if the queue's strategy is ringall, then
2891                  * we really don't care about the number of available members so much as we
2892                  * do that there is at least one available.
2893                  *
2894                  * In fact, we purposely will return from this function stating that only
2895                  * one member is available if either of those conditions hold. That way,
2896                  * functions which determine what action to take based on the number of available
2897                  * members will operate properly. The reasoning is that even if multiple
2898                  * members are available, only the head caller can actually be serviced.
2899                  */
2900                 if ((!q->autofill || q->strategy == QUEUE_STRATEGY_RINGALL) && avl) {
2901                         break;
2902                 }
2903         }
2904         ao2_iterator_destroy(&mem_iter);
2905
2906         return avl;
2907 }
2908
2909 /* traverse all defined queues which have calls waiting and contain this member
2910    return 0 if no other queue has precedence (higher weight) or 1 if found  */
2911 static int compare_weight(struct call_queue *rq, struct member *member)
2912 {
2913         struct call_queue *q;
2914         struct member *mem;
2915         int found = 0;
2916         struct ao2_iterator queue_iter;
2917         
2918         /* q's lock and rq's lock already set by try_calling()
2919          * to solve deadlock */
2920         queue_iter = ao2_iterator_init(queues, 0);
2921         while ((q = ao2_t_iterator_next(&queue_iter, "Iterate through queues"))) {
2922                 if (q == rq) { /* don't check myself, could deadlock */
2923                         queue_t_unref(q, "Done with iterator");
2924                         continue;
2925                 }
2926                 ao2_lock(q);
2927                 if (q->count && q->members) {
2928                         if ((mem = ao2_find(q->members, member, OBJ_POINTER))) {
2929                                 ast_debug(1, "Found matching member %s in queue '%s'\n", mem->interface, q->name);
2930                                 if (q->weight > rq->weight && q->count >= num_available_members(q)) {
2931                                         ast_debug(1, "Queue '%s' (weight %d, calls %d) is preferred over '%s' (weight %d, calls %d)\n", q->name, q->weight, q->count, rq->name, rq->weight, rq->count);
2932                                         found = 1;
2933                                 }
2934                                 ao2_ref(mem, -1);
2935                         }
2936                 }
2937                 ao2_unlock(q);
2938                 queue_t_unref(q, "Done with iterator");
2939                 if (found) {
2940                         break;
2941                 }
2942         }
2943         ao2_iterator_destroy(&queue_iter);
2944         return found;
2945 }
2946
2947 /*! \brief common hangup actions */
2948 static void do_hang(struct callattempt *o)
2949 {
2950         o->stillgoing = 0;
2951         ast_hangup(o->chan);
2952         o->chan = NULL;
2953 }
2954
2955 /*! \brief convert "\n" to "\nVariable: " ready for manager to use */
2956 static char *vars2manager(struct ast_channel *chan, char *vars, size_t len)
2957 {
2958         struct ast_str *buf = ast_str_thread_get(&ast_str_thread_global_buf, len + 1);
2959         const char *tmp;
2960
2961         if (pbx_builtin_serialize_variables(chan, &buf)) {
2962                 int i, j;
2963
2964                 /* convert "\n" to "\nVariable: " */
2965                 strcpy(vars, "Variable: ");
2966                 tmp = ast_str_buffer(buf);
2967
2968                 for (i = 0, j = 10; (i < len - 1) && (j < len - 1); i++, j++) {
2969                         vars[j] = tmp[i];
2970
2971                         if (tmp[i + 1] == '\0')
2972                                 break;
2973                         if (tmp[i] == '\n') {
2974                                 vars[j++] = '\r';
2975                                 vars[j++] = '\n';
2976
2977                                 ast_copy_string(&(vars[j]), "Variable: ", len - j);
2978                                 j += 9;
2979                         }
2980                 }
2981                 if (j > len - 3)
2982                         j = len - 3;
2983                 vars[j++] = '\r';
2984                 vars[j++] = '\n';
2985                 vars[j] = '\0';
2986         } else {
2987                 /* there are no channel variables; leave it blank */
2988                 *vars = '\0';
2989         }
2990         return vars;
2991 }
2992
2993 /*! 
2994  * \brief Part 2 of ring_one
2995  *
2996  * Does error checking before attempting to request a channel and call a member. 
2997  * This function is only called from ring_one(). 
2998  * Failure can occur if:
2999  * - Agent on call
3000  * - Agent is paused
3001  * - Wrapup time not expired
3002  * - Priority by another queue
3003  *
3004  * \retval 1 on success to reach a free agent
3005  * \retval 0 on failure to get agent.
3006  */
3007 static int ring_entry(struct queue_ent *qe, struct callattempt *tmp, int *busies)
3008 {
3009         int res;
3010         int status;
3011         char tech[256];
3012         char *location;
3013         const char *macrocontext, *macroexten;
3014
3015         /* on entry here, we know that tmp->chan == NULL */
3016         if ((tmp->lastqueue && tmp->lastqueue->wrapuptime && (time(NULL) - tmp->lastcall < tmp->lastqueue->wrapuptime)) ||
3017                 (!tmp->lastqueue && qe->parent->wrapuptime && (time(NULL) - tmp->lastcall < qe->parent->wrapuptime))) {
3018                 ast_debug(1, "Wrapuptime not yet expired on queue %s for %s\n", 
3019                                 (tmp->lastqueue ? tmp->lastqueue->name : qe->parent->name), tmp->interface);
3020                 if (qe->chan->cdr)
3021                         ast_cdr_busy(qe->chan->cdr);
3022                 tmp->stillgoing = 0;
3023                 (*busies)++;
3024                 return 0;
3025         }
3026
3027         if (!qe->parent->ringinuse && (tmp->member->status != AST_DEVICE_NOT_INUSE) && (tmp->member->status != AST_DEVICE_UNKNOWN)) {
3028                 ast_debug(1, "%s in use, can't receive call\n", tmp->interface);
3029                 if (qe->chan->cdr)
3030                         ast_cdr_busy(qe->chan->cdr);
3031                 tmp->stillgoing = 0;
3032                 return 0;
3033         }
3034
3035         if (tmp->member->paused) {
3036                 ast_debug(1, "%s paused, can't receive call\n", tmp->interface);
3037                 if (qe->chan->cdr)
3038                         ast_cdr_busy(qe->chan->cdr);
3039                 tmp->stillgoing = 0;
3040                 return 0;
3041         }
3042         if (use_weight && compare_weight(qe->parent,tmp->member)) {
3043                 ast_debug(1, "Priority queue delaying call to %s:%s\n", qe->parent->name, tmp->interface);
3044                 if (qe->chan->cdr)
3045                         ast_cdr_busy(qe->chan->cdr);
3046                 tmp->stillgoing = 0;
3047                 (*busies)++;
3048                 return 0;
3049         }
3050
3051         ast_copy_string(tech, tmp->interface, sizeof(tech));
3052         if ((location = strchr(tech, '/')))
3053                 *location++ = '\0';
3054         else
3055                 location = "";
3056
3057         /* Request the peer */
3058         tmp->chan = ast_request(tech, qe->chan->nativeformats, qe->chan, location, &status);
3059         if (!tmp->chan) {                       /* If we can't, just go on to the next call */
3060                 if (qe->chan->cdr)
3061                         ast_cdr_busy(qe->chan->cdr);
3062                 tmp->stillgoing = 0;    
3063
3064                 ao2_lock(qe->parent);
3065                 update_status(qe->parent, tmp->member, get_queue_member_status(tmp->member));
3066                 qe->parent->rrpos++;
3067                 qe->linpos++;
3068                 ao2_unlock(qe->parent);
3069
3070                 (*busies)++;
3071                 return 0;
3072         }
3073
3074         ast_channel_lock(tmp->chan);
3075         while (ast_channel_trylock(qe->chan)) {
3076                 CHANNEL_DEADLOCK_AVOIDANCE(tmp->chan);
3077         }
3078
3079         if (qe->cancel_answered_elsewhere) {
3080                 ast_set_flag(tmp->chan, AST_FLAG_ANSWERED_ELSEWHERE);
3081         }
3082         tmp->chan->appl = "AppQueue";
3083         tmp->chan->data = "(Outgoing Line)";
3084         memset(&tmp->chan->whentohangup, 0, sizeof(tmp->chan->whentohangup));
3085
3086         /* If the new channel has no callerid, try to guess what it should be */
3087         if (!tmp->chan->caller.id.number.valid) {
3088                 if (qe->chan->connected.id.number.valid) {
3089                         struct ast_party_caller caller;
3090
3091                         ast_party_caller_set_init(&caller, &tmp->chan->caller);
3092                         caller.id = qe->chan->connected.id;
3093                         caller.ani = qe->chan->connected.ani;
3094                         ast_channel_set_caller_event(tmp->chan, &caller, NULL);
3095                 } else if (!ast_strlen_zero(qe->chan->dialed.number.str)) {
3096                         ast_set_callerid(tmp->chan, qe->chan->dialed.number.str, NULL, NULL);
3097                 } else if (!ast_strlen_zero(S_OR(qe->chan->macroexten, qe->chan->exten))) {
3098                         ast_set_callerid(tmp->chan, S_OR(qe->chan->macroexten, qe->chan->exten), NULL, NULL); 
3099                 }
3100                 tmp->dial_callerid_absent = 1;
3101         }
3102
3103         ast_party_redirecting_copy(&tmp->chan->redirecting, &qe->chan->redirecting);
3104
3105         tmp->chan->dialed.transit_network_select = qe->chan->dialed.transit_network_select;
3106
3107         ast_connected_line_copy_from_caller(&tmp->chan->connected, &qe->chan->caller);
3108
3109         /* Inherit specially named variables from parent channel */
3110         ast_channel_inherit_variables(qe->chan, tmp->chan);
3111         ast_channel_datastore_inherit(qe->chan, tmp->chan);
3112
3113         /* Presense of ADSI CPE on outgoing channel follows ours */
3114         tmp->chan->adsicpe = qe->chan->adsicpe;
3115
3116         /* Inherit context and extension */
3117         macrocontext = pbx_builtin_getvar_helper(qe->chan, "MACRO_CONTEXT");
3118         ast_string_field_set(tmp->chan, dialcontext, ast_strlen_zero(macrocontext) ? qe->chan->context : macrocontext);
3119         macroexten = pbx_builtin_getvar_helper(qe->chan, "MACRO_EXTEN");
3120         if (!ast_strlen_zero(macroexten))
3121                 ast_copy_string(tmp->chan->exten, macroexten, sizeof(tmp->chan->exten));
3122         else
3123                 ast_copy_string(tmp->chan->exten, qe->chan->exten, sizeof(tmp->chan->exten));
3124         if (ast_cdr_isset_unanswered()) {
3125                 /* they want to see the unanswered dial attempts! */
3126                 /* set up the CDR fields on all the CDRs to give sensical information */
3127                 ast_cdr_setdestchan(tmp->chan->cdr, tmp->chan->name);
3128                 strcpy(tmp->chan->cdr->clid, qe->chan->cdr->clid);
3129                 strcpy(tmp->chan->cdr->channel, qe->chan->cdr->channel);
3130                 strcpy(tmp->chan->cdr->src, qe->chan->cdr->src);
3131                 strcpy(tmp->chan->cdr->dst, qe->chan->exten);
3132                 strcpy(tmp->chan->cdr->dcontext, qe->chan->context);
3133                 strcpy(tmp->chan->cdr->lastapp, qe->chan->cdr->lastapp);
3134                 strcpy(tmp->chan->cdr->lastdata, qe->chan->cdr->lastdata);
3135                 tmp->chan->cdr->amaflags = qe->chan->cdr->amaflags;
3136                 strcpy(tmp->chan->cdr->accountcode, qe->chan->cdr->accountcode);
3137                 strcpy(tmp->chan->cdr->userfield, qe->chan->cdr->userfield);
3138         }
3139
3140         /* Place the call, but don't wait on the answer */
3141         if ((res = ast_call(tmp->chan, location, 0))) {
3142                 /* Again, keep going even if there's an error */
3143                 ast_debug(1, "ast call on peer returned %d\n", res);
3144                 ast_verb(3, "Couldn't call %s\n", tmp->interface);
3145                 ast_channel_unlock(tmp->chan);
3146                 ast_channel_unlock(qe->chan);
3147                 do_hang(tmp);
3148                 (*busies)++;
3149                 update_status(qe->parent, tmp->member, get_queue_member_status(tmp->member));
3150                 return 0;
3151         } else if (qe->parent->eventwhencalled) {
3152                 char vars[2048];
3153
3154                 manager_event(EVENT_FLAG_AGENT, "AgentCalled",
3155                         "Queue: %s\r\n"
3156                         "AgentCalled: %s\r\n"
3157                         "AgentName: %s\r\n"
3158                         "ChannelCalling: %s\r\n"
3159                         "DestinationChannel: %s\r\n"
3160                         "CallerIDNum: %s\r\n"
3161                         "CallerIDName: %s\r\n"
3162                         "ConnectedLineNum: %s\r\n"
3163                         "ConnectedLineName: %s\r\n"
3164                         "Context: %s\r\n"
3165                         "Extension: %s\r\n"
3166                         "Priority: %d\r\n"
3167                         "Uniqueid: %s\r\n"
3168                         "%s",
3169                         qe->parent->name, tmp->interface, tmp->member->membername, qe->chan->name, tmp->chan->name,
3170                         S_COR(tmp->chan->caller.id.number.valid, tmp->chan->caller.id.number.str, "unknown"),
3171                         S_COR(tmp->chan->caller.id.name.valid, tmp->chan->caller.id.name.str, "unknown"),
3172                         S_COR(tmp->chan->connected.id.number.valid, tmp->chan->connected.id.number.str, "unknown"),
3173                         S_COR(tmp->chan->connected.id.name.valid, tmp->chan->connected.id.name.str, "unknown"),
3174                         qe->chan->context, qe->chan->exten, qe->chan->priority, qe->chan->uniqueid,
3175                         qe->parent->eventwhencalled == QUEUE_EVENT_VARIABLES ? vars2manager(qe->chan, vars, sizeof(vars)) : "");
3176                 ast_verb(3, "Called %s\n", tmp->interface);
3177         }
3178         ast_channel_unlock(tmp->chan);
3179         ast_channel_unlock(qe->chan);
3180
3181         update_status(qe->parent, tmp->member, get_queue_member_status(tmp->member));
3182         return 1;
3183 }
3184
3185 /*! \brief find the entry with the best metric, or NULL */
3186 static struct callattempt *find_best(struct callattempt *outgoing)
3187 {
3188         struct callattempt *best = NULL, *cur;
3189
3190         for (cur = outgoing; cur; cur = cur->q_next) {
3191                 if (cur->stillgoing &&                                  /* Not already done */
3192                         !cur->chan &&                                   /* Isn't already going */
3193                         (!best || cur->metric < best->metric)) {                /* We haven't found one yet, or it's better */
3194                         best = cur;
3195                 }
3196         }
3197
3198         return best;
3199 }
3200
3201 /*! 
3202  * \brief Place a call to a queue member.
3203  *
3204  * Once metrics have been calculated for each member, this function is used
3205  * to place a call to the appropriate member (or members). The low-level
3206  * channel-handling and error detection is handled in ring_entry
3207  *
3208  * \retval 1 if a member was called successfully
3209  * \retval 0 otherwise
3210  */
3211 static int ring_one(struct queue_ent *qe, struct callattempt *outgoing, int *busies)
3212 {
3213         int ret = 0;
3214
3215         while (ret == 0) {
3216                 struct callattempt *best = find_best(outgoing);
3217                 if (!best) {
3218                         ast_debug(1, "Nobody left to try ringing in queue\n");
3219                         break;
3220                 }
3221                 if (qe->parent->strategy == QUEUE_STRATEGY_RINGALL) {
3222                         struct callattempt *cur;
3223                         /* Ring everyone who shares this best metric (for ringall) */
3224                         for (cur = outgoing; cur; cur = cur->q_next) {
3225                                 if (cur->stillgoing && !cur->chan && cur->metric <= best->metric) {
3226                                         ast_debug(1, "(Parallel) Trying '%s' with metric %d\n", cur->interface, cur->metric);
3227                                         ret |= ring_entry(qe, cur, busies);
3228                                 }
3229                         }
3230                 } else {
3231                         /* Ring just the best channel */
3232                         ast_debug(1, "Trying '%s' with metric %d\n", best->interface, best->metric);
3233                         ret = ring_entry(qe, best, busies);
3234                 }
3235                 
3236                 /* If we have timed out, break out */
3237                 if (qe->expire && (time(NULL) >= qe->expire)) {
3238                         ast_debug(1, "Queue timed out while ringing members.\n");
3239                         ret = 0;
3240                         break;
3241                 }
3242         }
3243
3244         return ret;
3245 }
3246
3247 /*! \brief Search for best metric and add to Round Robbin queue */
3248 static int store_next_rr(struct queue_ent *qe, struct callattempt *outgoing)
3249 {
3250         struct callattempt *best = find_best(outgoing);
3251
3252         if (best) {
3253                 /* Ring just the best channel */
3254                 ast_debug(1, "Next is '%s' with metric %d\n", best->interface, best->metric);
3255                 qe->parent->rrpos = best->metric % 1000;
3256         } else {
3257                 /* Just increment rrpos */
3258                 if (qe->parent->wrapped) {
3259                         /* No more channels, start over */
3260                         qe->parent->rrpos = 0;
3261                 } else {
3262                         /* Prioritize next entry */
3263                         qe->parent->rrpos++;
3264                 }
3265         }
3266         qe->parent->wrapped = 0;
3267
3268         return 0;
3269 }
3270
3271 /*! \brief Search for best metric and add to Linear queue */
3272 static int store_next_lin(struct queue_ent *qe, struct callattempt *outgoing)
3273 {
3274         struct callattempt *best = find_best(outgoing);
3275
3276         if (best) {
3277                 /* Ring just the best channel */
3278                 ast_debug(1, "Next is '%s' with metric %d\n", best->interface, best->metric);
3279                 qe->linpos = best->metric % 1000;
3280         } else {
3281                 /* Just increment rrpos */
3282                 if (qe->linwrapped) {
3283                         /* No more channels, start over */
3284                         qe->linpos = 0;
3285                 } else {
3286                         /* Prioritize next entry */
3287                         qe->linpos++;
3288                 }
3289         }
3290         qe->linwrapped = 0;
3291
3292         return 0;
3293 }
3294
3295 /*! \brief Playback announcement to queued members if peroid has elapsed */
3296 static int say_periodic_announcement(struct queue_ent *qe, int ringing)
3297 {
3298         int res = 0;
3299         time_t now;
3300
3301         /* Get the current time */
3302         time(&now);
3303
3304         /* Check to see if it is time to announce */
3305         if ((now - qe->last_periodic_announce_time) < qe->parent->periodicannouncefrequency)
3306                 return 0;
3307
3308         /* Stop the music on hold so we can play our own file */
3309         if (ringing)
3310                 ast_indicate(qe->chan,-1);
3311         else
3312                 ast_moh_stop(qe->chan);
3313
3314         ast_verb(3, "Playing periodic announcement\n");
3315         
3316         if (qe->parent->randomperiodicannounce && qe->parent->numperiodicannounce) {
3317                 qe->last_periodic_announce_sound = ((unsigned long) ast_random()) % qe->parent->numperiodicannounce;
3318         } else if (qe->last_periodic_announce_sound >= qe->parent->numperiodicannounce || 
3319                 ast_str_strlen(qe->parent->sound_periodicannounce[qe->last_periodic_announce_sound]) == 0) {
3320                 qe->last_periodic_announce_sound = 0;
3321         }
3322         
3323         /* play the announcement */
3324         res = play_file(qe->chan, ast_str_buffer(qe->parent->sound_periodicannounce[qe->last_periodic_announce_sound]));
3325
3326         if (res > 0 && !valid_exit(qe, res))
3327                 res = 0;
3328
3329         /* Resume Music on Hold if the caller is going to stay in the queue */
3330         if (!res) {
3331                 if (ringing)
3332                         ast_indicate(qe->chan, AST_CONTROL_RINGING);
3333                 else
3334                         ast_moh_start(qe->chan, qe->moh, NULL);
3335         }
3336
3337         /* update last_periodic_announce_time */
3338         i