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