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