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