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