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