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