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