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