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