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