ae82bd9367ac5b81946a2c42f9c891b531e778e4
[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="ringinuse">
556                                                 <para>Gets or sets queue member ringinuse.</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
821         <manager name="QueueMemberRingInUse" language="en_US">
822                 <synopsis>
823                         Set the ringinuse value for a queue member.
824                 </synopsis>
825                 <syntax>
826                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
827                         <parameter name="Interface" required="true" />
828                         <parameter name="RingInUse" required="true" />
829                         <parameter name="Queue" />
830                 </syntax>
831                 <description>
832                 </description>
833         </manager>
834
835         <manager name="QueueRule" language="en_US">
836                 <synopsis>
837                         Queue Rules.
838                 </synopsis>
839                 <syntax>
840                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
841                         <parameter name="Rule" />
842                 </syntax>
843                 <description>
844                 </description>
845         </manager>
846         <manager name="QueueReload" language="en_US">
847                 <synopsis>
848                         Reload a queue, queues, or any sub-section of a queue or queues.
849                 </synopsis>
850                 <syntax>
851                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
852                         <parameter name="Queue" />
853                         <parameter name="Members">
854                                 <enumlist>
855                                         <enum name="yes" />
856                                         <enum name="no" />
857                                 </enumlist>
858                         </parameter>
859                         <parameter name="Rules">
860                                 <enumlist>
861                                         <enum name="yes" />
862                                         <enum name="no" />
863                                 </enumlist>
864                         </parameter>
865                         <parameter name="Parameters">
866                                 <enumlist>
867                                         <enum name="yes" />
868                                         <enum name="no" />
869                                 </enumlist>
870                         </parameter>
871                 </syntax>
872                 <description>
873                 </description>
874         </manager>
875         <manager name="QueueReset" language="en_US">
876                 <synopsis>
877                         Reset queue statistics.
878                 </synopsis>
879                 <syntax>
880                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
881                         <parameter name="Queue" />
882                 </syntax>
883                 <description>
884                 </description>
885         </manager>
886  ***/
887
888 enum {
889         OPT_MARK_AS_ANSWERED =       (1 << 0),
890         OPT_GO_ON =                  (1 << 1),
891         OPT_DATA_QUALITY =           (1 << 2),
892         OPT_CALLEE_GO_ON =           (1 << 3),
893         OPT_CALLEE_HANGUP =          (1 << 4),
894         OPT_CALLER_HANGUP =          (1 << 5),
895         OPT_IGNORE_CALL_FW =         (1 << 6),
896         OPT_UPDATE_CONNECTED =       (1 << 7),
897         OPT_CALLEE_PARK =            (1 << 8),
898         OPT_CALLER_PARK =            (1 << 9),
899         OPT_NO_RETRY =               (1 << 10),
900         OPT_RINGING =                (1 << 11),
901         OPT_RING_WHEN_RINGING =      (1 << 12),
902         OPT_CALLEE_TRANSFER =        (1 << 13),
903         OPT_CALLER_TRANSFER =        (1 << 14),
904         OPT_CALLEE_AUTOMIXMON =      (1 << 15),
905         OPT_CALLER_AUTOMIXMON =      (1 << 16),
906         OPT_CALLEE_AUTOMON =         (1 << 17),
907         OPT_CALLER_AUTOMON =         (1 << 18),
908 };
909
910 enum {
911         OPT_ARG_CALLEE_GO_ON = 0,
912         /* note: this entry _MUST_ be the last one in the enum */
913         OPT_ARG_ARRAY_SIZE
914 };
915
916 AST_APP_OPTIONS(queue_exec_options, BEGIN_OPTIONS
917         AST_APP_OPTION('C', OPT_MARK_AS_ANSWERED),
918         AST_APP_OPTION('c', OPT_GO_ON),
919         AST_APP_OPTION('d', OPT_DATA_QUALITY),
920         AST_APP_OPTION_ARG('F', OPT_CALLEE_GO_ON, OPT_ARG_CALLEE_GO_ON),
921         AST_APP_OPTION('h', OPT_CALLEE_HANGUP),
922         AST_APP_OPTION('H', OPT_CALLER_HANGUP),
923         AST_APP_OPTION('i', OPT_IGNORE_CALL_FW),
924         AST_APP_OPTION('I', OPT_UPDATE_CONNECTED),
925         AST_APP_OPTION('k', OPT_CALLEE_PARK),
926         AST_APP_OPTION('K', OPT_CALLER_PARK),
927         AST_APP_OPTION('n', OPT_NO_RETRY),
928         AST_APP_OPTION('r', OPT_RINGING),
929         AST_APP_OPTION('R', OPT_RING_WHEN_RINGING),
930         AST_APP_OPTION('t', OPT_CALLEE_TRANSFER),
931         AST_APP_OPTION('T', OPT_CALLER_TRANSFER),
932         AST_APP_OPTION('x', OPT_CALLEE_AUTOMIXMON),
933         AST_APP_OPTION('X', OPT_CALLER_AUTOMIXMON),
934         AST_APP_OPTION('w', OPT_CALLEE_AUTOMON),
935         AST_APP_OPTION('W', OPT_CALLER_AUTOMON),
936 END_OPTIONS);
937
938 enum {
939         QUEUE_STRATEGY_RINGALL = 0,
940         QUEUE_STRATEGY_LEASTRECENT,
941         QUEUE_STRATEGY_FEWESTCALLS,
942         QUEUE_STRATEGY_RANDOM,
943         QUEUE_STRATEGY_RRMEMORY,
944         QUEUE_STRATEGY_LINEAR,
945         QUEUE_STRATEGY_WRANDOM,
946         QUEUE_STRATEGY_RRORDERED,
947 };
948
949 enum {
950      QUEUE_AUTOPAUSE_OFF = 0,
951      QUEUE_AUTOPAUSE_ON,
952      QUEUE_AUTOPAUSE_ALL
953 };
954
955 enum queue_reload_mask {
956         QUEUE_RELOAD_PARAMETERS = (1 << 0),
957         QUEUE_RELOAD_MEMBER = (1 << 1),
958         QUEUE_RELOAD_RULES = (1 << 2),
959         QUEUE_RESET_STATS = (1 << 3),
960 };
961
962 static const struct strategy {
963         int strategy;
964         const char *name;
965 } strategies[] = {
966         { QUEUE_STRATEGY_RINGALL, "ringall" },
967         { QUEUE_STRATEGY_LEASTRECENT, "leastrecent" },
968         { QUEUE_STRATEGY_FEWESTCALLS, "fewestcalls" },
969         { QUEUE_STRATEGY_RANDOM, "random" },
970         { QUEUE_STRATEGY_RRMEMORY, "rrmemory" },
971         { QUEUE_STRATEGY_RRMEMORY, "roundrobin" },
972         { QUEUE_STRATEGY_LINEAR, "linear" },
973         { QUEUE_STRATEGY_WRANDOM, "wrandom"},
974         { QUEUE_STRATEGY_RRORDERED, "rrordered"},
975 };
976
977 static const struct autopause {
978         int autopause;
979         const char *name;
980 } autopausesmodes [] = {
981         { QUEUE_AUTOPAUSE_OFF,"no" },
982         { QUEUE_AUTOPAUSE_ON, "yes" },
983         { QUEUE_AUTOPAUSE_ALL,"all" },
984 };
985
986
987 static struct ast_taskprocessor *devicestate_tps;
988
989 #define DEFAULT_RETRY           5
990 #define DEFAULT_TIMEOUT         15
991 #define RECHECK                 1               /*!< Recheck every second to see we we're at the top yet */
992 #define MAX_PERIODIC_ANNOUNCEMENTS 10           /*!< The maximum periodic announcements we can have */
993 #define DEFAULT_MIN_ANNOUNCE_FREQUENCY 15       /*!< The minimum number of seconds between position announcements \
994                                                      The default value of 15 provides backwards compatibility */
995 #define MAX_QUEUE_BUCKETS 53
996
997 #define RES_OKAY        0               /*!< Action completed */
998 #define RES_EXISTS      (-1)            /*!< Entry already exists */
999 #define RES_OUTOFMEMORY (-2)            /*!< Out of memory */
1000 #define RES_NOSUCHQUEUE (-3)            /*!< No such queue */
1001 #define RES_NOT_DYNAMIC (-4)            /*!< Member is not dynamic */
1002
1003 static char *app = "Queue";
1004
1005 static char *app_aqm = "AddQueueMember" ;
1006
1007 static char *app_rqm = "RemoveQueueMember" ;
1008
1009 static char *app_pqm = "PauseQueueMember" ;
1010
1011 static char *app_upqm = "UnpauseQueueMember" ;
1012
1013 static char *app_ql = "QueueLog" ;
1014
1015 /*! \brief Persistent Members astdb family */
1016 static const char * const pm_family = "Queue/PersistentMembers";
1017 /* The maximum length of each persistent member queue database entry */
1018 #define PM_MAX_LEN 8192
1019
1020 /*! \brief queues.conf [general] option */
1021 static int queue_persistent_members = 0;
1022
1023 /*! \brief queues.conf per-queue weight option */
1024 static int use_weight = 0;
1025
1026 /*! \brief queues.conf [general] option */
1027 static int autofill_default = 1;
1028
1029 /*! \brief queues.conf [general] option */
1030 static int montype_default = 0;
1031
1032 /*! \brief queues.conf [general] option */
1033 static int shared_lastcall = 1;
1034
1035 /*! \brief Subscription to device state change events */
1036 static struct ast_event_sub *device_state_sub;
1037
1038 /*! \brief queues.conf [general] option */
1039 static int update_cdr = 0;
1040
1041 /*! \brief queues.conf [general] option */
1042 static int negative_penalty_invalid = 0;
1043
1044 /*! \brief queues.conf [general] option */
1045 static int log_membername_as_agent = 0;
1046
1047 /*! \brief queues.conf [general] option */
1048 static int check_state_unknown = 0;
1049
1050 /*! \brief name of the ringinuse field in the realtime database */
1051 static char *realtime_ringinuse_field;
1052
1053 enum queue_result {
1054         QUEUE_UNKNOWN = 0,
1055         QUEUE_TIMEOUT = 1,
1056         QUEUE_JOINEMPTY = 2,
1057         QUEUE_LEAVEEMPTY = 3,
1058         QUEUE_JOINUNAVAIL = 4,
1059         QUEUE_LEAVEUNAVAIL = 5,
1060         QUEUE_FULL = 6,
1061         QUEUE_CONTINUE = 7,
1062 };
1063
1064 static const struct {
1065         enum queue_result id;
1066         char *text;
1067 } queue_results[] = {
1068         { QUEUE_UNKNOWN, "UNKNOWN" },
1069         { QUEUE_TIMEOUT, "TIMEOUT" },
1070         { QUEUE_JOINEMPTY,"JOINEMPTY" },
1071         { QUEUE_LEAVEEMPTY, "LEAVEEMPTY" },
1072         { QUEUE_JOINUNAVAIL, "JOINUNAVAIL" },
1073         { QUEUE_LEAVEUNAVAIL, "LEAVEUNAVAIL" },
1074         { QUEUE_FULL, "FULL" },
1075         { QUEUE_CONTINUE, "CONTINUE" },
1076 };
1077
1078 enum queue_timeout_priority {
1079         TIMEOUT_PRIORITY_APP,
1080         TIMEOUT_PRIORITY_CONF,
1081 };
1082
1083 /*! \brief We define a custom "local user" structure because we
1084  *  use it not only for keeping track of what is in use but
1085  *  also for keeping track of who we're dialing.
1086  *
1087  *  There are two "links" defined in this structure, q_next and call_next.
1088  *  q_next links ALL defined callattempt structures into a linked list. call_next is
1089  *  a link which allows for a subset of the callattempts to be traversed. This subset
1090  *  is used in wait_for_answer so that irrelevant callattempts are not traversed. This
1091  *  also is helpful so that queue logs are always accurate in the case where a call to 
1092  *  a member times out, especially if using the ringall strategy. 
1093 */
1094
1095 struct callattempt {
1096         struct callattempt *q_next;
1097         struct callattempt *call_next;
1098         struct ast_channel *chan;
1099         char interface[256];                    /*!< An Asterisk dial string (not a channel name) */
1100         int stillgoing;
1101         int metric;
1102         time_t lastcall;
1103         struct call_queue *lastqueue;
1104         struct member *member;
1105         /*! Saved connected party info from an AST_CONTROL_CONNECTED_LINE. */
1106         struct ast_party_connected_line connected;
1107         /*! TRUE if an AST_CONTROL_CONNECTED_LINE update was saved to the connected element. */
1108         unsigned int pending_connected_update:1;
1109         /*! TRUE if caller id is not available for connected line */
1110         unsigned int dial_callerid_absent:1;
1111         struct ast_aoc_decoded *aoc_s_rate_list;
1112 };
1113
1114
1115 struct queue_ent {
1116         struct call_queue *parent;             /*!< What queue is our parent */
1117         char moh[MAX_MUSICCLASS];              /*!< Name of musiconhold to be used */
1118         char announce[PATH_MAX];               /*!< Announcement to play for member when call is answered */
1119         char context[AST_MAX_CONTEXT];         /*!< Context when user exits queue */
1120         char digits[AST_MAX_EXTENSION];        /*!< Digits entered while in queue */
1121         int valid_digits;                      /*!< Digits entered correspond to valid extension. Exited */
1122         int pos;                               /*!< Where we are in the queue */
1123         int prio;                              /*!< Our priority */
1124         int last_pos_said;                     /*!< Last position we told the user */
1125         int ring_when_ringing;                 /*!< Should we only use ring indication when a channel is ringing? */
1126         time_t last_periodic_announce_time;    /*!< The last time we played a periodic announcement */
1127         int last_periodic_announce_sound;      /*!< The last periodic announcement we made */
1128         time_t last_pos;                       /*!< Last time we told the user their position */
1129         int opos;                              /*!< Where we started in the queue */
1130         int handled;                           /*!< Whether our call was handled */
1131         int pending;                           /*!< Non-zero if we are attempting to call a member */
1132         int max_penalty;                       /*!< Limit the members that can take this call to this penalty or lower */
1133         int min_penalty;                       /*!< Limit the members that can take this call to this penalty or higher */
1134         int linpos;                            /*!< If using linear strategy, what position are we at? */
1135         int linwrapped;                        /*!< Is the linpos wrapped? */
1136         time_t start;                          /*!< When we started holding */
1137         time_t expire;                         /*!< When this entry should expire (time out of queue) */
1138         int cancel_answered_elsewhere;         /*!< Whether we should force the CAE flag on this call (C) option*/
1139         struct ast_channel *chan;              /*!< Our channel */
1140         AST_LIST_HEAD_NOLOCK(,penalty_rule) qe_rules; /*!< Local copy of the queue's penalty rules */
1141         struct penalty_rule *pr;               /*!< Pointer to the next penalty rule to implement */
1142         struct queue_ent *next;                /*!< The next queue entry */
1143 };
1144
1145 struct member {
1146         char interface[AST_CHANNEL_NAME];    /*!< Technology/Location to dial to reach this member*/
1147         char state_exten[AST_MAX_EXTENSION]; /*!< Extension to get state from (if using hint) */
1148         char state_context[AST_MAX_CONTEXT]; /*!< Context to use when getting state (if using hint) */
1149         char state_interface[AST_CHANNEL_NAME]; /*!< Technology/Location from which to read devicestate changes */
1150         char membername[80];                 /*!< Member name to use in queue logs */
1151         int penalty;                         /*!< Are we a last resort? */
1152         int calls;                           /*!< Number of calls serviced by this member */
1153         int dynamic;                         /*!< Are we dynamically added? */
1154         int realtime;                        /*!< Is this member realtime? */
1155         int status;                          /*!< Status of queue member */
1156         int paused;                          /*!< Are we paused (not accepting calls)? */
1157         time_t lastcall;                     /*!< When last successful call was hungup */
1158         struct call_queue *lastqueue;        /*!< Last queue we received a call */
1159         unsigned int dead:1;                 /*!< Used to detect members deleted in realtime */
1160         unsigned int delme:1;                /*!< Flag to delete entry on reload */
1161         char rt_uniqueid[80];                /*!< Unique id of realtime member entry */
1162         unsigned int ringinuse:1;            /*!< Flag to ring queue members even if their status is 'inuse' */
1163 };
1164
1165 enum empty_conditions {
1166         QUEUE_EMPTY_PENALTY = (1 << 0),
1167         QUEUE_EMPTY_PAUSED = (1 << 1),
1168         QUEUE_EMPTY_INUSE = (1 << 2),
1169         QUEUE_EMPTY_RINGING = (1 << 3),
1170         QUEUE_EMPTY_UNAVAILABLE = (1 << 4),
1171         QUEUE_EMPTY_INVALID = (1 << 5),
1172         QUEUE_EMPTY_UNKNOWN = (1 << 6),
1173         QUEUE_EMPTY_WRAPUP = (1 << 7),
1174 };
1175
1176 enum member_properties {
1177         MEMBER_PENALTY = 0,
1178         MEMBER_RINGINUSE = 1,
1179 };
1180
1181 /* values used in multi-bit flags in call_queue */
1182 #define ANNOUNCEHOLDTIME_ALWAYS 1
1183 #define ANNOUNCEHOLDTIME_ONCE 2
1184 #define QUEUE_EVENT_VARIABLES 3
1185
1186 struct penalty_rule {
1187         int time;                           /*!< Number of seconds that need to pass before applying this rule */
1188         int max_value;                      /*!< The amount specified in the penalty rule for max penalty */
1189         int min_value;                      /*!< The amount specified in the penalty rule for min penalty */
1190         int max_relative;                   /*!< Is the max adjustment relative? 1 for relative, 0 for absolute */
1191         int min_relative;                   /*!< Is the min adjustment relative? 1 for relative, 0 for absolute */
1192         AST_LIST_ENTRY(penalty_rule) list;  /*!< Next penalty_rule */
1193 };
1194
1195 #define ANNOUNCEPOSITION_YES 1 /*!< We announce position */
1196 #define ANNOUNCEPOSITION_NO 2 /*!< We don't announce position */
1197 #define ANNOUNCEPOSITION_MORE_THAN 3 /*!< We say "Currently there are more than <limit>" */
1198 #define ANNOUNCEPOSITION_LIMIT 4 /*!< We not announce position more than <limit> */
1199
1200 struct call_queue {
1201         AST_DECLARE_STRING_FIELDS(
1202                 /*! Queue name */
1203                 AST_STRING_FIELD(name);
1204                 /*! Music on Hold class */
1205                 AST_STRING_FIELD(moh);
1206                 /*! Announcement to play when call is answered */
1207                 AST_STRING_FIELD(announce);
1208                 /*! Exit context */
1209                 AST_STRING_FIELD(context);
1210                 /*! Macro to run upon member connection */
1211                 AST_STRING_FIELD(membermacro);
1212                 /*! Gosub to run upon member connection */
1213                 AST_STRING_FIELD(membergosub);
1214                 /*! Default rule to use if none specified in call to Queue() */
1215                 AST_STRING_FIELD(defaultrule);
1216                 /*! Sound file: "Your call is now first in line" (def. queue-youarenext) */
1217                 AST_STRING_FIELD(sound_next);
1218                 /*! Sound file: "There are currently" (def. queue-thereare) */
1219                 AST_STRING_FIELD(sound_thereare);
1220                 /*! Sound file: "calls waiting to speak to a representative." (def. queue-callswaiting) */
1221                 AST_STRING_FIELD(sound_calls);
1222                 /*! Sound file: "Currently there are more than" (def. queue-quantity1) */
1223                 AST_STRING_FIELD(queue_quantity1);
1224                 /*! Sound file: "callers waiting to speak with a representative" (def. queue-quantity2) */
1225                 AST_STRING_FIELD(queue_quantity2);
1226                 /*! Sound file: "The current estimated total holdtime is" (def. queue-holdtime) */
1227                 AST_STRING_FIELD(sound_holdtime);
1228                 /*! Sound file: "minutes." (def. queue-minutes) */
1229                 AST_STRING_FIELD(sound_minutes);
1230                 /*! Sound file: "minute." (def. queue-minute) */
1231                 AST_STRING_FIELD(sound_minute);
1232                 /*! Sound file: "seconds." (def. queue-seconds) */
1233                 AST_STRING_FIELD(sound_seconds);
1234                 /*! Sound file: "Thank you for your patience." (def. queue-thankyou) */
1235                 AST_STRING_FIELD(sound_thanks);
1236                 /*! Sound file: Custom announce for caller, no default */
1237                 AST_STRING_FIELD(sound_callerannounce);
1238                 /*! Sound file: "Hold time" (def. queue-reporthold) */
1239                 AST_STRING_FIELD(sound_reporthold);
1240         );
1241         /*! Sound files: Custom announce, no default */
1242         struct ast_str *sound_periodicannounce[MAX_PERIODIC_ANNOUNCEMENTS];
1243         unsigned int dead:1;
1244         unsigned int eventwhencalled:2;
1245         unsigned int ringinuse:1;
1246         unsigned int setinterfacevar:1;
1247         unsigned int setqueuevar:1;
1248         unsigned int setqueueentryvar:1;
1249         unsigned int reportholdtime:1;
1250         unsigned int wrapped:1;
1251         unsigned int timeoutrestart:1;
1252         unsigned int announceholdtime:2;
1253         unsigned int announceposition:3;
1254         int strategy:4;
1255         unsigned int maskmemberstatus:1;
1256         unsigned int realtime:1;
1257         unsigned int found:1;
1258         unsigned int relativeperiodicannounce:1;
1259         unsigned int autopausebusy:1;
1260         unsigned int autopauseunavail:1;
1261         enum empty_conditions joinempty;
1262         enum empty_conditions leavewhenempty;
1263         int announcepositionlimit;          /*!< How many positions we announce? */
1264         int announcefrequency;              /*!< How often to announce their position */
1265         int minannouncefrequency;           /*!< The minimum number of seconds between position announcements (def. 15) */
1266         int periodicannouncefrequency;      /*!< How often to play periodic announcement */
1267         int numperiodicannounce;            /*!< The number of periodic announcements configured */
1268         int randomperiodicannounce;         /*!< Are periodic announcments randomly chosen */
1269         int roundingseconds;                /*!< How many seconds do we round to? */
1270         int holdtime;                       /*!< Current avg holdtime, based on an exponential average */
1271         int talktime;                       /*!< Current avg talktime, based on the same exponential average */
1272         int callscompleted;                 /*!< Number of queue calls completed */
1273         int callsabandoned;                 /*!< Number of queue calls abandoned */
1274         int servicelevel;                   /*!< seconds setting for servicelevel*/
1275         int callscompletedinsl;             /*!< Number of calls answered with servicelevel*/
1276         char monfmt[8];                     /*!< Format to use when recording calls */
1277         int montype;                        /*!< Monitor type  Monitor vs. MixMonitor */
1278         int count;                          /*!< How many entries */
1279         int maxlen;                         /*!< Max number of entries */
1280         int wrapuptime;                     /*!< Wrapup Time */
1281         int penaltymemberslimit;            /*!< Disregard penalty when queue has fewer than this many members */
1282
1283         int retry;                          /*!< Retry calling everyone after this amount of time */
1284         int timeout;                        /*!< How long to wait for an answer */
1285         int weight;                         /*!< Respective weight */
1286         int autopause;                      /*!< Auto pause queue members if they fail to answer */
1287         int autopausedelay;                 /*!< Delay auto pause for autopausedelay seconds since last call */
1288         int timeoutpriority;                /*!< Do we allow a fraction of the timeout to occur for a ring? */
1289
1290         /* Queue strategy things */
1291         int rrpos;                          /*!< Round Robin - position */
1292         int memberdelay;                    /*!< Seconds to delay connecting member to caller */
1293         int autofill;                       /*!< Ignore the head call status and ring an available agent */
1294         
1295         struct ao2_container *members;             /*!< Head of the list of members */
1296         struct queue_ent *head;             /*!< Head of the list of callers */
1297         AST_LIST_ENTRY(call_queue) list;    /*!< Next call queue */
1298         AST_LIST_HEAD_NOLOCK(, penalty_rule) rules; /*!< The list of penalty rules to invoke */
1299 };
1300
1301 struct rule_list {
1302         char name[80];
1303         AST_LIST_HEAD_NOLOCK(,penalty_rule) rules;
1304         AST_LIST_ENTRY(rule_list) list;
1305 };
1306
1307 static AST_LIST_HEAD_STATIC(rule_lists, rule_list);
1308
1309 static struct ao2_container *queues;
1310
1311 static void update_realtime_members(struct call_queue *q);
1312 static struct member *interface_exists(struct call_queue *q, const char *interface);
1313 static int set_member_paused(const char *queuename, const char *interface, const char *reason, int paused);
1314
1315 static void queue_transfer_fixup(void *data, struct ast_channel *old_chan, struct ast_channel *new_chan);
1316
1317 static struct member *find_member_by_queuename_and_interface(const char *queuename, const char *interface);
1318 /*! \brief sets the QUEUESTATUS channel variable */
1319 static void set_queue_result(struct ast_channel *chan, enum queue_result res)
1320 {
1321         int i;
1322
1323         for (i = 0; i < ARRAY_LEN(queue_results); i++) {
1324                 if (queue_results[i].id == res) {
1325                         pbx_builtin_setvar_helper(chan, "QUEUESTATUS", queue_results[i].text);
1326                         return;
1327                 }
1328         }
1329 }
1330
1331 static const char *int2strat(int strategy)
1332 {
1333         int x;
1334
1335         for (x = 0; x < ARRAY_LEN(strategies); x++) {
1336                 if (strategy == strategies[x].strategy) {
1337                         return strategies[x].name;
1338                 }
1339         }
1340
1341         return "<unknown>";
1342 }
1343
1344 static int strat2int(const char *strategy)
1345 {
1346         int x;
1347
1348         for (x = 0; x < ARRAY_LEN(strategies); x++) {
1349                 if (!strcasecmp(strategy, strategies[x].name)) {
1350                         return strategies[x].strategy;
1351                 }
1352         }
1353
1354         return -1;
1355 }
1356
1357 static int autopause2int(const char *autopause)
1358 {
1359         int x;
1360         /*This 'double check' that default value is OFF */
1361         if (ast_strlen_zero(autopause)) {
1362                 return QUEUE_AUTOPAUSE_OFF;
1363         }
1364
1365         /*This 'double check' is to ensure old values works */
1366         if(ast_true(autopause)) {
1367                 return QUEUE_AUTOPAUSE_ON;
1368         }
1369
1370         for (x = 0; x < ARRAY_LEN(autopausesmodes); x++) {
1371                 if (!strcasecmp(autopause, autopausesmodes[x].name)) {
1372                         return autopausesmodes[x].autopause;
1373                 }
1374         }
1375
1376         /*This 'double check' that default value is OFF */
1377         return QUEUE_AUTOPAUSE_OFF;
1378 }
1379
1380 static int queue_hash_cb(const void *obj, const int flags)
1381 {
1382         const struct call_queue *q = obj;
1383
1384         return ast_str_case_hash(q->name);
1385 }
1386
1387 static int queue_cmp_cb(void *obj, void *arg, int flags)
1388 {
1389         struct call_queue *q = obj, *q2 = arg;
1390         return !strcasecmp(q->name, q2->name) ? CMP_MATCH | CMP_STOP : 0;
1391 }
1392
1393 #ifdef REF_DEBUG_ONLY_QUEUES
1394 #define queue_ref(q)                            _queue_ref(q, "", __FILE__, __LINE__, __PRETTY_FUNCTION__)
1395 #define queue_unref(q)                          _queue_unref(q, "", __FILE__, __LINE__, __PRETTY_FUNCTION__)
1396 #define queue_t_ref(q, tag)                     _queue_ref(q, tag, __FILE__, __LINE__, __PRETTY_FUNCTION__)
1397 #define queue_t_unref(q, tag)           _queue_unref(q, tag, __FILE__, __LINE__, __PRETTY_FUNCTION__)
1398 #define queues_t_link(c, q, tag)        __ao2_link_debug(c, q, 0, tag, __FILE__, __LINE__, __PRETTY_FUNCTION__)
1399 #define queues_t_unlink(c, q, tag)      __ao2_unlink_debug(c, q, 0, tag, __FILE__, __LINE__, __PRETTY_FUNCTION__)
1400
1401 static inline struct call_queue *_queue_ref(struct call_queue *q, const char *tag, const char *file, int line, const char *filename)
1402 {
1403         __ao2_ref_debug(q, 1, tag, file, line, filename);
1404         return q;
1405 }
1406
1407 static inline struct call_queue *_queue_unref(struct call_queue *q, const char *tag, const char *file, int line, const char *filename)
1408 {
1409         __ao2_ref_debug(q, -1, tag, file, line, filename);
1410         return NULL;
1411 }
1412
1413 #else
1414
1415 #define queue_t_ref(q, tag)                     queue_ref(q)
1416 #define queue_t_unref(q, tag)           queue_unref(q)
1417 #define queues_t_link(c, q, tag)        ao2_t_link(c, q, tag)
1418 #define queues_t_unlink(c, q, tag)      ao2_t_unlink(c, q, tag)
1419
1420 static inline struct call_queue *queue_ref(struct call_queue *q)
1421 {
1422         ao2_ref(q, 1);
1423         return q;
1424 }
1425
1426 static inline struct call_queue *queue_unref(struct call_queue *q)
1427 {
1428         ao2_ref(q, -1);
1429         return NULL;
1430 }
1431 #endif
1432
1433 /*! \brief Set variables of queue */
1434 static void set_queue_variables(struct call_queue *q, struct ast_channel *chan)
1435 {
1436         char interfacevar[256]="";
1437         float sl = 0;
1438
1439         ao2_lock(q);
1440
1441         if (q->setqueuevar) {
1442                 sl = 0;
1443                 if (q->callscompleted > 0) {
1444                         sl = 100 * ((float) q->callscompletedinsl / (float) q->callscompleted);
1445                 }
1446
1447                 snprintf(interfacevar, sizeof(interfacevar),
1448                         "QUEUENAME=%s,QUEUEMAX=%d,QUEUESTRATEGY=%s,QUEUECALLS=%d,QUEUEHOLDTIME=%d,QUEUETALKTIME=%d,QUEUECOMPLETED=%d,QUEUEABANDONED=%d,QUEUESRVLEVEL=%d,QUEUESRVLEVELPERF=%2.1f",
1449                         q->name, q->maxlen, int2strat(q->strategy), q->count, q->holdtime, q->talktime, q->callscompleted, q->callsabandoned,  q->servicelevel, sl);
1450
1451                 ao2_unlock(q);
1452         
1453                 pbx_builtin_setvar_multiple(chan, interfacevar); 
1454         } else {
1455                 ao2_unlock(q);
1456         }
1457 }
1458
1459 /*! \brief Insert the 'new' entry after the 'prev' entry of queue 'q' */
1460 static inline void insert_entry(struct call_queue *q, struct queue_ent *prev, struct queue_ent *new, int *pos)
1461 {
1462         struct queue_ent *cur;
1463
1464         if (!q || !new)
1465                 return;
1466         if (prev) {
1467                 cur = prev->next;
1468                 prev->next = new;
1469         } else {
1470                 cur = q->head;
1471                 q->head = new;
1472         }
1473         new->next = cur;
1474
1475         /* every queue_ent must have a reference to it's parent call_queue, this
1476          * reference does not go away until the end of the queue_ent's life, meaning
1477          * that even when the queue_ent leaves the call_queue this ref must remain. */
1478         queue_ref(q);
1479         new->parent = q;
1480         new->pos = ++(*pos);
1481         new->opos = *pos;
1482 }
1483
1484 /*! \brief Check if members are available
1485  *
1486  * This function checks to see if members are available to be called. If any member
1487  * is available, the function immediately returns 0. If no members are available,
1488  * then -1 is returned.
1489  */
1490 static int get_member_status(struct call_queue *q, int max_penalty, int min_penalty, enum empty_conditions conditions)
1491 {
1492         struct member *member;
1493         struct ao2_iterator mem_iter;
1494
1495         ao2_lock(q);
1496         mem_iter = ao2_iterator_init(q->members, 0);
1497         for (; (member = ao2_iterator_next(&mem_iter)); ao2_ref(member, -1)) {
1498                 if ((max_penalty && (member->penalty > max_penalty)) || (min_penalty && (member->penalty < min_penalty))) {
1499                         if (conditions & QUEUE_EMPTY_PENALTY) {
1500                                 ast_debug(4, "%s is unavailable because his penalty is not between %d and %d\n", member->membername, min_penalty, max_penalty);
1501                                 continue;
1502                         }
1503                 }
1504
1505                 switch (member->status) {
1506                 case AST_DEVICE_INVALID:
1507                         if (conditions & QUEUE_EMPTY_INVALID) {
1508                                 ast_debug(4, "%s is unavailable because his device state is 'invalid'\n", member->membername);
1509                                 break;
1510                         }
1511                         goto default_case;
1512                 case AST_DEVICE_UNAVAILABLE:
1513                         if (conditions & QUEUE_EMPTY_UNAVAILABLE) {
1514                                 ast_debug(4, "%s is unavailable because his device state is 'unavailable'\n", member->membername);
1515                                 break;
1516                         }
1517                         goto default_case;
1518                 case AST_DEVICE_INUSE:
1519                         if (conditions & QUEUE_EMPTY_INUSE) {
1520                                 ast_debug(4, "%s is unavailable because his device state is 'inuse'\n", member->membername);
1521                                 break;
1522                         }
1523                         goto default_case;
1524                 case AST_DEVICE_RINGING:
1525                         if (conditions & QUEUE_EMPTY_RINGING) {
1526                                 ast_debug(4, "%s is unavailable because his device state is 'ringing'\n", member->membername);
1527                                 break;
1528                         }
1529                         goto default_case;
1530                 case AST_DEVICE_UNKNOWN:
1531                         if (conditions & QUEUE_EMPTY_UNKNOWN) {
1532                                 ast_debug(4, "%s is unavailable because his device state is 'unknown'\n", member->membername);
1533                                 break;
1534                         }
1535                         /* Fall-through */
1536                 default:
1537                 default_case:
1538                         if (member->paused && (conditions & QUEUE_EMPTY_PAUSED)) {
1539                                 ast_debug(4, "%s is unavailable because he is paused'\n", member->membername);
1540                                 break;
1541                         } else if ((conditions & QUEUE_EMPTY_WRAPUP) && member->lastcall && q->wrapuptime && (time(NULL) - q->wrapuptime < member->lastcall)) {
1542                                 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);
1543                                 break;
1544                         } else {
1545                                 ao2_ref(member, -1);
1546                                 ao2_iterator_destroy(&mem_iter);
1547                                 ao2_unlock(q);
1548                                 ast_debug(4, "%s is available.\n", member->membername);
1549                                 return 0;
1550                         }
1551                         break;
1552                 }
1553         }
1554         ao2_iterator_destroy(&mem_iter);
1555
1556         ao2_unlock(q);
1557         return -1;
1558 }
1559
1560 struct statechange {
1561         AST_LIST_ENTRY(statechange) entry;
1562         int state;
1563         char dev[0];
1564 };
1565
1566 /*! \brief set a member's status based on device state of that member's state_interface.
1567  *
1568  * Lock interface list find sc, iterate through each queues queue_member list for member to
1569  * update state inside queues
1570 */
1571 static int update_status(struct call_queue *q, struct member *m, const int status)
1572 {
1573         m->status = status;
1574
1575         if (q->maskmemberstatus) {
1576                 return 0;
1577         }
1578
1579         manager_event(EVENT_FLAG_AGENT, "QueueMemberStatus",
1580                 "Queue: %s\r\n"
1581                 "Location: %s\r\n"
1582                 "MemberName: %s\r\n"
1583                 "StateInterface: %s\r\n"
1584                 "Membership: %s\r\n"
1585                 "Penalty: %d\r\n"
1586                 "CallsTaken: %d\r\n"
1587                 "LastCall: %d\r\n"
1588                 "Status: %d\r\n"
1589                 "Paused: %d\r\n",
1590                 q->name, m->interface, m->membername, m->state_interface, m->dynamic ? "dynamic" : m->realtime ? "realtime" : "static",
1591                 m->penalty, m->calls, (int)m->lastcall, m->status, m->paused
1592         );
1593
1594         return 0;
1595 }
1596
1597 /*! \brief set a member's status based on device state of that member's interface*/
1598 static int handle_statechange(void *datap)
1599 {
1600         struct statechange *sc = datap;
1601         struct ao2_iterator miter, qiter;
1602         struct member *m;
1603         struct call_queue *q;
1604         char interface[80], *slash_pos;
1605         int found = 0;
1606
1607         qiter = ao2_iterator_init(queues, 0);
1608         while ((q = ao2_t_iterator_next(&qiter, "Iterate over queues"))) {
1609                 ao2_lock(q);
1610
1611                 miter = ao2_iterator_init(q->members, 0);
1612                 for (; (m = ao2_iterator_next(&miter)); ao2_ref(m, -1)) {
1613                         ast_copy_string(interface, m->state_interface, sizeof(interface));
1614
1615                         if ((slash_pos = strchr(interface, '/'))) {
1616                                 if (!strncasecmp(interface, "Local/", 6) && (slash_pos = strchr(slash_pos + 1, '/'))) {
1617                                         *slash_pos = '\0';
1618                                 }
1619                         }
1620
1621                         if (!strcasecmp(interface, sc->dev)) {
1622                                 found = 1;
1623                                 update_status(q, m, sc->state);
1624                                 ao2_ref(m, -1);
1625                                 break;
1626                         }
1627                 }
1628                 ao2_iterator_destroy(&miter);
1629
1630                 ao2_unlock(q);
1631                 queue_t_unref(q, "Done with iterator");
1632         }
1633         ao2_iterator_destroy(&qiter);
1634
1635         if (found) {
1636                 ast_debug(1, "Device '%s' changed to state '%d' (%s)\n", sc->dev, sc->state, ast_devstate2str(sc->state));
1637         } else {
1638                 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));
1639         }
1640
1641         ast_free(sc);
1642         return 0;
1643 }
1644
1645 static void device_state_cb(const struct ast_event *event, void *unused)
1646 {
1647         enum ast_device_state state;
1648         const char *device;
1649         struct statechange *sc;
1650         size_t datapsize;
1651
1652         state = ast_event_get_ie_uint(event, AST_EVENT_IE_STATE);
1653         device = ast_event_get_ie_str(event, AST_EVENT_IE_DEVICE);
1654
1655         if (ast_strlen_zero(device)) {
1656                 ast_log(LOG_ERROR, "Received invalid event that had no device IE\n");
1657                 return;
1658         }
1659         datapsize = sizeof(*sc) + strlen(device) + 1;
1660         if (!(sc = ast_calloc(1, datapsize))) {
1661                 ast_log(LOG_ERROR, "failed to calloc a state change struct\n");
1662                 return;
1663         }
1664         sc->state = state;
1665         strcpy(sc->dev, device);
1666         if (ast_taskprocessor_push(devicestate_tps, handle_statechange, sc) < 0) {
1667                 ast_free(sc);
1668         }
1669 }
1670
1671 /*! \brief Helper function which converts from extension state to device state values */
1672 static int extensionstate2devicestate(int state)
1673 {
1674         switch (state) {
1675         case AST_EXTENSION_NOT_INUSE:
1676                 state = AST_DEVICE_NOT_INUSE;
1677                 break;
1678         case AST_EXTENSION_INUSE:
1679                 state = AST_DEVICE_INUSE;
1680                 break;
1681         case AST_EXTENSION_BUSY:
1682                 state = AST_DEVICE_BUSY;
1683                 break;
1684         case AST_EXTENSION_RINGING:
1685                 state = AST_DEVICE_RINGING;
1686                 break;
1687         case AST_EXTENSION_ONHOLD:
1688                 state = AST_DEVICE_ONHOLD;
1689                 break;
1690         case AST_EXTENSION_UNAVAILABLE:
1691                 state = AST_DEVICE_UNAVAILABLE;
1692                 break;
1693         case AST_EXTENSION_REMOVED:
1694         case AST_EXTENSION_DEACTIVATED:
1695         default:
1696                 state = AST_DEVICE_INVALID;
1697                 break;
1698         }
1699
1700         return state;
1701 }
1702
1703 static int extension_state_cb(const char *context, const char *exten, enum ast_extension_states state, void *data)
1704 {
1705         struct ao2_iterator miter, qiter;
1706         struct member *m;
1707         struct call_queue *q;
1708         int found = 0, device_state = extensionstate2devicestate(state);
1709
1710         qiter = ao2_iterator_init(queues, 0);
1711         while ((q = ao2_t_iterator_next(&qiter, "Iterate through queues"))) {
1712                 ao2_lock(q);
1713
1714                 miter = ao2_iterator_init(q->members, 0);
1715                 for (; (m = ao2_iterator_next(&miter)); ao2_ref(m, -1)) {
1716                         if (!strcmp(m->state_context, context) && !strcmp(m->state_exten, exten)) {
1717                                 update_status(q, m, device_state);
1718                                 ao2_ref(m, -1);
1719                                 found = 1;
1720                                 break;
1721                         }
1722                 }
1723                 ao2_iterator_destroy(&miter);
1724
1725                 ao2_unlock(q);
1726                 queue_t_unref(q, "Done with iterator");
1727         }
1728         ao2_iterator_destroy(&qiter);
1729
1730         if (found) {
1731                 ast_debug(1, "Extension '%s@%s' changed to state '%d' (%s)\n", exten, context, device_state, ast_devstate2str(device_state));
1732         } else {
1733                 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",
1734                           exten, context, device_state, ast_devstate2str(device_state));
1735         }
1736
1737         return 0;
1738 }
1739
1740 /*! \brief Return the current state of a member */
1741 static int get_queue_member_status(struct member *cur)
1742 {
1743         return ast_strlen_zero(cur->state_exten) ? ast_device_state(cur->state_interface) : extensionstate2devicestate(ast_extension_state(NULL, cur->state_context, cur->state_exten));
1744 }
1745
1746 /*! \brief allocate space for new queue member and set fields based on parameters passed */
1747 static struct member *create_queue_member(const char *interface, const char *membername, int penalty, int paused, const char *state_interface, int ringinuse)
1748 {
1749         struct member *cur;
1750
1751         if ((cur = ao2_alloc(sizeof(*cur), NULL))) {
1752                 cur->ringinuse = ringinuse;
1753                 cur->penalty = penalty;
1754                 cur->paused = paused;
1755                 ast_copy_string(cur->interface, interface, sizeof(cur->interface));
1756                 if (!ast_strlen_zero(state_interface)) {
1757                         ast_copy_string(cur->state_interface, state_interface, sizeof(cur->state_interface));
1758                 } else {
1759                         ast_copy_string(cur->state_interface, interface, sizeof(cur->state_interface));
1760                 }
1761                 if (!ast_strlen_zero(membername)) {
1762                         ast_copy_string(cur->membername, membername, sizeof(cur->membername));
1763                 } else {
1764                         ast_copy_string(cur->membername, interface, sizeof(cur->membername));
1765                 }
1766                 if (!strchr(cur->interface, '/')) {
1767                         ast_log(LOG_WARNING, "No location at interface '%s'\n", interface);
1768                 }
1769                 if (!strncmp(cur->state_interface, "hint:", 5)) {
1770                         char *tmp = ast_strdupa(cur->state_interface), *context = tmp;
1771                         char *exten = strsep(&context, "@") + 5;
1772
1773                         ast_copy_string(cur->state_exten, exten, sizeof(cur->state_exten));
1774                         ast_copy_string(cur->state_context, S_OR(context, "default"), sizeof(cur->state_context));
1775                 }
1776                 cur->status = get_queue_member_status(cur);
1777         }
1778
1779         return cur;
1780 }
1781
1782
1783 static int compress_char(const char c)
1784 {
1785         if (c < 32) {
1786                 return 0;
1787         } else if (c > 96) {
1788                 return c - 64;
1789         } 
1790         return c - 32;
1791 }
1792
1793 static int member_hash_fn(const void *obj, const int flags)
1794 {
1795         const struct member *mem = obj;
1796         const char *interface = (flags & OBJ_KEY) ? obj : mem->interface;
1797         const char *chname = strchr(interface, '/');
1798         int ret = 0, i;
1799
1800         if (!chname) {
1801                 chname = interface;
1802         }
1803         for (i = 0; i < 5 && chname[i]; i++) {
1804                 ret += compress_char(chname[i]) << (i * 6);
1805         }
1806         return ret;
1807 }
1808
1809 static int member_cmp_fn(void *obj1, void *obj2, int flags)
1810 {
1811         struct member *mem1 = obj1;
1812         struct member *mem2 = obj2;
1813         const char *interface = (flags & OBJ_KEY) ? obj2 : mem2->interface;
1814
1815         return strcasecmp(mem1->interface, interface) ? 0 : CMP_MATCH | CMP_STOP;
1816 }
1817
1818 /*!
1819  * \brief Initialize Queue default values.
1820  * \note the queue's lock  must be held before executing this function
1821 */
1822 static void init_queue(struct call_queue *q)
1823 {
1824         int i;
1825         struct penalty_rule *pr_iter;
1826
1827         q->dead = 0;
1828         q->retry = DEFAULT_RETRY;
1829         q->timeout = DEFAULT_TIMEOUT;
1830         q->maxlen = 0;
1831         q->announcefrequency = 0;
1832         q->minannouncefrequency = DEFAULT_MIN_ANNOUNCE_FREQUENCY;
1833         q->announceholdtime = 1;
1834         q->announcepositionlimit = 10; /* Default 10 positions */
1835         q->announceposition = ANNOUNCEPOSITION_YES; /* Default yes */
1836         q->roundingseconds = 0; /* Default - don't announce seconds */
1837         q->servicelevel = 0;
1838         q->ringinuse = 1;
1839         q->setinterfacevar = 0;
1840         q->setqueuevar = 0;
1841         q->setqueueentryvar = 0;
1842         q->autofill = autofill_default;
1843         q->montype = montype_default;
1844         q->monfmt[0] = '\0';
1845         q->reportholdtime = 0;
1846         q->wrapuptime = 0;
1847         q->penaltymemberslimit = 0;
1848         q->joinempty = 0;
1849         q->leavewhenempty = 0;
1850         q->memberdelay = 0;
1851         q->maskmemberstatus = 0;
1852         q->eventwhencalled = 0;
1853         q->weight = 0;
1854         q->timeoutrestart = 0;
1855         q->periodicannouncefrequency = 0;
1856         q->randomperiodicannounce = 0;
1857         q->numperiodicannounce = 0;
1858         q->autopause = QUEUE_AUTOPAUSE_OFF;
1859         q->timeoutpriority = TIMEOUT_PRIORITY_APP;
1860         q->autopausedelay = 0;
1861         if (!q->members) {
1862                 if (q->strategy == QUEUE_STRATEGY_LINEAR || q->strategy == QUEUE_STRATEGY_RRORDERED) {
1863                         /* linear strategy depends on order, so we have to place all members in a single bucket */
1864                         q->members = ao2_container_alloc(1, member_hash_fn, member_cmp_fn);
1865                 } else {
1866                         q->members = ao2_container_alloc(37, member_hash_fn, member_cmp_fn);
1867                 }
1868         }
1869         q->found = 1;
1870
1871         ast_string_field_set(q, sound_next, "queue-youarenext");
1872         ast_string_field_set(q, sound_thereare, "queue-thereare");
1873         ast_string_field_set(q, sound_calls, "queue-callswaiting");
1874         ast_string_field_set(q, queue_quantity1, "queue-quantity1");
1875         ast_string_field_set(q, queue_quantity2, "queue-quantity2");
1876         ast_string_field_set(q, sound_holdtime, "queue-holdtime");
1877         ast_string_field_set(q, sound_minutes, "queue-minutes");
1878         ast_string_field_set(q, sound_minute, "queue-minute");
1879         ast_string_field_set(q, sound_seconds, "queue-seconds");
1880         ast_string_field_set(q, sound_thanks, "queue-thankyou");
1881         ast_string_field_set(q, sound_reporthold, "queue-reporthold");
1882
1883         if (!q->sound_periodicannounce[0]) {
1884                 q->sound_periodicannounce[0] = ast_str_create(32);
1885         }
1886
1887         if (q->sound_periodicannounce[0]) {
1888                 ast_str_set(&q->sound_periodicannounce[0], 0, "queue-periodic-announce");
1889         }
1890
1891         for (i = 1; i < MAX_PERIODIC_ANNOUNCEMENTS; i++) {
1892                 if (q->sound_periodicannounce[i]) {
1893                         ast_str_set(&q->sound_periodicannounce[i], 0, "%s", "");
1894                 }
1895         }
1896
1897         while ((pr_iter = AST_LIST_REMOVE_HEAD(&q->rules,list))) {
1898                 ast_free(pr_iter);
1899         }
1900 }
1901
1902 static void clear_queue(struct call_queue *q)
1903 {
1904         q->holdtime = 0;
1905         q->callscompleted = 0;
1906         q->callsabandoned = 0;
1907         q->callscompletedinsl = 0;
1908         q->talktime = 0;
1909
1910         if (q->members) {
1911                 struct member *mem;
1912                 struct ao2_iterator mem_iter = ao2_iterator_init(q->members, 0);
1913                 while ((mem = ao2_iterator_next(&mem_iter))) {
1914                         mem->calls = 0;
1915                         mem->lastcall = 0;
1916                         ao2_ref(mem, -1);
1917                 }
1918                 ao2_iterator_destroy(&mem_iter);
1919         }
1920 }
1921
1922 /*!
1923  * \brief Change queue penalty by adding rule.
1924  *
1925  * Check rule for errors with time or fomatting, see if rule is relative to rest
1926  * of queue, iterate list of rules to find correct insertion point, insert and return.
1927  * \retval -1 on failure
1928  * \retval 0 on success
1929  * \note Call this with the rule_lists locked
1930 */
1931 static int insert_penaltychange(const char *list_name, const char *content, const int linenum)
1932 {
1933         char *timestr, *maxstr, *minstr, *contentdup;
1934         struct penalty_rule *rule = NULL, *rule_iter;
1935         struct rule_list *rl_iter;
1936         int penaltychangetime, inserted = 0;
1937
1938         if (!(rule = ast_calloc(1, sizeof(*rule)))) {
1939                 return -1;
1940         }
1941
1942         contentdup = ast_strdupa(content);
1943         
1944         if (!(maxstr = strchr(contentdup, ','))) {
1945                 ast_log(LOG_WARNING, "Improperly formatted penaltychange rule at line %d. Ignoring.\n", linenum);
1946                 ast_free(rule);
1947                 return -1;
1948         }
1949
1950         *maxstr++ = '\0';
1951         timestr = contentdup;
1952
1953         if ((penaltychangetime = atoi(timestr)) < 0) {
1954                 ast_log(LOG_WARNING, "Improper time parameter specified for penaltychange rule at line %d. Ignoring.\n", linenum);
1955                 ast_free(rule);
1956                 return -1;
1957         }
1958
1959         rule->time = penaltychangetime;
1960
1961         if ((minstr = strchr(maxstr,','))) {
1962                 *minstr++ = '\0';
1963         }
1964         
1965         /* The last check will evaluate true if either no penalty change is indicated for a given rule
1966          * OR if a min penalty change is indicated but no max penalty change is */
1967         if (*maxstr == '+' || *maxstr == '-' || *maxstr == '\0') {
1968                 rule->max_relative = 1;
1969         }
1970
1971         rule->max_value = atoi(maxstr);
1972
1973         if (!ast_strlen_zero(minstr)) {
1974                 if (*minstr == '+' || *minstr == '-') {
1975                         rule->min_relative = 1;
1976                 }
1977                 rule->min_value = atoi(minstr);
1978         } else { /*there was no minimum specified, so assume this means no change*/
1979                 rule->min_relative = 1;
1980         }
1981
1982         /*We have the rule made, now we need to insert it where it belongs*/
1983         AST_LIST_TRAVERSE(&rule_lists, rl_iter, list){
1984                 if (strcasecmp(rl_iter->name, list_name)) {
1985                         continue;
1986                 }
1987
1988                 AST_LIST_TRAVERSE_SAFE_BEGIN(&rl_iter->rules, rule_iter, list) {
1989                         if (rule->time < rule_iter->time) {
1990                                 AST_LIST_INSERT_BEFORE_CURRENT(rule, list);
1991                                 inserted = 1;
1992                                 break;
1993                         }
1994                 }
1995                 AST_LIST_TRAVERSE_SAFE_END;
1996         
1997                 if (!inserted) {
1998                         AST_LIST_INSERT_TAIL(&rl_iter->rules, rule, list);
1999                         inserted = 1;
2000                 }
2001
2002                 break;
2003         }
2004
2005         if (!inserted) {
2006                 ast_log(LOG_WARNING, "Unknown rule list name %s; ignoring.\n", list_name);
2007                 ast_free(rule);
2008                 return -1;
2009         }
2010         return 0;
2011 }
2012
2013 static void parse_empty_options(const char *value, enum empty_conditions *empty, int joinempty)
2014 {
2015         char *value_copy = ast_strdupa(value);
2016         char *option = NULL;
2017         while ((option = strsep(&value_copy, ","))) {
2018                 if (!strcasecmp(option, "paused")) {
2019                         *empty |= QUEUE_EMPTY_PAUSED;
2020                 } else if (!strcasecmp(option, "penalty")) {
2021                         *empty |= QUEUE_EMPTY_PENALTY;
2022                 } else if (!strcasecmp(option, "inuse")) {
2023                         *empty |= QUEUE_EMPTY_INUSE;
2024                 } else if (!strcasecmp(option, "ringing")) {
2025                         *empty |= QUEUE_EMPTY_RINGING;
2026                 } else if (!strcasecmp(option, "invalid")) {
2027                         *empty |= QUEUE_EMPTY_INVALID;
2028                 } else if (!strcasecmp(option, "wrapup")) {
2029                         *empty |= QUEUE_EMPTY_WRAPUP;
2030                 } else if (!strcasecmp(option, "unavailable")) {
2031                         *empty |= QUEUE_EMPTY_UNAVAILABLE;
2032                 } else if (!strcasecmp(option, "unknown")) {
2033                         *empty |= QUEUE_EMPTY_UNKNOWN;
2034                 } else if (!strcasecmp(option, "loose")) {
2035                         *empty = (QUEUE_EMPTY_PENALTY | QUEUE_EMPTY_INVALID);
2036                 } else if (!strcasecmp(option, "strict")) {
2037                         *empty = (QUEUE_EMPTY_PENALTY | QUEUE_EMPTY_INVALID | QUEUE_EMPTY_PAUSED | QUEUE_EMPTY_UNAVAILABLE);
2038                 } else if ((ast_false(option) && joinempty) || (ast_true(option) && !joinempty)) {
2039                         *empty = (QUEUE_EMPTY_PENALTY | QUEUE_EMPTY_INVALID | QUEUE_EMPTY_PAUSED);
2040                 } else if ((ast_false(option) && !joinempty) || (ast_true(option) && joinempty)) {
2041                         *empty = 0;
2042                 } else {
2043                         ast_log(LOG_WARNING, "Unknown option %s for '%s'\n", option, joinempty ? "joinempty" : "leavewhenempty");
2044                 }
2045         }
2046 }
2047
2048 /*! \brief Configure a queue parameter.
2049  * 
2050  * The failunknown flag is set for config files (and static realtime) to show
2051  * errors for unknown parameters. It is cleared for dynamic realtime to allow
2052  *  extra fields in the tables.
2053  * \note For error reporting, line number is passed for .conf static configuration,
2054  * for Realtime queues, linenum is -1.
2055 */
2056 static void queue_set_param(struct call_queue *q, const char *param, const char *val, int linenum, int failunknown)
2057 {
2058         if (!strcasecmp(param, "musicclass") || 
2059                 !strcasecmp(param, "music") || !strcasecmp(param, "musiconhold")) {
2060                 ast_string_field_set(q, moh, val);
2061         } else if (!strcasecmp(param, "announce")) {
2062                 ast_string_field_set(q, announce, val);
2063         } else if (!strcasecmp(param, "context")) {
2064                 ast_string_field_set(q, context, val);
2065         } else if (!strcasecmp(param, "timeout")) {
2066                 q->timeout = atoi(val);
2067                 if (q->timeout < 0) {
2068                         q->timeout = DEFAULT_TIMEOUT;
2069                 }
2070         } else if (!strcasecmp(param, "ringinuse")) {
2071                 q->ringinuse = ast_true(val);
2072         } else if (!strcasecmp(param, "setinterfacevar")) {
2073                 q->setinterfacevar = ast_true(val);
2074         } else if (!strcasecmp(param, "setqueuevar")) {
2075                 q->setqueuevar = ast_true(val);
2076         } else if (!strcasecmp(param, "setqueueentryvar")) {
2077                 q->setqueueentryvar = ast_true(val);
2078         } else if (!strcasecmp(param, "monitor-format")) {
2079                 ast_copy_string(q->monfmt, val, sizeof(q->monfmt));
2080         } else if (!strcasecmp(param, "membermacro")) {
2081                 ast_string_field_set(q, membermacro, val);
2082         } else if (!strcasecmp(param, "membergosub")) {
2083                 ast_string_field_set(q, membergosub, val);
2084         } else if (!strcasecmp(param, "queue-youarenext")) {
2085                 ast_string_field_set(q, sound_next, val);
2086         } else if (!strcasecmp(param, "queue-thereare")) {
2087                 ast_string_field_set(q, sound_thereare, val);
2088         } else if (!strcasecmp(param, "queue-callswaiting")) {
2089                 ast_string_field_set(q, sound_calls, val);
2090         } else if (!strcasecmp(param, "queue-quantity1")) {
2091                 ast_string_field_set(q, queue_quantity1, val);
2092         } else if (!strcasecmp(param, "queue-quantity2")) {
2093                 ast_string_field_set(q, queue_quantity2, val);
2094         } else if (!strcasecmp(param, "queue-holdtime")) {
2095                 ast_string_field_set(q, sound_holdtime, val);
2096         } else if (!strcasecmp(param, "queue-minutes")) {
2097                 ast_string_field_set(q, sound_minutes, val);
2098         } else if (!strcasecmp(param, "queue-minute")) {
2099                 ast_string_field_set(q, sound_minute, val);
2100         } else if (!strcasecmp(param, "queue-seconds")) {
2101                 ast_string_field_set(q, sound_seconds, val);
2102         } else if (!strcasecmp(param, "queue-thankyou")) {
2103                 ast_string_field_set(q, sound_thanks, val);
2104         } else if (!strcasecmp(param, "queue-callerannounce")) {
2105                 ast_string_field_set(q, sound_callerannounce, val);
2106         } else if (!strcasecmp(param, "queue-reporthold")) {
2107                 ast_string_field_set(q, sound_reporthold, val);
2108         } else if (!strcasecmp(param, "announce-frequency")) {
2109                 q->announcefrequency = atoi(val);
2110         } else if (!strcasecmp(param, "min-announce-frequency")) {
2111                 q->minannouncefrequency = atoi(val);
2112                 ast_debug(1, "%s=%s for queue '%s'\n", param, val, q->name);
2113         } else if (!strcasecmp(param, "announce-round-seconds")) {
2114                 q->roundingseconds = atoi(val);
2115                 /* Rounding to any other values just doesn't make sense... */
2116                 if (!(q->roundingseconds == 0 || q->roundingseconds == 5 || q->roundingseconds == 10
2117                         || q->roundingseconds == 15 || q->roundingseconds == 20 || q->roundingseconds == 30)) {
2118                         if (linenum >= 0) {
2119                                 ast_log(LOG_WARNING, "'%s' isn't a valid value for %s "
2120                                         "using 0 instead for queue '%s' at line %d of queues.conf\n",
2121                                         val, param, q->name, linenum);
2122                         } else {
2123                                 ast_log(LOG_WARNING, "'%s' isn't a valid value for %s "
2124                                         "using 0 instead for queue '%s'\n", val, param, q->name);
2125                         }
2126                         q->roundingseconds=0;
2127                 }
2128         } else if (!strcasecmp(param, "announce-holdtime")) {
2129                 if (!strcasecmp(val, "once")) {
2130                         q->announceholdtime = ANNOUNCEHOLDTIME_ONCE;
2131                 } else if (ast_true(val)) {
2132                         q->announceholdtime = ANNOUNCEHOLDTIME_ALWAYS;
2133                 } else {
2134                         q->announceholdtime = 0;
2135                 }
2136         } else if (!strcasecmp(param, "announce-position")) {
2137                 if (!strcasecmp(val, "limit")) {
2138                         q->announceposition = ANNOUNCEPOSITION_LIMIT;
2139                 } else if (!strcasecmp(val, "more")) {
2140                         q->announceposition = ANNOUNCEPOSITION_MORE_THAN;
2141                 } else if (ast_true(val)) {
2142                         q->announceposition = ANNOUNCEPOSITION_YES;
2143                 } else {
2144                         q->announceposition = ANNOUNCEPOSITION_NO;
2145                 }
2146         } else if (!strcasecmp(param, "announce-position-limit")) {
2147                 q->announcepositionlimit = atoi(val);
2148         } else if (!strcasecmp(param, "periodic-announce")) {
2149                 if (strchr(val, ',')) {
2150                         char *s, *buf = ast_strdupa(val);
2151                         unsigned int i = 0;
2152
2153                         while ((s = strsep(&buf, ",|"))) {
2154                                 if (!q->sound_periodicannounce[i]) {
2155                                         q->sound_periodicannounce[i] = ast_str_create(16);
2156                                 }
2157                                 ast_str_set(&q->sound_periodicannounce[i], 0, "%s", s);
2158                                 i++;
2159                                 if (i == MAX_PERIODIC_ANNOUNCEMENTS) {
2160                                         break;
2161                                 }
2162                         }
2163                         q->numperiodicannounce = i;
2164                 } else {
2165                         ast_str_set(&q->sound_periodicannounce[0], 0, "%s", val);
2166                         q->numperiodicannounce = 1;
2167                 }
2168         } else if (!strcasecmp(param, "periodic-announce-frequency")) {
2169                 q->periodicannouncefrequency = atoi(val);
2170         } else if (!strcasecmp(param, "relative-periodic-announce")) {
2171                 q->relativeperiodicannounce = ast_true(val);
2172         } else if (!strcasecmp(param, "random-periodic-announce")) {
2173                 q->randomperiodicannounce = ast_true(val);
2174         } else if (!strcasecmp(param, "retry")) {
2175                 q->retry = atoi(val);
2176                 if (q->retry <= 0) {
2177                         q->retry = DEFAULT_RETRY;
2178                 }
2179         } else if (!strcasecmp(param, "wrapuptime")) {
2180                 q->wrapuptime = atoi(val);
2181         } else if (!strcasecmp(param, "penaltymemberslimit")) {
2182                 if ((sscanf(val, "%10d", &q->penaltymemberslimit) != 1)) {
2183                         q->penaltymemberslimit = 0;
2184                 }
2185         } else if (!strcasecmp(param, "autofill")) {
2186                 q->autofill = ast_true(val);
2187         } else if (!strcasecmp(param, "monitor-type")) {
2188                 if (!strcasecmp(val, "mixmonitor")) {
2189                         q->montype = 1;
2190                 }
2191         } else if (!strcasecmp(param, "autopause")) {
2192                 q->autopause = autopause2int(val);
2193         } else if (!strcasecmp(param, "autopausedelay")) {
2194                 q->autopausedelay = atoi(val);
2195         } else if (!strcasecmp(param, "autopausebusy")) {
2196                 q->autopausebusy = ast_true(val);
2197         } else if (!strcasecmp(param, "autopauseunavail")) {
2198                 q->autopauseunavail = ast_true(val);
2199         } else if (!strcasecmp(param, "maxlen")) {
2200                 q->maxlen = atoi(val);
2201                 if (q->maxlen < 0) {
2202                         q->maxlen = 0;
2203                 }
2204         } else if (!strcasecmp(param, "servicelevel")) {
2205                 q->servicelevel= atoi(val);
2206         } else if (!strcasecmp(param, "strategy")) {
2207                 int strategy;
2208
2209                 /* We are a static queue and already have set this, no need to do it again */
2210                 if (failunknown) {
2211                         return;
2212                 }
2213                 strategy = strat2int(val);
2214                 if (strategy < 0) {
2215                         ast_log(LOG_WARNING, "'%s' isn't a valid strategy for queue '%s', using ringall instead\n",
2216                                 val, q->name);
2217                         q->strategy = QUEUE_STRATEGY_RINGALL;
2218                 }
2219                 if (strategy == q->strategy) {
2220                         return;
2221                 }
2222                 if (strategy == QUEUE_STRATEGY_LINEAR) {
2223                         ast_log(LOG_WARNING, "Changing to the linear strategy currently requires asterisk to be restarted.\n");
2224                         return;
2225                 }
2226                 q->strategy = strategy;
2227         } else if (!strcasecmp(param, "joinempty")) {
2228                 parse_empty_options(val, &q->joinempty, 1);
2229         } else if (!strcasecmp(param, "leavewhenempty")) {
2230                 parse_empty_options(val, &q->leavewhenempty, 0);
2231         } else if (!strcasecmp(param, "eventmemberstatus")) {
2232                 q->maskmemberstatus = !ast_true(val);
2233         } else if (!strcasecmp(param, "eventwhencalled")) {
2234                 if (!strcasecmp(val, "vars")) {
2235                         q->eventwhencalled = QUEUE_EVENT_VARIABLES;
2236                 } else {
2237                         q->eventwhencalled = ast_true(val) ? 1 : 0;
2238                 }
2239         } else if (!strcasecmp(param, "reportholdtime")) {
2240                 q->reportholdtime = ast_true(val);
2241         } else if (!strcasecmp(param, "memberdelay")) {
2242                 q->memberdelay = atoi(val);
2243         } else if (!strcasecmp(param, "weight")) {
2244                 q->weight = atoi(val);
2245         } else if (!strcasecmp(param, "timeoutrestart")) {
2246                 q->timeoutrestart = ast_true(val);
2247         } else if (!strcasecmp(param, "defaultrule")) {
2248                 ast_string_field_set(q, defaultrule, val);
2249         } else if (!strcasecmp(param, "timeoutpriority")) {
2250                 if (!strcasecmp(val, "conf")) {
2251                         q->timeoutpriority = TIMEOUT_PRIORITY_CONF;
2252                 } else {
2253                         q->timeoutpriority = TIMEOUT_PRIORITY_APP;
2254                 }
2255         } else if (failunknown) {
2256                 if (linenum >= 0) {
2257                         ast_log(LOG_WARNING, "Unknown keyword in queue '%s': %s at line %d of queues.conf\n",
2258                                 q->name, param, linenum);
2259                 } else {
2260                         ast_log(LOG_WARNING, "Unknown keyword in queue '%s': %s\n", q->name, param);
2261                 }
2262         }
2263 }
2264
2265 /*!
2266  * \brief Find rt member record to update otherwise create one.
2267  *
2268  * Search for member in queue, if found update penalty/paused state,
2269  * if no member exists create one flag it as a RT member and add to queue member list.
2270 */
2271 static void rt_handle_member_record(struct call_queue *q, char *interface, struct ast_config *member_config)
2272 {
2273         struct member *m;
2274         struct ao2_iterator mem_iter;
2275         int penalty = 0;
2276         int paused  = 0;
2277         int found = 0;
2278         int ringinuse = q->ringinuse;
2279
2280         const char *config_val;
2281         const char *rt_uniqueid = ast_variable_retrieve(member_config, interface, "uniqueid");
2282         const char *membername = S_OR(ast_variable_retrieve(member_config, interface, "membername"), interface);
2283         const char *state_interface = S_OR(ast_variable_retrieve(member_config, interface, "state_interface"), interface);
2284         const char *penalty_str = ast_variable_retrieve(member_config, interface, "penalty");
2285         const char *paused_str = ast_variable_retrieve(member_config, interface, "paused");
2286
2287         if (ast_strlen_zero(rt_uniqueid)) {
2288                 ast_log(LOG_WARNING, "Realtime field uniqueid is empty for member %s\n", S_OR(membername, "NULL"));
2289                 return;
2290         }
2291
2292         if (penalty_str) {
2293                 penalty = atoi(penalty_str);
2294                 if ((penalty < 0) && negative_penalty_invalid) {
2295                         return;
2296                 } else if (penalty < 0) {
2297                         penalty = 0;
2298                 }
2299         }
2300
2301         if (paused_str) {
2302                 paused = atoi(paused_str);
2303                 if (paused < 0) {
2304                         paused = 0;
2305                 }
2306         }
2307
2308         if ((config_val = ast_variable_retrieve(member_config, interface, realtime_ringinuse_field))) {
2309                 if (ast_true(config_val)) {
2310                         ringinuse = 1;
2311                 } else if (ast_false(config_val)) {
2312                         ringinuse = 0;
2313                 } else {
2314                         ast_log(LOG_WARNING, "Invalid value of '%s' field for %s in queue '%s'\n", realtime_ringinuse_field, interface, q->name);
2315                 }
2316         }
2317
2318         /* Find member by realtime uniqueid and update */
2319         mem_iter = ao2_iterator_init(q->members, 0);
2320         while ((m = ao2_iterator_next(&mem_iter))) {
2321                 if (!strcasecmp(m->rt_uniqueid, rt_uniqueid)) {
2322                         m->dead = 0;    /* Do not delete this one. */
2323                         ast_copy_string(m->rt_uniqueid, rt_uniqueid, sizeof(m->rt_uniqueid));
2324                         if (paused_str) {
2325                                 m->paused = paused;
2326                         }
2327                         if (strcasecmp(state_interface, m->state_interface)) {
2328                                 ast_copy_string(m->state_interface, state_interface, sizeof(m->state_interface));
2329                         }
2330                         m->penalty = penalty;
2331                         m->ringinuse = ringinuse;
2332                         found = 1;
2333                         ao2_ref(m, -1);
2334                         break;
2335                 }
2336                 ao2_ref(m, -1);
2337         }
2338         ao2_iterator_destroy(&mem_iter);
2339
2340         /* Create a new member */
2341         if (!found) {
2342                 if ((m = create_queue_member(interface, membername, penalty, paused, state_interface, ringinuse))) {
2343                         m->dead = 0;
2344                         m->realtime = 1;
2345                         ast_copy_string(m->rt_uniqueid, rt_uniqueid, sizeof(m->rt_uniqueid));
2346                         if (!log_membername_as_agent) {
2347                                 ast_queue_log(q->name, "REALTIME", m->interface, "ADDMEMBER", "%s", paused ? "PAUSED" : "");
2348                         } else {
2349                                 ast_queue_log(q->name, "REALTIME", m->membername, "ADDMEMBER", "%s", paused ? "PAUSED" : "");
2350                         }
2351                         ao2_link(q->members, m);
2352                         ao2_ref(m, -1);
2353                         m = NULL;
2354                 }
2355         }
2356 }
2357
2358 /*! \brief Iterate through queue's member list and delete them */
2359 static void free_members(struct call_queue *q, int all)
2360 {
2361         /* Free non-dynamic members */
2362         struct member *cur;
2363         struct ao2_iterator mem_iter = ao2_iterator_init(q->members, 0);
2364
2365         while ((cur = ao2_iterator_next(&mem_iter))) {
2366                 if (all || !cur->dynamic) {
2367                         ao2_unlink(q->members, cur);
2368                 }
2369                 ao2_ref(cur, -1);
2370         }
2371         ao2_iterator_destroy(&mem_iter);
2372 }
2373
2374 /*! \brief Free queue's member list then its string fields */
2375 static void destroy_queue(void *obj)
2376 {
2377         struct call_queue *q = obj;
2378         int i;
2379
2380         free_members(q, 1);
2381         ast_string_field_free_memory(q);
2382         for (i = 0; i < MAX_PERIODIC_ANNOUNCEMENTS; i++) {
2383                 if (q->sound_periodicannounce[i]) {
2384                         free(q->sound_periodicannounce[i]);
2385                 }
2386         }
2387         ao2_ref(q->members, -1);
2388 }
2389
2390 static struct call_queue *alloc_queue(const char *queuename)
2391 {
2392         struct call_queue *q;
2393
2394         if ((q = ao2_t_alloc(sizeof(*q), destroy_queue, "Allocate queue"))) {
2395                 if (ast_string_field_init(q, 64)) {
2396                         queue_t_unref(q, "String field allocation failed");
2397                         return NULL;
2398                 }
2399                 ast_string_field_set(q, name, queuename);
2400         }
2401         return q;
2402 }
2403
2404 /*!
2405  * \brief Reload a single queue via realtime.
2406  *
2407  * Check for statically defined queue first, check if deleted RT queue,
2408  * check for new RT queue, if queue vars are not defined init them with defaults.
2409  * reload RT queue vars, set RT queue members dead and reload them, return finished queue.
2410  * \retval the queue,
2411  * \retval NULL if it doesn't exist.
2412  * \note Should be called with the "queues" container locked.
2413 */
2414 static struct call_queue *find_queue_by_name_rt(const char *queuename, struct ast_variable *queue_vars, struct ast_config *member_config)
2415 {
2416         struct ast_variable *v;
2417         struct call_queue *q, tmpq = {
2418                 .name = queuename,
2419         };
2420         struct member *m;
2421         struct ao2_iterator mem_iter;
2422         char *interface = NULL;
2423         const char *tmp_name;
2424         char *tmp;
2425         char tmpbuf[64];        /* Must be longer than the longest queue param name. */
2426
2427         /* Static queues override realtime. */
2428         if ((q = ao2_t_find(queues, &tmpq, OBJ_POINTER, "Check if static queue exists"))) {
2429                 ao2_lock(q);
2430                 if (!q->realtime) {
2431                         if (q->dead) {
2432                                 ao2_unlock(q);
2433                                 queue_t_unref(q, "Queue is dead; can't return it");
2434                                 return NULL;
2435                         } 
2436                         ast_log(LOG_WARNING, "Static queue '%s' already exists. Not loading from realtime\n", q->name);
2437                         ao2_unlock(q);
2438                         return q;
2439                 }
2440         } else if (!member_config) {
2441                 /* Not found in the list, and it's not realtime ... */
2442                 return NULL;
2443         }
2444         /* Check if queue is defined in realtime. */
2445         if (!queue_vars) {
2446                 /* Delete queue from in-core list if it has been deleted in realtime. */
2447                 if (q) {
2448                         /*! \note Hmm, can't seem to distinguish a DB failure from a not
2449                            found condition... So we might delete an in-core queue
2450                            in case of DB failure. */
2451                         ast_debug(1, "Queue %s not found in realtime.\n", queuename);
2452
2453                         q->dead = 1;
2454                         /* Delete if unused (else will be deleted when last caller leaves). */
2455                         queues_t_unlink(queues, q, "Unused; removing from container");
2456                         ao2_unlock(q);
2457                         queue_t_unref(q, "Queue is dead; can't return it");
2458                 }
2459                 return NULL;
2460         }
2461
2462         /* Create a new queue if an in-core entry does not exist yet. */
2463         if (!q) {
2464                 struct ast_variable *tmpvar = NULL;
2465                 if (!(q = alloc_queue(queuename))) {
2466                         return NULL;
2467                 }
2468                 ao2_lock(q);
2469                 clear_queue(q);
2470                 q->realtime = 1;
2471                 /*Before we initialize the queue, we need to set the strategy, so that linear strategy
2472                  * will allocate the members properly
2473                  */
2474                 for (tmpvar = queue_vars; tmpvar; tmpvar = tmpvar->next) {
2475                         if (!strcasecmp(tmpvar->name, "strategy")) {
2476                                 q->strategy = strat2int(tmpvar->value);
2477                                 if (q->strategy < 0) {
2478                                         ast_log(LOG_WARNING, "'%s' isn't a valid strategy for queue '%s', using ringall instead\n",
2479                                         tmpvar->value, q->name);
2480                                         q->strategy = QUEUE_STRATEGY_RINGALL;
2481                                 }
2482                                 break;
2483                         }
2484                 }
2485                 /* We traversed all variables and didn't find a strategy */
2486                 if (!tmpvar) {
2487                         q->strategy = QUEUE_STRATEGY_RINGALL;
2488                 }
2489                 queues_t_link(queues, q, "Add queue to container");
2490         }
2491         init_queue(q);          /* Ensure defaults for all parameters not set explicitly. */
2492
2493         memset(tmpbuf, 0, sizeof(tmpbuf));
2494         for (v = queue_vars; v; v = v->next) {
2495                 /* Convert to dashes `-' from underscores `_' as the latter are more SQL friendly. */
2496                 if ((tmp = strchr(v->name, '_'))) {
2497                         ast_copy_string(tmpbuf, v->name, sizeof(tmpbuf));
2498                         tmp_name = tmpbuf;
2499                         tmp = tmpbuf;
2500                         while ((tmp = strchr(tmp, '_'))) {
2501                                 *tmp++ = '-';
2502                         }
2503                 } else {
2504                         tmp_name = v->name;
2505                 }
2506
2507                 /* NULL values don't get returned from realtime; blank values should
2508                  * still get set.  If someone doesn't want a value to be set, they
2509                  * should set the realtime column to NULL, not blank. */
2510                 queue_set_param(q, tmp_name, v->value, -1, 0);
2511         }
2512
2513         /* Temporarily set realtime members dead so we can detect deleted ones. */
2514         mem_iter = ao2_iterator_init(q->members, 0);
2515         while ((m = ao2_iterator_next(&mem_iter))) {
2516                 if (m->realtime) {
2517                         m->dead = 1;
2518                 }
2519                 ao2_ref(m, -1);
2520         }
2521         ao2_iterator_destroy(&mem_iter);
2522
2523         while ((interface = ast_category_browse(member_config, interface))) {
2524                 rt_handle_member_record(q, interface, member_config);
2525         }
2526
2527         /* Delete all realtime members that have been deleted in DB. */
2528         mem_iter = ao2_iterator_init(q->members, 0);
2529         while ((m = ao2_iterator_next(&mem_iter))) {
2530                 if (m->dead) {
2531                         if (ast_strlen_zero(m->membername) || !log_membername_as_agent) {
2532                                 ast_queue_log(q->name, "REALTIME", m->interface, "REMOVEMEMBER", "%s", "");
2533                         } else {
2534                                 ast_queue_log(q->name, "REALTIME", m->membername, "REMOVEMEMBER", "%s", "");
2535                         }
2536                         ao2_unlink(q->members, m);
2537                 }
2538                 ao2_ref(m, -1);
2539         }
2540         ao2_iterator_destroy(&mem_iter);
2541
2542         ao2_unlock(q);
2543
2544         return q;
2545 }
2546
2547 /*!
2548  * note  */
2549
2550 /*!
2551  * \internal
2552  * \brief Returns reference to the named queue. If the queue is realtime, it will load the queue as well.
2553  * \param queuename - name of the desired queue
2554  *
2555  * \retval the queue
2556  * \retval NULL if it doesn't exist
2557  */
2558 static struct call_queue *find_load_queue_rt_friendly(const char *queuename)
2559 {
2560         struct ast_variable *queue_vars;
2561         struct ast_config *member_config = NULL;
2562         struct call_queue *q = NULL, tmpq = {
2563                 .name = queuename,
2564         };
2565         int prev_weight = 0;
2566
2567         /* Find the queue in the in-core list first. */
2568         q = ao2_t_find(queues, &tmpq, OBJ_POINTER, "Look for queue in memory first");
2569
2570         if (!q || q->realtime) {
2571                 /*! \note Load from realtime before taking the "queues" container lock, to avoid blocking all
2572                    queue operations while waiting for the DB.
2573
2574                    This will be two separate database transactions, so we might
2575                    see queue parameters as they were before another process
2576                    changed the queue and member list as it was after the change.
2577                    Thus we might see an empty member list when a queue is
2578                    deleted. In practise, this is unlikely to cause a problem. */
2579
2580                 queue_vars = ast_load_realtime("queues", "name", queuename, SENTINEL);
2581                 if (queue_vars) {
2582                         member_config = ast_load_realtime_multientry("queue_members", "interface LIKE", "%", "queue_name", queuename, SENTINEL);
2583                         if (!member_config) {
2584                                 ast_debug(1, "No queue_members defined in config extconfig.conf\n");
2585                                 member_config = ast_config_new();
2586                         }
2587                 }
2588                 if (q) {
2589                         prev_weight = q->weight ? 1 : 0;
2590                         queue_t_unref(q, "Need to find realtime queue");
2591                 }
2592
2593                 q = find_queue_by_name_rt(queuename, queue_vars, member_config);
2594                 ast_config_destroy(member_config);
2595                 ast_variables_destroy(queue_vars);
2596
2597                 /* update the use_weight value if the queue's has gained or lost a weight */
2598                 if (q) {
2599                         if (!q->weight && prev_weight) {
2600                                 ast_atomic_fetchadd_int(&use_weight, -1);
2601                         }
2602                         if (q->weight && !prev_weight) {
2603                                 ast_atomic_fetchadd_int(&use_weight, +1);
2604                         }
2605                 }
2606                 /* Other cases will end up with the proper value for use_weight */
2607         } else {
2608                 update_realtime_members(q);
2609         }
2610         return q;
2611 }
2612
2613 static int update_realtime_member_field(struct member *mem, const char *queue_name, const char *field, const char *value)
2614 {
2615         int ret = -1;
2616
2617         if (ast_strlen_zero(mem->rt_uniqueid)) {
2618                 return ret;
2619         }
2620
2621         if ((ast_update_realtime("queue_members", "uniqueid", mem->rt_uniqueid, field, value, SENTINEL)) > 0) {
2622                 ret = 0;
2623         }
2624
2625         return ret;
2626 }
2627
2628
2629 static void update_realtime_members(struct call_queue *q)
2630 {
2631         struct ast_config *member_config = NULL;
2632         struct member *m;
2633         char *interface = NULL;
2634         struct ao2_iterator mem_iter;
2635
2636         if (!(member_config = ast_load_realtime_multientry("queue_members", "interface LIKE", "%", "queue_name", q->name , SENTINEL))) {
2637                 /*This queue doesn't have realtime members*/
2638                 ast_debug(3, "Queue %s has no realtime members defined. No need for update\n", q->name);
2639                 return;
2640         }
2641
2642         ao2_lock(q);
2643
2644         /* Temporarily set realtime  members dead so we can detect deleted ones.*/
2645         mem_iter = ao2_iterator_init(q->members, 0);
2646         while ((m = ao2_iterator_next(&mem_iter))) {
2647                 if (m->realtime) {
2648                         m->dead = 1;
2649                 }
2650                 ao2_ref(m, -1);
2651         }
2652         ao2_iterator_destroy(&mem_iter);
2653
2654         while ((interface = ast_category_browse(member_config, interface))) {
2655                 rt_handle_member_record(q, interface, member_config);
2656         }
2657
2658         /* Delete all realtime members that have been deleted in DB. */
2659         mem_iter = ao2_iterator_init(q->members, 0);
2660         while ((m = ao2_iterator_next(&mem_iter))) {
2661                 if (m->dead) {
2662                         if (ast_strlen_zero(m->membername) || !log_membername_as_agent) {
2663                                 ast_queue_log(q->name, "REALTIME", m->interface, "REMOVEMEMBER", "%s", "");
2664                         } else {
2665                                 ast_queue_log(q->name, "REALTIME", m->membername, "REMOVEMEMBER", "%s", "");
2666                         }
2667                         ao2_unlink(q->members, m);
2668                 }
2669                 ao2_ref(m, -1);
2670         }
2671         ao2_iterator_destroy(&mem_iter);
2672         ao2_unlock(q);
2673         ast_config_destroy(member_config);
2674 }
2675
2676 static int join_queue(char *queuename, struct queue_ent *qe, enum queue_result *reason, int position)
2677 {
2678         struct call_queue *q;
2679         struct queue_ent *cur, *prev = NULL;
2680         int res = -1;
2681         int pos = 0;
2682         int inserted = 0;
2683
2684         if (!(q = find_load_queue_rt_friendly(queuename))) {
2685                 return res;
2686         }
2687         ao2_lock(q);
2688
2689         /* This is our one */
2690         if (q->joinempty) {
2691                 int status = 0;
2692                 if ((status = get_member_status(q, qe->max_penalty, qe->min_penalty, q->joinempty))) {
2693                         *reason = QUEUE_JOINEMPTY;
2694                         ao2_unlock(q);
2695                         queue_t_unref(q, "Done with realtime queue");
2696                         return res;
2697                 }
2698         }
2699         if (*reason == QUEUE_UNKNOWN && q->maxlen && (q->count >= q->maxlen)) {
2700                 *reason = QUEUE_FULL;
2701         } else if (*reason == QUEUE_UNKNOWN) {
2702                 /* There's space for us, put us at the right position inside
2703                  * the queue.
2704                  * Take into account the priority of the calling user */
2705                 inserted = 0;
2706                 prev = NULL;
2707                 cur = q->head;
2708                 while (cur) {
2709                         /* We have higher priority than the current user, enter
2710                          * before him, after all the other users with priority
2711                          * higher or equal to our priority. */
2712                         if ((!inserted) && (qe->prio > cur->prio)) {
2713                                 insert_entry(q, prev, qe, &pos);
2714                                 inserted = 1;
2715                         }
2716                         /* <= is necessary for the position comparison because it may not be possible to enter
2717                          * at our desired position since higher-priority callers may have taken the position we want
2718                          */
2719                         if (!inserted && (qe->prio >= cur->prio) && position && (position <= pos + 1)) {
2720                                 insert_entry(q, prev, qe, &pos);
2721                                 /*pos is incremented inside insert_entry, so don't need to add 1 here*/
2722                                 if (position < pos) {
2723                                         ast_log(LOG_NOTICE, "Asked to be inserted at position %d but forced into position %d due to higher priority callers\n", position, pos);
2724                                 }
2725                                 inserted = 1;
2726                         }
2727                         cur->pos = ++pos;
2728                         prev = cur;
2729                         cur = cur->next;
2730                 }
2731                 /* No luck, join at the end of the queue */
2732                 if (!inserted) {
2733                         insert_entry(q, prev, qe, &pos);
2734                 }
2735                 ast_copy_string(qe->moh, q->moh, sizeof(qe->moh));
2736                 ast_copy_string(qe->announce, q->announce, sizeof(qe->announce));
2737                 ast_copy_string(qe->context, q->context, sizeof(qe->context));
2738                 q->count++;
2739                 res = 0;
2740                 ast_manager_event(qe->chan, EVENT_FLAG_CALL, "Join",
2741                         "Channel: %s\r\n"
2742                         "CallerIDNum: %s\r\n"
2743                         "CallerIDName: %s\r\n"
2744                         "ConnectedLineNum: %s\r\n"
2745                         "ConnectedLineName: %s\r\n"
2746                         "Queue: %s\r\n"
2747                         "Position: %d\r\n"
2748                         "Count: %d\r\n"
2749                         "Uniqueid: %s\r\n",
2750                         ast_channel_name(qe->chan),
2751                         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> */
2752                         S_COR(ast_channel_caller(qe->chan)->id.name.valid, ast_channel_caller(qe->chan)->id.name.str, "unknown"),
2753                         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> */
2754                         S_COR(ast_channel_connected(qe->chan)->id.name.valid, ast_channel_connected(qe->chan)->id.name.str, "unknown"),
2755                         q->name, qe->pos, q->count, ast_channel_uniqueid(qe->chan));
2756                 ast_debug(1, "Queue '%s' Join, Channel '%s', Position '%d'\n", q->name, ast_channel_name(qe->chan), qe->pos );
2757         }
2758         ao2_unlock(q);
2759         queue_t_unref(q, "Done with realtime queue");
2760
2761         return res;
2762 }
2763
2764 static int play_file(struct ast_channel *chan, const char *filename)
2765 {
2766         int res;
2767
2768         if (ast_strlen_zero(filename)) {
2769                 return 0;
2770         }
2771
2772         if (!ast_fileexists(filename, NULL, ast_channel_language(chan))) {
2773                 return 0;
2774         }
2775
2776         ast_stopstream(chan);
2777
2778         res = ast_streamfile(chan, filename, ast_channel_language(chan));
2779         if (!res) {
2780                 res = ast_waitstream(chan, AST_DIGIT_ANY);
2781         }
2782
2783         ast_stopstream(chan);
2784
2785         return res;
2786 }
2787
2788 /*!
2789  * \brief Check for valid exit from queue via goto
2790  * \retval 0 if failure
2791  * \retval 1 if successful
2792 */
2793 static int valid_exit(struct queue_ent *qe, char digit)
2794 {
2795         int digitlen = strlen(qe->digits);
2796
2797         /* Prevent possible buffer overflow */
2798         if (digitlen < sizeof(qe->digits) - 2) {
2799                 qe->digits[digitlen] = digit;
2800                 qe->digits[digitlen + 1] = '\0';
2801         } else {
2802                 qe->digits[0] = '\0';
2803                 return 0;
2804         }
2805
2806         /* If there's no context to goto, short-circuit */
2807         if (ast_strlen_zero(qe->context)) {
2808                 return 0;
2809         }
2810
2811         /* If the extension is bad, then reset the digits to blank */
2812         if (!ast_canmatch_extension(qe->chan, qe->context, qe->digits, 1,
2813                 S_COR(ast_channel_caller(qe->chan)->id.number.valid, ast_channel_caller(qe->chan)->id.number.str, NULL))) {
2814                 qe->digits[0] = '\0';
2815                 return 0;
2816         }
2817
2818         /* We have an exact match */
2819         if (!ast_goto_if_exists(qe->chan, qe->context, qe->digits, 1)) {
2820                 qe->valid_digits = 1;
2821                 /* Return 1 on a successful goto */
2822                 return 1;
2823         }
2824
2825         return 0;
2826 }
2827
2828 static int say_position(struct queue_ent *qe, int ringing)
2829 {
2830         int res = 0, avgholdmins, avgholdsecs, announceposition = 0;
2831         int say_thanks = 1;
2832         time_t now;
2833
2834         /* Let minannouncefrequency seconds pass between the start of each position announcement */
2835         time(&now);
2836         if ((now - qe->last_pos) < qe->parent->minannouncefrequency) {
2837                 return 0;
2838         }
2839
2840         /* If either our position has changed, or we are over the freq timer, say position */
2841         if ((qe->last_pos_said == qe->pos) && ((now - qe->last_pos) < qe->parent->announcefrequency)) {
2842                 return 0;
2843         }
2844
2845         if (ringing) {
2846                 ast_indicate(qe->chan,-1);
2847         } else {
2848                 ast_moh_stop(qe->chan);
2849         }
2850
2851         if (qe->parent->announceposition == ANNOUNCEPOSITION_YES ||
2852                 qe->parent->announceposition == ANNOUNCEPOSITION_MORE_THAN ||
2853                 (qe->parent->announceposition == ANNOUNCEPOSITION_LIMIT &&
2854                 qe->pos <= qe->parent->announcepositionlimit)) {
2855                         announceposition = 1;
2856         }
2857
2858
2859         if (announceposition == 1) {
2860                 /* Say we're next, if we are */
2861                 if (qe->pos == 1) {
2862                         res = play_file(qe->chan, qe->parent->sound_next);
2863                         if (res) {
2864                                 goto playout;
2865                         }
2866                         goto posout;
2867                 } else {
2868                         if (qe->parent->announceposition == ANNOUNCEPOSITION_MORE_THAN && qe->pos > qe->parent->announcepositionlimit){
2869                                 /* More than Case*/
2870                                 res = play_file(qe->chan, qe->parent->queue_quantity1);
2871                                 if (res) {
2872                                         goto playout;
2873                                 }
2874                                 res = ast_say_number(qe->chan, qe->parent->announcepositionlimit, AST_DIGIT_ANY, ast_channel_language(qe->chan), NULL); /* Needs gender */
2875                                 if (res) {
2876                                         goto playout;
2877                                 }
2878                         } else {
2879                                 /* Normal Case */
2880                                 res = play_file(qe->chan, qe->parent->sound_thereare);
2881                                 if (res) {
2882                                         goto playout;
2883                                 }
2884                                 res = ast_say_number(qe->chan, qe->pos, AST_DIGIT_ANY, ast_channel_language(qe->chan), NULL); /* Needs gender */
2885                                 if (res) {
2886                                         goto playout;
2887                                 }
2888                         }
2889                         if (qe->parent->announceposition == ANNOUNCEPOSITION_MORE_THAN && qe->pos > qe->parent->announcepositionlimit){
2890                                 /* More than Case*/
2891                                 res = play_file(qe->chan, qe->parent->queue_quantity2);
2892                                 if (res) {
2893                                         goto playout;
2894                                 }
2895                         } else {
2896                                 res = play_file(qe->chan, qe->parent->sound_calls);
2897                                 if (res) {
2898                                         goto playout;
2899                                 }
2900                         }
2901                 }
2902         }
2903         /* Round hold time to nearest minute */
2904         avgholdmins = abs(((qe->parent->holdtime + 30) - (now - qe->start)) / 60);
2905
2906         /* If they have specified a rounding then round the seconds as well */
2907         if (qe->parent->roundingseconds) {
2908                 avgholdsecs = (abs(((qe->parent->holdtime + 30) - (now - qe->start))) - 60 * avgholdmins) / qe->parent->roundingseconds;
2909                 avgholdsecs *= qe->parent->roundingseconds;
2910         } else {
2911                 avgholdsecs = 0;
2912         }
2913
2914         ast_verb(3, "Hold time for %s is %d minute(s) %d seconds\n", qe->parent->name, avgholdmins, avgholdsecs);
2915
2916         /* If the hold time is >1 min, if it's enabled, and if it's not
2917            supposed to be only once and we have already said it, say it */
2918     if ((avgholdmins+avgholdsecs) > 0 && qe->parent->announceholdtime &&
2919         ((qe->parent->announceholdtime == ANNOUNCEHOLDTIME_ONCE && !qe->last_pos) ||
2920         !(qe->parent->announceholdtime == ANNOUNCEHOLDTIME_ONCE))) {
2921                 res = play_file(qe->chan, qe->parent->sound_holdtime);
2922                 if (res) {
2923                         goto playout;
2924                 }
2925
2926                 if (avgholdmins >= 1) {
2927                         res = ast_say_number(qe->chan, avgholdmins, AST_DIGIT_ANY, ast_channel_language(qe->chan), NULL);
2928                         if (res) {
2929                                 goto playout;
2930                         }
2931
2932                         if (avgholdmins == 1) {
2933                                 res = play_file(qe->chan, qe->parent->sound_minute);
2934                                 if (res) {
2935                                         goto playout;
2936                                 }
2937                         } else {
2938                                 res = play_file(qe->chan, qe->parent->sound_minutes);
2939                                 if (res) {
2940                                         goto playout;
2941                                 }
2942                         }
2943                 }
2944                 if (avgholdsecs >= 1) {
2945                         res = ast_say_number(qe->chan, avgholdsecs, AST_DIGIT_ANY, ast_channel_language(qe->chan), NULL);
2946                         if (res) {
2947                                 goto playout;
2948                         }
2949
2950                         res = play_file(qe->chan, qe->parent->sound_seconds);
2951                         if (res) {
2952                                 goto playout;
2953                         }
2954                 }
2955         } else if (qe->parent->announceholdtime && !qe->parent->announceposition) {
2956                 say_thanks = 0;
2957         }
2958
2959 posout:
2960         if (qe->parent->announceposition) {
2961                 ast_verb(3, "Told %s in %s their queue position (which was %d)\n",
2962                         ast_channel_name(qe->chan), qe->parent->name, qe->pos);
2963         }
2964         if (say_thanks) {
2965                 res = play_file(qe->chan, qe->parent->sound_thanks);
2966         }
2967 playout:
2968
2969         if ((res > 0 && !valid_exit(qe, res))) {
2970                 res = 0;
2971         }
2972
2973         /* Set our last_pos indicators */
2974         qe->last_pos = now;
2975         qe->last_pos_said = qe->pos;
2976
2977         /* Don't restart music on hold if we're about to exit the caller from the queue */
2978         if (!res) {
2979                 if (ringing) {
2980                         ast_indicate(qe->chan, AST_CONTROL_RINGING);
2981                 } else {
2982                         ast_moh_start(qe->chan, qe->moh, NULL);
2983                 }
2984         }
2985         return res;
2986 }
2987
2988 static void recalc_holdtime(struct queue_ent *qe, int newholdtime)
2989 {
2990         int oldvalue;
2991
2992         /* Calculate holdtime using an exponential average */
2993         /* Thanks to SRT for this contribution */
2994         /* 2^2 (4) is the filter coefficient; a higher exponent would give old entries more weight */
2995
2996         ao2_lock(qe->parent);
2997         oldvalue = qe->parent->holdtime;
2998         qe->parent->holdtime = (((oldvalue << 2) - oldvalue) + newholdtime) >> 2;
2999         ao2_unlock(qe->parent);
3000 }
3001
3002 /*! \brief Caller leaving queue.
3003  * 
3004  * Search the queue to find the leaving client, if found remove from queue
3005  * create manager event, move others up the queue.
3006 */
3007 static void leave_queue(struct queue_ent *qe)
3008 {
3009         struct call_queue *q;
3010         struct queue_ent *current, *prev = NULL;
3011         struct penalty_rule *pr_iter;
3012         int pos = 0;
3013
3014         if (!(q = qe->parent)) {
3015                 return;
3016         }
3017         queue_t_ref(q, "Copy queue pointer from queue entry");
3018         ao2_lock(q);
3019
3020         prev = NULL;
3021         for (current = q->head; current; current = current->next) {
3022                 if (current == qe) {
3023                         char posstr[20];
3024                         q->count--;
3025
3026                         /* Take us out of the queue */
3027                         ast_manager_event(qe->chan, EVENT_FLAG_CALL, "Leave",
3028                                 "Channel: %s\r\nQueue: %s\r\nCount: %d\r\nPosition: %d\r\nUniqueid: %s\r\n",
3029                                 ast_channel_name(qe->chan), q->name,  q->count, qe->pos, ast_channel_uniqueid(qe->chan));
3030                         ast_debug(1, "Queue '%s' Leave, Channel '%s'\n", q->name, ast_channel_name(qe->chan));
3031                         /* Take us out of the queue */
3032                         if (prev) {
3033                                 prev->next = current->next;
3034                         } else {
3035                                 q->head = current->next;
3036                         }
3037                         /* Free penalty rules */
3038                         while ((pr_iter = AST_LIST_REMOVE_HEAD(&qe->qe_rules, list))) {
3039                                 ast_free(pr_iter);
3040                         }
3041                         snprintf(posstr, sizeof(posstr), "%d", qe->pos);
3042                         pbx_builtin_setvar_helper(qe->chan, "QUEUEPOSITION", posstr);
3043                 } else {
3044                         /* Renumber the people after us in the queue based on a new count */
3045                         current->pos = ++pos;
3046                         prev = current;
3047                 }
3048         }
3049         ao2_unlock(q);
3050
3051         /*If the queue is a realtime queue, check to see if it's still defined in real time*/
3052         if (q->realtime) {
3053                 struct ast_variable *var;
3054                 if (!(var = ast_load_realtime("queues", "name", q->name, SENTINEL))) {
3055                         q->dead = 1;
3056                 } else {
3057                         ast_variables_destroy(var);
3058                 }
3059         }
3060
3061         if (q->dead) {
3062                 /* It's dead and nobody is in it, so kill it */
3063                 queues_t_unlink(queues, q, "Queue is now dead; remove it from the container");
3064         }
3065         /* unref the explicit ref earlier in the function */
3066         queue_t_unref(q, "Expire copied reference");
3067 }
3068
3069 /*!
3070  * \internal
3071  * \brief Destroy the given callattempt structure and free it.
3072  * \since 1.8
3073  *
3074  * \param doomed callattempt structure to destroy.
3075  *
3076  * \return Nothing
3077  */
3078 static void callattempt_free(struct callattempt *doomed)
3079 {
3080         if (doomed->member) {
3081                 ao2_ref(doomed->member, -1);
3082         }
3083         ast_party_connected_line_free(&doomed->connected);
3084         ast_free(doomed);
3085 }
3086
3087 /*! \brief Hang up a list of outgoing calls */
3088 static void hangupcalls(struct callattempt *outgoing, struct ast_channel *exception, int cancel_answered_elsewhere)
3089 {
3090         struct callattempt *oo;
3091
3092         while (outgoing) {
3093                 /* If someone else answered the call we should indicate this in the CANCEL */
3094                 /* Hangup any existing lines we have open */
3095                 if (outgoing->chan && (outgoing->chan != exception)) {
3096                         if (exception || cancel_answered_elsewhere) {
3097                                 ast_set_flag(ast_channel_flags(outgoing->chan), AST_FLAG_ANSWERED_ELSEWHERE);
3098                         }
3099                         ast_hangup(outgoing->chan);
3100                 }
3101                 oo = outgoing;
3102                 outgoing = outgoing->q_next;
3103                 ast_aoc_destroy_decoded(oo->aoc_s_rate_list);
3104                 callattempt_free(oo);
3105         }
3106 }
3107
3108 /*!
3109  * \brief Get the number of members available to accept a call.
3110  *
3111  * \note The queue passed in should be locked prior to this function call
3112  *
3113  * \param[in] q The queue for which we are couting the number of available members
3114  * \return Return the number of available members in queue q
3115  */
3116 static int num_available_members(struct call_queue *q)
3117 {
3118         struct member *mem;
3119         int avl = 0;
3120         struct ao2_iterator mem_iter;
3121
3122         mem_iter = ao2_iterator_init(q->members, 0);
3123         while ((mem = ao2_iterator_next(&mem_iter))) {
3124                 switch (mem->status) {
3125                         case AST_DEVICE_INVALID:
3126                         case AST_DEVICE_UNAVAILABLE:
3127                                 break;
3128                         case AST_DEVICE_INUSE:
3129                         case AST_DEVICE_BUSY:
3130                         case AST_DEVICE_RINGING:
3131                         case AST_DEVICE_RINGINUSE:
3132                         case AST_DEVICE_ONHOLD:
3133                                 if (!mem->ringinuse) {
3134                                         break;
3135                                 }
3136                                 /* else fall through */
3137                         case AST_DEVICE_NOT_INUSE:
3138                         case AST_DEVICE_UNKNOWN:
3139                                 if (!mem->paused) {
3140                                         avl++;
3141                                 }
3142                                 break;
3143                 }
3144                 ao2_ref(mem, -1);
3145
3146                 /* If autofill is not enabled or if the queue's strategy is ringall, then
3147                  * we really don't care about the number of available members so much as we
3148                  * do that there is at least one available.
3149                  *
3150                  * In fact, we purposely will return from this function stating that only
3151                  * one member is available if either of those conditions hold. That way,
3152                  * functions which determine what action to take based on the number of available
3153                  * members will operate properly. The reasoning is that even if multiple
3154                  * members are available, only the head caller can actually be serviced.
3155                  */
3156                 if ((!q->autofill || q->strategy == QUEUE_STRATEGY_RINGALL) && avl) {
3157                         break;
3158                 }
3159         }
3160         ao2_iterator_destroy(&mem_iter);
3161
3162         return avl;
3163 }
3164
3165 /* traverse all defined queues which have calls waiting and contain this member
3166    return 0 if no other queue has precedence (higher weight) or 1 if found  */
3167 static int compare_weight(struct call_queue *rq, struct member *member)
3168 {
3169         struct call_queue *q;
3170         struct member *mem;
3171         int found = 0;
3172         struct ao2_iterator queue_iter;
3173
3174         queue_iter = ao2_iterator_init(queues, 0);
3175         while ((q = ao2_t_iterator_next(&queue_iter, "Iterate through queues"))) {
3176                 if (q == rq) { /* don't check myself, could deadlock */
3177                         queue_t_unref(q, "Done with iterator");
3178                         continue;
3179                 }
3180                 ao2_lock(q);
3181                 if (q->count && q->members) {
3182                         if ((mem = ao2_find(q->members, member, OBJ_POINTER))) {
3183                                 ast_debug(1, "Found matching member %s in queue '%s'\n", mem->interface, q->name);
3184                                 if (q->weight > rq->weight && q->count >= num_available_members(q)) {
3185                                         ast_debug(1, "Queue '%s' (weight %d, calls %d) is preferred over '%s' (weight %d, calls %d)\n", q->name, q->weight, q->count, rq->name, rq->weight, rq->count);
3186                                         found = 1;
3187                                 }
3188                                 ao2_ref(mem, -1);
3189                         }
3190                 }
3191                 ao2_unlock(q);
3192                 queue_t_unref(q, "Done with iterator");
3193                 if (found) {
3194                         break;
3195                 }
3196         }
3197         ao2_iterator_destroy(&queue_iter);
3198         return found;
3199 }
3200
3201 /*! \brief common hangup actions */
3202 static void do_hang(struct callattempt *o)
3203 {
3204         o->stillgoing = 0;
3205         ast_hangup(o->chan);
3206         o->chan = NULL;
3207 }
3208
3209 /*! \brief convert "\n" to "\nVariable: " ready for manager to use */
3210 static char *vars2manager(struct ast_channel *chan, char *vars, size_t len)
3211 {
3212         struct ast_str *buf = ast_str_thread_get(&ast_str_thread_global_buf, len + 1);
3213         const char *tmp;
3214
3215         if (pbx_builtin_serialize_variables(chan, &buf)) {
3216                 int i, j;
3217
3218                 /* convert "\n" to "\nVariable: " */
3219                 strcpy(vars, "Variable: ");
3220                 tmp = ast_str_buffer(buf);
3221
3222                 for (i = 0, j = 10; (i < len - 1) && (j < len - 1); i++, j++) {
3223                         vars[j] = tmp[i];
3224
3225                         if (tmp[i + 1] == '\0') {
3226                                 break;
3227                         }
3228                         if (tmp[i] == '\n') {
3229                                 vars[j++] = '\r';
3230                                 vars[j++] = '\n';
3231
3232                                 ast_copy_string(&(vars[j]), "Variable: ", len - j);
3233                                 j += 9;
3234                         }
3235                 }
3236                 if (j > len - 3) {
3237                         j = len - 3;
3238                 }
3239                 vars[j++] = '\r';
3240                 vars[j++] = '\n';
3241                 vars[j] = '\0';
3242         } else {
3243                 /* there are no channel variables; leave it blank */
3244                 *vars = '\0';
3245         }
3246         return vars;
3247 }
3248
3249 /*! 
3250  * \brief Part 2 of ring_one
3251  *
3252  * Does error checking before attempting to request a channel and call a member. 
3253  * This function is only called from ring_one(). 
3254  * Failure can occur if:
3255  * - Agent on call
3256  * - Agent is paused
3257  * - Wrapup time not expired
3258  * - Priority by another queue
3259  *
3260  * \retval 1 on success to reach a free agent
3261  * \retval 0 on failure to get agent.
3262  */
3263 static int ring_entry(struct queue_ent *qe, struct callattempt *tmp, int *busies)
3264 {
3265         int res;
3266         int status;
3267         char tech[256];
3268         char *location;
3269         const char *macrocontext, *macroexten;
3270         enum ast_device_state newstate;
3271
3272         /* on entry here, we know that tmp->chan == NULL */
3273         if (tmp->member->paused) {
3274                 ast_debug(1, "%s paused, can't receive call\n", tmp->interface);
3275                 if (ast_channel_cdr(qe->chan)) {
3276                         ast_cdr_busy(ast_channel_cdr(qe->chan));
3277                 }
3278                 tmp->stillgoing = 0;
3279                 return 0;
3280         }
3281
3282         if ((tmp->lastqueue && tmp->lastqueue->wrapuptime && (time(NULL) - tmp->lastcall < tmp->lastqueue->wrapuptime)) ||
3283                 (!tmp->lastqueue && qe->parent->wrapuptime && (time(NULL) - tmp->lastcall < qe->parent->wrapuptime))) {
3284                 ast_debug(1, "Wrapuptime not yet expired on queue %s for %s\n",
3285                                 (tmp->lastqueue ? tmp->lastqueue->name : qe->parent->name), tmp->interface);
3286                 if (ast_channel_cdr(qe->chan)) {
3287                         ast_cdr_busy(ast_channel_cdr(qe->chan));
3288                 }
3289                 tmp->stillgoing = 0;
3290                 (*busies)++;
3291                 return 0;
3292         }
3293
3294         if (tmp->member->ringinuse) {
3295                 if (check_state_unknown && (tmp->member->status == AST_DEVICE_UNKNOWN)) {
3296                         newstate = ast_device_state(tmp->member->interface);
3297                         if (newstate != tmp->member->status) {
3298                                 ast_log(LOG_WARNING, "Found a channel matching iterface %s while status was %s changed to %s\n",
3299                                         tmp->member->interface, ast_devstate2str(tmp->member->status), ast_devstate2str(newstate));
3300                                 ast_devstate_changed_literal(newstate, tmp->member->interface);
3301                         }
3302                 }
3303                 if ((tmp->member->status != AST_DEVICE_NOT_INUSE) && (tmp->member->status != AST_DEVICE_UNKNOWN)) {
3304                         ast_debug(1, "%s in use, can't receive call\n", tmp->interface);
3305                         if (ast_channel_cdr(qe->chan)) {
3306                                 ast_cdr_busy(ast_channel_cdr(qe->chan));
3307                         }
3308                         tmp->stillgoing = 0;
3309                         return 0;
3310                 }
3311         }
3312
3313         if (use_weight && compare_weight(qe->parent,tmp->member)) {
3314                 ast_debug(1, "Priority queue delaying call to %s:%s\n", qe->parent->name, tmp->interface);
3315                 if (ast_channel_cdr(qe->chan)) {
3316                         ast_cdr_busy(ast_channel_cdr(qe->chan));
3317                 }
3318                 tmp->stillgoing = 0;
3319                 (*busies)++;
3320                 return 0;
3321         }
3322
3323         ast_copy_string(tech, tmp->interface, sizeof(tech));
3324         if ((location = strchr(tech, '/'))) {
3325                 *location++ = '\0';
3326         } else {
3327                 location&nbs