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