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