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