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