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