Fix trunk's compilation.
[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                         ao2_ref(q, -1);
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) {
1830                         if (!q->weight && prev_weight) {
1831                                 ast_atomic_fetchadd_int(&use_weight, -1);
1832                         }
1833                         if (q->weight && !prev_weight) {
1834                                 ast_atomic_fetchadd_int(&use_weight, +1);
1835                         }
1836                 }
1837                 /* Other cases will end up with the proper value for use_weight */
1838                 ao2_unlock(queues);
1839
1840         } else {
1841                 update_realtime_members(q);
1842         }
1843         return q;
1844 }
1845
1846 static int update_realtime_member_field(struct member *mem, const char *queue_name, const char *field, const char *value)
1847 {
1848         int ret = -1;
1849
1850         if (ast_strlen_zero(mem->rt_uniqueid))
1851                 return ret;
1852
1853         if ((ast_update_realtime("queue_members", "uniqueid", mem->rt_uniqueid, field, value, SENTINEL)) > 0)
1854                 ret = 0;
1855
1856         return ret;
1857 }
1858
1859
1860 static void update_realtime_members(struct call_queue *q)
1861 {
1862         struct ast_config *member_config = NULL;
1863         struct member *m;
1864         char *interface = NULL;
1865         struct ao2_iterator mem_iter;
1866
1867         if (!(member_config = ast_load_realtime_multientry("queue_members", "interface LIKE", "%", "queue_name", q->name , SENTINEL))) {
1868                 /*This queue doesn't have realtime members*/
1869                 ast_debug(3, "Queue %s has no realtime members defined. No need for update\n", q->name);
1870                 return;
1871         }
1872
1873         ao2_lock(queues);
1874         ao2_lock(q);
1875         
1876         /* Temporarily set realtime  members dead so we can detect deleted ones.*/ 
1877         mem_iter = ao2_iterator_init(q->members, 0);
1878         while ((m = ao2_iterator_next(&mem_iter))) {
1879                 if (m->realtime)
1880                         m->dead = 1;
1881                 ao2_ref(m, -1);
1882         }
1883
1884         while ((interface = ast_category_browse(member_config, interface))) {
1885                 rt_handle_member_record(q, interface,
1886                         ast_variable_retrieve(member_config, interface, "uniqueid"),
1887                         S_OR(ast_variable_retrieve(member_config, interface, "membername"), interface),
1888                         ast_variable_retrieve(member_config, interface, "penalty"),
1889                         ast_variable_retrieve(member_config, interface, "paused"),
1890                         S_OR(ast_variable_retrieve(member_config, interface, "state_interface"), interface));
1891         }
1892
1893         /* Delete all realtime members that have been deleted in DB. */
1894         mem_iter = ao2_iterator_init(q->members, 0);
1895         while ((m = ao2_iterator_next(&mem_iter))) {
1896                 if (m->dead) {
1897                         ast_queue_log(q->name, "REALTIME", m->interface, "REMOVEMEMBER", "%s", "");
1898                         ao2_unlink(q->members, m);
1899                         q->membercount--;
1900                 }
1901                 ao2_ref(m, -1);
1902         }
1903         ao2_unlock(q);
1904         ao2_unlock(queues);
1905         ast_config_destroy(member_config);
1906 }
1907
1908 static int join_queue(char *queuename, struct queue_ent *qe, enum queue_result *reason)
1909 {
1910         struct call_queue *q;
1911         struct queue_ent *cur, *prev = NULL;
1912         int res = -1;
1913         int pos = 0;
1914         int inserted = 0;
1915
1916         if (!(q = load_realtime_queue(queuename)))
1917                 return res;
1918
1919         ao2_lock(queues);
1920         ao2_lock(q);
1921
1922         /* This is our one */
1923         if (q->joinempty) {
1924                 int status = 0;
1925                 if ((status = get_member_status(q, qe->max_penalty, qe->min_penalty, q->joinempty))) {
1926                         *reason = QUEUE_JOINEMPTY;
1927                         ao2_unlock(q);
1928                         ao2_unlock(queues);
1929                         return res;
1930                 }
1931         }
1932         if (*reason == QUEUE_UNKNOWN && q->maxlen && (q->count >= q->maxlen))
1933                 *reason = QUEUE_FULL;
1934         else if (*reason == QUEUE_UNKNOWN) {
1935                 /* There's space for us, put us at the right position inside
1936                  * the queue.
1937                  * Take into account the priority of the calling user */
1938                 inserted = 0;
1939                 prev = NULL;
1940                 cur = q->head;
1941                 while (cur) {
1942                         /* We have higher priority than the current user, enter
1943                          * before him, after all the other users with priority
1944                          * higher or equal to our priority. */
1945                         if ((!inserted) && (qe->prio > cur->prio)) {
1946                                 insert_entry(q, prev, qe, &pos);
1947                                 inserted = 1;
1948                         }
1949                         cur->pos = ++pos;
1950                         prev = cur;
1951                         cur = cur->next;
1952                 }
1953                 /* No luck, join at the end of the queue */
1954                 if (!inserted)
1955                         insert_entry(q, prev, qe, &pos);
1956                 ast_copy_string(qe->moh, q->moh, sizeof(qe->moh));
1957                 ast_copy_string(qe->announce, q->announce, sizeof(qe->announce));
1958                 ast_copy_string(qe->context, q->context, sizeof(qe->context));
1959                 q->count++;
1960                 res = 0;
1961                 manager_event(EVENT_FLAG_CALL, "Join",
1962                         "Channel: %s\r\nCallerIDNum: %s\r\nCallerIDName: %s\r\nQueue: %s\r\nPosition: %d\r\nCount: %d\r\nUniqueid: %s\r\n",
1963                         qe->chan->name,
1964                         S_OR(qe->chan->cid.cid_num, "unknown"), /* XXX somewhere else it is <unknown> */
1965                         S_OR(qe->chan->cid.cid_name, "unknown"),
1966                         q->name, qe->pos, q->count, qe->chan->uniqueid );
1967                 ast_debug(1, "Queue '%s' Join, Channel '%s', Position '%d'\n", q->name, qe->chan->name, qe->pos );
1968         }
1969         ao2_unlock(q);
1970         ao2_unlock(queues);
1971
1972         return res;
1973 }
1974
1975 static int play_file(struct ast_channel *chan, const char *filename)
1976 {
1977         int res;
1978
1979         if (ast_strlen_zero(filename)) {
1980                 return 0;
1981         }
1982
1983         ast_stopstream(chan);
1984
1985         res = ast_streamfile(chan, filename, chan->language);
1986         if (!res)
1987                 res = ast_waitstream(chan, AST_DIGIT_ANY);
1988
1989         ast_stopstream(chan);
1990
1991         return res;
1992 }
1993
1994 /*!
1995  * \brief Check for valid exit from queue via goto
1996  * \retval 0 if failure
1997  * \retval 1 if successful
1998 */
1999 static int valid_exit(struct queue_ent *qe, char digit)
2000 {
2001         int digitlen = strlen(qe->digits);
2002
2003         /* Prevent possible buffer overflow */
2004         if (digitlen < sizeof(qe->digits) - 2) {
2005                 qe->digits[digitlen] = digit;
2006                 qe->digits[digitlen + 1] = '\0';
2007         } else {
2008                 qe->digits[0] = '\0';
2009                 return 0;
2010         }
2011
2012         /* If there's no context to goto, short-circuit */
2013         if (ast_strlen_zero(qe->context))
2014                 return 0;
2015
2016         /* If the extension is bad, then reset the digits to blank */
2017         if (!ast_canmatch_extension(qe->chan, qe->context, qe->digits, 1, qe->chan->cid.cid_num)) {
2018                 qe->digits[0] = '\0';
2019                 return 0;
2020         }
2021
2022         /* We have an exact match */
2023         if (!ast_goto_if_exists(qe->chan, qe->context, qe->digits, 1)) {
2024                 qe->valid_digits = 1;
2025                 /* Return 1 on a successful goto */
2026                 return 1;
2027         }
2028
2029         return 0;
2030 }
2031
2032 static int say_position(struct queue_ent *qe, int ringing)
2033 {
2034         int res = 0, avgholdmins, avgholdsecs, announceposition = 0;
2035         int say_thanks = 1;
2036         time_t now;
2037
2038         /* Let minannouncefrequency seconds pass between the start of each position announcement */
2039         time(&now);
2040         if ((now - qe->last_pos) < qe->parent->minannouncefrequency)
2041                 return 0;
2042
2043         /* If either our position has changed, or we are over the freq timer, say position */
2044         if ((qe->last_pos_said == qe->pos) && ((now - qe->last_pos) < qe->parent->announcefrequency))
2045                 return 0;
2046
2047         if (ringing) {
2048                 ast_indicate(qe->chan,-1);
2049         } else {
2050                 ast_moh_stop(qe->chan);
2051         }
2052
2053         if (qe->parent->announceposition == ANNOUNCEPOSITION_YES ||
2054                 qe->parent->announceposition == ANNOUNCEPOSITION_MORE_THAN ||
2055                 (qe->parent->announceposition == ANNOUNCEPOSITION_LIMIT &&
2056                 qe->pos <= qe->parent->announcepositionlimit))
2057                         announceposition = 1;
2058
2059
2060         if (announceposition == 1) {
2061                 /* Say we're next, if we are */
2062                 if (qe->pos == 1) {
2063                         res = play_file(qe->chan, qe->parent->sound_next);
2064                         if (res)
2065                                 goto playout;
2066                         else
2067                                 goto posout;
2068                 } else {
2069                         if (qe->parent->announceposition == ANNOUNCEPOSITION_MORE_THAN && qe->pos > qe->parent->announcepositionlimit){
2070                                 /* More than Case*/
2071                                 res = play_file(qe->chan, qe->parent->queue_quantity1);
2072                                 if (res)
2073                                         goto playout;
2074                                 res = ast_say_number(qe->chan, qe->parent->announcepositionlimit, AST_DIGIT_ANY, qe->chan->language, NULL); /* Needs gender */
2075                                 if (res)
2076                                         goto playout;
2077                         } else {
2078                                 /* Normal Case */
2079                                 res = play_file(qe->chan, qe->parent->sound_thereare);
2080                                 if (res)
2081                                         goto playout;
2082                                 res = ast_say_number(qe->chan, qe->pos, AST_DIGIT_ANY, qe->chan->language, NULL); /* Needs gender */
2083                                 if (res)
2084                                         goto playout;
2085                         }
2086                         if (qe->parent->announceposition == ANNOUNCEPOSITION_MORE_THAN && qe->pos > qe->parent->announcepositionlimit){
2087                                 /* More than Case*/
2088                                 res = play_file(qe->chan, qe->parent->queue_quantity2);
2089                                 if (res)
2090                                         goto playout;
2091                         } else {
2092                                 res = play_file(qe->chan, qe->parent->sound_calls);
2093                                 if (res)
2094                                         goto playout;
2095                         }
2096                 }
2097         }
2098         /* Round hold time to nearest minute */
2099         avgholdmins = abs(((qe->parent->holdtime + 30) - (now - qe->start)) / 60);
2100
2101         /* If they have specified a rounding then round the seconds as well */
2102         if (qe->parent->roundingseconds) {
2103                 avgholdsecs = (abs(((qe->parent->holdtime + 30) - (now - qe->start))) - 60 * avgholdmins) / qe->parent->roundingseconds;
2104                 avgholdsecs *= qe->parent->roundingseconds;
2105         } else {
2106                 avgholdsecs = 0;
2107         }
2108
2109         ast_verb(3, "Hold time for %s is %d minute(s) %d seconds\n", qe->parent->name, avgholdmins, avgholdsecs);
2110
2111         /* If the hold time is >1 min, if it's enabled, and if it's not
2112            supposed to be only once and we have already said it, say it */
2113     if ((avgholdmins+avgholdsecs) > 0 && qe->parent->announceholdtime &&
2114         ((qe->parent->announceholdtime == ANNOUNCEHOLDTIME_ONCE && !qe->last_pos) ||
2115         !(qe->parent->announceholdtime == ANNOUNCEHOLDTIME_ONCE))) {
2116                 res = play_file(qe->chan, qe->parent->sound_holdtime);
2117                 if (res)
2118                         goto playout;
2119
2120                 if (avgholdmins >= 1) {
2121                         res = ast_say_number(qe->chan, avgholdmins, AST_DIGIT_ANY, qe->chan->language, NULL);
2122                         if (res)
2123                                 goto playout;
2124
2125                         if (avgholdmins == 1) {
2126                                 res = play_file(qe->chan, qe->parent->sound_minute);
2127                                 if (res)
2128                                         goto playout;
2129                         } else {
2130                                 res = play_file(qe->chan, qe->parent->sound_minutes);
2131                                 if (res)
2132                                         goto playout;
2133                         }
2134                 }
2135                 if (avgholdsecs >= 1) {
2136                         res = ast_say_number(qe->chan, avgholdmins > 1 ? avgholdsecs : avgholdmins * 60 + avgholdsecs, AST_DIGIT_ANY, qe->chan->language, NULL);
2137                         if (res)
2138                                 goto playout;
2139
2140                         res = play_file(qe->chan, qe->parent->sound_seconds);
2141                         if (res)
2142                                 goto playout;
2143                 }
2144         } else if (qe->parent->announceholdtime && !qe->parent->announceposition) {
2145                 say_thanks = 0;
2146         }
2147
2148 posout:
2149         if (qe->parent->announceposition) {
2150                 ast_verb(3, "Told %s in %s their queue position (which was %d)\n",
2151                         qe->chan->name, qe->parent->name, qe->pos);
2152         }
2153         if (say_thanks) {
2154                 res = play_file(qe->chan, qe->parent->sound_thanks);
2155         }
2156 playout:
2157         if ((res > 0 && !valid_exit(qe, res)) || res < 0)
2158                 res = 0;
2159
2160         /* Set our last_pos indicators */
2161         qe->last_pos = now;
2162         qe->last_pos_said = qe->pos;
2163
2164         /* Don't restart music on hold if we're about to exit the caller from the queue */
2165         if (!res) {
2166                 if (ringing) {
2167                         ast_indicate(qe->chan, AST_CONTROL_RINGING);
2168                 } else {
2169                         ast_moh_start(qe->chan, qe->moh, NULL);
2170                 }
2171         }
2172         return res;
2173 }
2174
2175 static void recalc_holdtime(struct queue_ent *qe, int newholdtime)
2176 {
2177         int oldvalue;
2178
2179         /* Calculate holdtime using an exponential average */
2180         /* Thanks to SRT for this contribution */
2181         /* 2^2 (4) is the filter coefficient; a higher exponent would give old entries more weight */
2182
2183         ao2_lock(qe->parent);
2184         oldvalue = qe->parent->holdtime;
2185         qe->parent->holdtime = (((oldvalue << 2) - oldvalue) + newholdtime) >> 2;
2186         ao2_unlock(qe->parent);
2187 }
2188
2189 /*! \brief Caller leaving queue.
2190  * 
2191  * Search the queue to find the leaving client, if found remove from queue
2192  * create manager event, move others up the queue.
2193 */
2194 static void leave_queue(struct queue_ent *qe)
2195 {
2196         struct call_queue *q;
2197         struct queue_ent *current, *prev = NULL;
2198         struct penalty_rule *pr_iter;
2199         int pos = 0;
2200
2201         if (!(q = qe->parent))
2202                 return;
2203         queue_ref(q);
2204         ao2_lock(q);
2205
2206         prev = NULL;
2207         for (current = q->head; current; current = current->next) {
2208                 if (current == qe) {
2209                         q->count--;
2210
2211                         /* Take us out of the queue */
2212                         manager_event(EVENT_FLAG_CALL, "Leave",
2213                                 "Channel: %s\r\nQueue: %s\r\nCount: %d\r\nUniqueid: %s\r\n",
2214                                 qe->chan->name, q->name,  q->count, qe->chan->uniqueid);
2215                         ast_debug(1, "Queue '%s' Leave, Channel '%s'\n", q->name, qe->chan->name );
2216                         /* Take us out of the queue */
2217                         if (prev)
2218                                 prev->next = current->next;
2219                         else
2220                                 q->head = current->next;
2221                         /* Free penalty rules */
2222                         while ((pr_iter = AST_LIST_REMOVE_HEAD(&qe->qe_rules, list)))
2223                                 ast_free(pr_iter);
2224                 } else {
2225                         /* Renumber the people after us in the queue based on a new count */
2226                         current->pos = ++pos;
2227                         prev = current;
2228                 }
2229         }
2230         ao2_unlock(q);
2231
2232         /*If the queue is a realtime queue, check to see if it's still defined in real time*/
2233         if (q->realtime) {
2234                 struct ast_variable *var;
2235                 if (!(var = ast_load_realtime("queues", "name", q->name, SENTINEL))) {
2236                         q->dead = 1;
2237                 } else {
2238                         ast_variables_destroy(var);
2239                 }
2240         }
2241
2242         if (q->dead) {  
2243                 /* It's dead and nobody is in it, so kill it */
2244                 ao2_unlink(queues, q);
2245         }
2246         /* unref the explicit ref earlier in the function */
2247         queue_unref(q);
2248 }
2249
2250 /*! \brief Hang up a list of outgoing calls */
2251 static void hangupcalls(struct callattempt *outgoing, struct ast_channel *exception, int cancel_answered_elsewhere)
2252 {
2253         struct callattempt *oo;
2254
2255         while (outgoing) {
2256                 /* If someone else answered the call we should indicate this in the CANCEL */
2257                 /* Hangup any existing lines we have open */
2258                 if (outgoing->chan && (outgoing->chan != exception || cancel_answered_elsewhere)) {
2259                         if (exception || cancel_answered_elsewhere)
2260                                 ast_set_flag(outgoing->chan, AST_FLAG_ANSWERED_ELSEWHERE);
2261                         ast_hangup(outgoing->chan);
2262                 }
2263                 oo = outgoing;
2264                 outgoing = outgoing->q_next;
2265                 if (oo->member)
2266                         ao2_ref(oo->member, -1);
2267                 ast_free(oo);
2268         }
2269 }
2270
2271 /*!
2272  * \brief Get the number of members available to accept a call.
2273  *
2274  * \note The queue passed in should be locked prior to this function call
2275  *
2276  * \param[in] q The queue for which we are couting the number of available members
2277  * \return Return the number of available members in queue q
2278  */
2279 static int num_available_members(struct call_queue *q)
2280 {
2281         struct member *mem;
2282         int avl = 0;
2283         struct ao2_iterator mem_iter;
2284
2285         mem_iter = ao2_iterator_init(q->members, 0);
2286         while ((mem = ao2_iterator_next(&mem_iter))) {
2287                 switch (mem->status) {
2288                 case AST_DEVICE_INUSE:
2289                         if (!q->ringinuse)
2290                                 break;
2291                         /* else fall through */
2292                 case AST_DEVICE_NOT_INUSE:
2293                 case AST_DEVICE_UNKNOWN:
2294                         if (!mem->paused) {
2295                                 avl++;
2296                         }
2297                         break;
2298                 }
2299                 ao2_ref(mem, -1);
2300
2301                 /* If autofill is not enabled or if the queue's strategy is ringall, then
2302                  * we really don't care about the number of available members so much as we
2303                  * do that there is at least one available.
2304                  *
2305                  * In fact, we purposely will return from this function stating that only
2306                  * one member is available if either of those conditions hold. That way,
2307                  * functions which determine what action to take based on the number of available
2308                  * members will operate properly. The reasoning is that even if multiple
2309                  * members are available, only the head caller can actually be serviced.
2310                  */
2311                 if ((!q->autofill || q->strategy == QUEUE_STRATEGY_RINGALL) && avl) {
2312                         break;
2313                 }
2314         }
2315
2316         return avl;
2317 }
2318
2319 /* traverse all defined queues which have calls waiting and contain this member
2320    return 0 if no other queue has precedence (higher weight) or 1 if found  */
2321 static int compare_weight(struct call_queue *rq, struct member *member)
2322 {
2323         struct call_queue *q;
2324         struct member *mem;
2325         int found = 0;
2326         struct ao2_iterator queue_iter;
2327         
2328         /* q's lock and rq's lock already set by try_calling()
2329          * to solve deadlock */
2330         queue_iter = ao2_iterator_init(queues, 0);
2331         while ((q = ao2_iterator_next(&queue_iter))) {
2332                 if (q == rq) { /* don't check myself, could deadlock */
2333                         queue_unref(q);
2334                         continue;
2335                 }
2336                 ao2_lock(q);
2337                 if (q->count && q->members) {
2338                         if ((mem = ao2_find(q->members, member, OBJ_POINTER))) {
2339                                 ast_debug(1, "Found matching member %s in queue '%s'\n", mem->interface, q->name);
2340                                 if (q->weight > rq->weight && q->count >= num_available_members(q)) {
2341                                         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);
2342                                         found = 1;
2343                                 }
2344                                 ao2_ref(mem, -1);
2345                         }
2346                 }
2347                 ao2_unlock(q);
2348                 queue_unref(q);
2349                 if (found) {
2350                         break;
2351                 }
2352         }
2353         return found;
2354 }
2355
2356 /*! \brief common hangup actions */
2357 static void do_hang(struct callattempt *o)
2358 {
2359         o->stillgoing = 0;
2360         ast_hangup(o->chan);
2361         o->chan = NULL;
2362 }
2363
2364 /*! \brief convert "\n" to "\nVariable: " ready for manager to use */
2365 static char *vars2manager(struct ast_channel *chan, char *vars, size_t len)
2366 {
2367         struct ast_str *buf = ast_str_thread_get(&ast_str_thread_global_buf, len + 1);
2368         char *tmp;
2369
2370         if (pbx_builtin_serialize_variables(chan, &buf)) {
2371                 int i, j;
2372
2373                 /* convert "\n" to "\nVariable: " */
2374                 strcpy(vars, "Variable: ");
2375                 tmp = ast_str_buffer(buf);
2376
2377                 for (i = 0, j = 10; (i < len - 1) && (j < len - 1); i++, j++) {
2378                         vars[j] = tmp[i];
2379
2380                         if (tmp[i + 1] == '\0')
2381                                 break;
2382                         if (tmp[i] == '\n') {
2383                                 vars[j++] = '\r';
2384                                 vars[j++] = '\n';
2385
2386                                 ast_copy_string(&(vars[j]), "Variable: ", len - j);
2387                                 j += 9;
2388                         }
2389                 }
2390                 if (j > len - 3)
2391                         j = len - 3;
2392                 vars[j++] = '\r';
2393                 vars[j++] = '\n';
2394                 vars[j] = '\0';
2395         } else {
2396                 /* there are no channel variables; leave it blank */
2397                 *vars = '\0';
2398         }
2399         return vars;
2400 }
2401
2402 /*! 
2403  * \brief Part 2 of ring_one
2404  *
2405  * Does error checking before attempting to request a channel and call a member. 
2406  * This function is only called from ring_one(). 
2407  * Failure can occur if:
2408  * - Agent on call
2409  * - Agent is paused
2410  * - Wrapup time not expired
2411  * - Priority by another queue
2412  *
2413  * \retval 1 on success to reach a free agent
2414  * \retval 0 on failure to get agent.
2415  */
2416 static int ring_entry(struct queue_ent *qe, struct callattempt *tmp, int *busies)
2417 {
2418         int res;
2419         int status;
2420         char tech[256];
2421         char *location;
2422         const char *macrocontext, *macroexten;
2423
2424         /* on entry here, we know that tmp->chan == NULL */
2425         if ((tmp->lastqueue && tmp->lastqueue->wrapuptime && (time(NULL) - tmp->lastcall < tmp->lastqueue->wrapuptime)) ||
2426                 (!tmp->lastqueue && qe->parent->wrapuptime && (time(NULL) - tmp->lastcall < qe->parent->wrapuptime))) {
2427                 ast_debug(1, "Wrapuptime not yet expired on queue %s for %s\n", 
2428                                 (tmp->lastqueue ? tmp->lastqueue->name : qe->parent->name), tmp->interface);
2429                 if (qe->chan->cdr)
2430                         ast_cdr_busy(qe->chan->cdr);
2431                 tmp->stillgoing = 0;
2432                 (*busies)++;
2433                 return 0;
2434         }
2435
2436         if (!qe->parent->ringinuse && (tmp->member->status != AST_DEVICE_NOT_INUSE) && (tmp->member->status != AST_DEVICE_UNKNOWN)) {
2437                 ast_debug(1, "%s in use, can't receive call\n", tmp->interface);
2438                 if (qe->chan->cdr)
2439                         ast_cdr_busy(qe->chan->cdr);
2440                 tmp->stillgoing = 0;
2441                 return 0;
2442         }
2443
2444         if (tmp->member->paused) {
2445                 ast_debug(1, "%s paused, can't receive call\n", tmp->interface);
2446                 if (qe->chan->cdr)
2447                         ast_cdr_busy(qe->chan->cdr);
2448                 tmp->stillgoing = 0;
2449                 return 0;
2450         }
2451         if (use_weight && compare_weight(qe->parent,tmp->member)) {
2452                 ast_debug(1, "Priority queue delaying call to %s:%s\n", qe->parent->name, tmp->interface);
2453                 if (qe->chan->cdr)
2454                         ast_cdr_busy(qe->chan->cdr);
2455                 tmp->stillgoing = 0;
2456                 (*busies)++;
2457                 return 0;
2458         }
2459
2460         ast_copy_string(tech, tmp->interface, sizeof(tech));
2461         if ((location = strchr(tech, '/')))
2462                 *location++ = '\0';
2463         else
2464                 location = "";
2465
2466         /* Request the peer */
2467         tmp->chan = ast_request(tech, qe->chan->nativeformats, location, &status);
2468         if (!tmp->chan) {                       /* If we can't, just go on to the next call */
2469                 if (qe->chan->cdr)
2470                         ast_cdr_busy(qe->chan->cdr);
2471                 tmp->stillgoing = 0;    
2472
2473                 ao2_lock(qe->parent);
2474                 update_status(qe->parent, tmp->member, ast_device_state(tmp->member->state_interface));
2475                 qe->parent->rrpos++;
2476                 qe->linpos++;
2477                 ao2_unlock(qe->parent);
2478
2479                 (*busies)++;
2480                 return 0;
2481         }
2482         
2483         if (qe->cancel_answered_elsewhere) {
2484                 ast_set_flag(tmp->chan, AST_FLAG_ANSWERED_ELSEWHERE);
2485         }
2486         tmp->chan->appl = "AppQueue";
2487         tmp->chan->data = "(Outgoing Line)";
2488         memset(&tmp->chan->whentohangup, 0, sizeof(tmp->chan->whentohangup));
2489         if (tmp->chan->cid.cid_num)
2490                 ast_free(tmp->chan->cid.cid_num);
2491         tmp->chan->cid.cid_num = ast_strdup(qe->chan->cid.cid_num);
2492         if (tmp->chan->cid.cid_name)
2493                 ast_free(tmp->chan->cid.cid_name);
2494         tmp->chan->cid.cid_name = ast_strdup(qe->chan->cid.cid_name);
2495         if (tmp->chan->cid.cid_ani)
2496                 ast_free(tmp->chan->cid.cid_ani);
2497         tmp->chan->cid.cid_ani = ast_strdup(qe->chan->cid.cid_ani);
2498
2499         /* Inherit specially named variables from parent channel */
2500         ast_channel_inherit_variables(qe->chan, tmp->chan);
2501
2502         /* Presense of ADSI CPE on outgoing channel follows ours */
2503         tmp->chan->adsicpe = qe->chan->adsicpe;
2504
2505         /* Inherit context and extension */
2506         ast_channel_lock(qe->chan);
2507         macrocontext = pbx_builtin_getvar_helper(qe->chan, "MACRO_CONTEXT");
2508         ast_string_field_set(tmp->chan, dialcontext, ast_strlen_zero(macrocontext) ? qe->chan->context : macrocontext);
2509         macroexten = pbx_builtin_getvar_helper(qe->chan, "MACRO_EXTEN");
2510         if (!ast_strlen_zero(macroexten))
2511                 ast_copy_string(tmp->chan->exten, macroexten, sizeof(tmp->chan->exten));
2512         else
2513                 ast_copy_string(tmp->chan->exten, qe->chan->exten, sizeof(tmp->chan->exten));
2514         ast_channel_unlock(qe->chan);
2515
2516         /* Place the call, but don't wait on the answer */
2517         if ((res = ast_call(tmp->chan, location, 0))) {
2518                 /* Again, keep going even if there's an error */
2519                 ast_debug(1, "ast call on peer returned %d\n", res);
2520                 ast_verb(3, "Couldn't call %s\n", tmp->interface);
2521                 do_hang(tmp);
2522                 (*busies)++;
2523                 update_status(qe->parent, tmp->member, ast_device_state(tmp->member->state_interface));
2524                 return 0;
2525         } else if (qe->parent->eventwhencalled) {
2526                 char vars[2048];
2527
2528                 manager_event(EVENT_FLAG_AGENT, "AgentCalled",
2529                                         "Queue: %s\r\n"
2530                                         "AgentCalled: %s\r\n"
2531                                         "AgentName: %s\r\n"
2532                                         "ChannelCalling: %s\r\n"
2533                                         "DestinationChannel: %s\r\n"
2534                                         "CallerIDNum: %s\r\n"
2535                                         "CallerIDName: %s\r\n"
2536                                         "Context: %s\r\n"
2537                                         "Extension: %s\r\n"
2538                                         "Priority: %d\r\n"
2539                                         "Uniqueid: %s\r\n"
2540                                         "%s",
2541                                         qe->parent->name, tmp->interface, tmp->member->membername, qe->chan->name, tmp->chan->name,
2542                                         tmp->chan->cid.cid_num ? tmp->chan->cid.cid_num : "unknown",
2543                                         tmp->chan->cid.cid_name ? tmp->chan->cid.cid_name : "unknown",
2544                                         qe->chan->context, qe->chan->exten, qe->chan->priority, qe->chan->uniqueid,
2545                                         qe->parent->eventwhencalled == QUEUE_EVENT_VARIABLES ? vars2manager(qe->chan, vars, sizeof(vars)) : "");
2546                 ast_verb(3, "Called %s\n", tmp->interface);
2547         }
2548
2549         update_status(qe->parent, tmp->member, ast_device_state(tmp->member->state_interface));
2550         return 1;
2551 }
2552
2553 /*! \brief find the entry with the best metric, or NULL */
2554 static struct callattempt *find_best(struct callattempt *outgoing)
2555 {
2556         struct callattempt *best = NULL, *cur;
2557
2558         for (cur = outgoing; cur; cur = cur->q_next) {
2559                 if (cur->stillgoing &&                                  /* Not already done */
2560                         !cur->chan &&                                   /* Isn't already going */
2561                         (!best || cur->metric < best->metric)) {                /* We haven't found one yet, or it's better */
2562                         best = cur;
2563                 }
2564         }
2565
2566         return best;
2567 }
2568
2569 /*! 
2570  * \brief Place a call to a queue member.
2571  *
2572  * Once metrics have been calculated for each member, this function is used
2573  * to place a call to the appropriate member (or members). The low-level
2574  * channel-handling and error detection is handled in ring_entry
2575  *
2576  * \retval 1 if a member was called successfully
2577  * \retval 0 otherwise
2578  */
2579 static int ring_one(struct queue_ent *qe, struct callattempt *outgoing, int *busies)
2580 {
2581         int ret = 0;
2582
2583         while (ret == 0) {
2584                 struct callattempt *best = find_best(outgoing);
2585                 if (!best) {
2586                         ast_debug(1, "Nobody left to try ringing in queue\n");
2587                         break;
2588                 }
2589                 if (qe->parent->strategy == QUEUE_STRATEGY_RINGALL) {
2590                         struct callattempt *cur;
2591                         /* Ring everyone who shares this best metric (for ringall) */
2592                         for (cur = outgoing; cur; cur = cur->q_next) {
2593                                 if (cur->stillgoing && !cur->chan && cur->metric <= best->metric) {
2594                                         ast_debug(1, "(Parallel) Trying '%s' with metric %d\n", cur->interface, cur->metric);
2595                                         ret |= ring_entry(qe, cur, busies);
2596                                 }
2597                         }
2598                 } else {
2599                         /* Ring just the best channel */
2600                         ast_debug(1, "Trying '%s' with metric %d\n", best->interface, best->metric);
2601                         ret = ring_entry(qe, best, busies);
2602                 }
2603                 
2604                 /* If we have timed out, break out */
2605                 if (qe->expire && (time(NULL) >= qe->expire)) {
2606                         ast_debug(1, "Queue timed out while ringing members.\n");
2607                         ret = 0;
2608                         break;
2609                 }
2610         }
2611
2612         return ret;
2613 }
2614
2615 /*! \brief Search for best metric and add to Round Robbin queue */
2616 static int store_next_rr(struct queue_ent *qe, struct callattempt *outgoing)
2617 {
2618         struct callattempt *best = find_best(outgoing);
2619
2620         if (best) {
2621                 /* Ring just the best channel */
2622                 ast_debug(1, "Next is '%s' with metric %d\n", best->interface, best->metric);
2623                 qe->parent->rrpos = best->metric % 1000;
2624         } else {
2625                 /* Just increment rrpos */
2626                 if (qe->parent->wrapped) {
2627                         /* No more channels, start over */
2628                         qe->parent->rrpos = 0;
2629                 } else {
2630                         /* Prioritize next entry */
2631                         qe->parent->rrpos++;
2632                 }
2633         }
2634         qe->parent->wrapped = 0;
2635
2636         return 0;
2637 }
2638
2639 /*! \brief Search for best metric and add to Linear queue */
2640 static int store_next_lin(struct queue_ent *qe, struct callattempt *outgoing)
2641 {
2642         struct callattempt *best = find_best(outgoing);
2643
2644         if (best) {
2645                 /* Ring just the best channel */
2646                 ast_debug(1, "Next is '%s' with metric %d\n", best->interface, best->metric);
2647                 qe->linpos = best->metric % 1000;
2648         } else {
2649                 /* Just increment rrpos */
2650                 if (qe->linwrapped) {
2651                         /* No more channels, start over */
2652                         qe->linpos = 0;
2653                 } else {
2654                         /* Prioritize next entry */
2655                         qe->linpos++;
2656                 }
2657         }
2658         qe->linwrapped = 0;
2659
2660         return 0;
2661 }
2662
2663 /*! \brief Playback announcement to queued members if peroid has elapsed */
2664 static int say_periodic_announcement(struct queue_ent *qe, int ringing)
2665 {
2666         int res = 0;
2667         time_t now;
2668
2669         /* Get the current time */
2670         time(&now);
2671
2672         /* Check to see if it is time to announce */
2673         if ((now - qe->last_periodic_announce_time) < qe->parent->periodicannouncefrequency)
2674                 return 0;
2675
2676         /* Stop the music on hold so we can play our own file */
2677         if (ringing)
2678                 ast_indicate(qe->chan,-1);
2679         else
2680                 ast_moh_stop(qe->chan);
2681
2682         ast_verb(3, "Playing periodic announcement\n");
2683         
2684         if (qe->parent->randomperiodicannounce) {
2685                 qe->last_periodic_announce_sound = ((unsigned long) ast_random()) % qe->parent->numperiodicannounce;
2686         } else if (qe->last_periodic_announce_sound >= qe->parent->numperiodicannounce || 
2687                 ast_str_strlen(qe->parent->sound_periodicannounce[qe->last_periodic_announce_sound]) == 0) {
2688                 qe->last_periodic_announce_sound = 0;
2689         }
2690         
2691         /* play the announcement */
2692         res = play_file(qe->chan, ast_str_buffer(qe->parent->sound_periodicannounce[qe->last_periodic_announce_sound]));
2693
2694         if ((res > 0 && !valid_exit(qe, res)) || res < 0)
2695                 res = 0;
2696
2697         /* Resume Music on Hold if the caller is going to stay in the queue */
2698         if (!res) {
2699                 if (ringing)
2700                         ast_indicate(qe->chan, AST_CONTROL_RINGING);
2701                 else
2702                         ast_moh_start(qe->chan, qe->moh, NULL);
2703         }
2704
2705         /* update last_periodic_announce_time */
2706         qe->last_periodic_announce_time = now;
2707
2708         /* Update the current periodic announcement to the next announcement */
2709         if (!qe->parent->randomperiodicannounce) {
2710                 qe->last_periodic_announce_sound++;
2711         }
2712         
2713         return res;
2714 }
2715
2716 /*! \brief Record that a caller gave up on waiting in queue */
2717 static void record_abandoned(struct queue_ent *qe)
2718 {
2719         ao2_lock(qe->parent);
2720         set_queue_variables(qe->parent, qe->chan);
2721         manager_event(EVENT_FLAG_AGENT, "QueueCallerAbandon",
2722                 "Queue: %s\r\n"
2723                 "Uniqueid: %s\r\n"
2724                 "Position: %d\r\n"
2725                 "OriginalPosition: %d\r\n"
2726                 "HoldTime: %d\r\n",
2727                 qe->parent->name, qe->chan->uniqueid, qe->pos, qe->opos, (int)(time(NULL) - qe->start));
2728
2729         qe->parent->callsabandoned++;
2730         ao2_unlock(qe->parent);
2731 }
2732
2733 /*! \brief RNA == Ring No Answer. Common code that is executed when we try a queue member and they don't answer. */
2734 static void rna(int rnatime, struct queue_ent *qe, char *interface, char *membername, int pause)
2735 {
2736         ast_verb(3, "Nobody picked up in %d ms\n", rnatime);
2737         if (qe->parent->eventwhencalled) {
2738                 char vars[2048];
2739
2740                 manager_event(EVENT_FLAG_AGENT, "AgentRingNoAnswer",
2741                                                 "Queue: %s\r\n"
2742                                                 "Uniqueid: %s\r\n"
2743                                                 "Channel: %s\r\n"
2744                                                 "Member: %s\r\n"
2745                                                 "MemberName: %s\r\n"
2746                                                 "Ringtime: %d\r\n"
2747                                                 "%s",
2748                                                 qe->parent->name,
2749                                                 qe->chan->uniqueid,
2750                                                 qe->chan->name,
2751                                                 interface,
2752                                                 membername,
2753                                                 rnatime,
2754                                                 qe->parent->eventwhencalled == QUEUE_EVENT_VARIABLES ? vars2manager(qe->chan, vars, sizeof(vars)) : "");
2755         }
2756         ast_queue_log(qe->parent->name, qe->chan->uniqueid, membername, "RINGNOANSWER", "%d", rnatime);
2757         if (qe->parent->autopause && pause) {
2758                 if (!set_member_paused(qe->parent->name, interface, "Auto-Pause", 1)) {
2759                         ast_verb(3, "Auto-Pausing Queue Member %s in queue %s since they failed to answer.\n", interface, qe->parent->name);
2760                 } else {
2761                         ast_verb(3, "Failed to pause Queue Member %s in queue %s!\n", interface, qe->parent->name);
2762                 }
2763         }
2764         return;
2765 }
2766
2767 #define AST_MAX_WATCHERS 256
2768 /*! \brief Wait for a member to answer the call
2769  *
2770  * \param[in] qe the queue_ent corresponding to the caller in the queue
2771  * \param[in] outgoing the list of callattempts. Relevant ones will have their chan and stillgoing parameters non-zero
2772  * \param[in] to the amount of time (in milliseconds) to wait for a response
2773  * \param[out] digit if a user presses a digit to exit the queue, this is the digit the caller pressed
2774  * \param[in] prebusies number of busy members calculated prior to calling wait_for_answer
2775  * \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
2776  * \param[in] forwardsallowed used to detect if we should allow call forwarding, based on the 'i' option to Queue()
2777  */
2778 static struct callattempt *wait_for_answer(struct queue_ent *qe, struct callattempt *outgoing, int *to, char *digit, int prebusies, int caller_disconnect, int forwardsallowed)
2779 {
2780         const char *queue = qe->parent->name;
2781         struct callattempt *o, *start = NULL, *prev = NULL;
2782         int status;
2783         int numbusies = prebusies;
2784         int numnochan = 0;
2785         int stillgoing = 0;
2786         int orig = *to;
2787         struct ast_frame *f;
2788         struct callattempt *peer = NULL;
2789         struct ast_channel *winner;
2790         struct ast_channel *in = qe->chan;
2791         char on[80] = "";
2792         char membername[80] = "";
2793         long starttime = 0;
2794         long endtime = 0;
2795 #ifdef HAVE_EPOLL
2796         struct callattempt *epollo;
2797 #endif
2798
2799         starttime = (long) time(NULL);
2800 #ifdef HAVE_EPOLL
2801         for (epollo = outgoing; epollo; epollo = epollo->q_next) {
2802                 if (epollo->chan)
2803                         ast_poll_channel_add(in, epollo->chan);
2804         }
2805 #endif
2806         
2807         while (*to && !peer) {
2808                 int numlines, retry, pos = 1;
2809                 struct ast_channel *watchers[AST_MAX_WATCHERS];
2810                 watchers[0] = in;
2811                 start = NULL;
2812
2813                 for (retry = 0; retry < 2; retry++) {
2814                         numlines = 0;
2815                         for (o = outgoing; o; o = o->q_next) { /* Keep track of important channels */
2816                                 if (o->stillgoing) {    /* Keep track of important channels */
2817                                         stillgoing = 1;
2818                                         if (o->chan) {
2819                                                 watchers[pos++] = o->chan;
2820                                                 if (!start)
2821                                                         start = o;
2822                                                 else
2823                                                         prev->call_next = o;
2824                                                 prev = o;
2825                                         }
2826                                 }
2827                                 numlines++;
2828                         }
2829                         if (pos > 1 /* found */ || !stillgoing /* nobody listening */ ||
2830                                 (qe->parent->strategy != QUEUE_STRATEGY_RINGALL) /* ring would not be delivered */)
2831                                 break;
2832                         /* On "ringall" strategy we only move to the next penalty level
2833                            when *all* ringing phones are done in the current penalty level */
2834                         ring_one(qe, outgoing, &numbusies);
2835                         /* and retry... */
2836                 }
2837                 if (pos == 1 /* not found */) {
2838                         if (numlines == (numbusies + numnochan)) {
2839                                 ast_debug(1, "Everyone is busy at this time\n");
2840                         } else {
2841                                 ast_debug(3, "No one is answering queue '%s' (%d numlines / %d busies / %d failed channels)\n", queue, numlines, numbusies, numnochan);
2842                         }
2843                         *to = 0;
2844                         return NULL;
2845                 }
2846                 winner = ast_waitfor_n(watchers, pos, to);
2847                 for (o = start; o; o = o->call_next) {
2848                         if (o->stillgoing && (o->chan) &&  (o->chan->_state == AST_STATE_UP)) {
2849                                 if (!peer) {
2850                                         ast_verb(3, "%s answered %s\n", o->chan->name, in->name);
2851                                         peer = o;
2852                                 }
2853                         } else if (o->chan && (o->chan == winner)) {
2854
2855                                 ast_copy_string(on, o->member->interface, sizeof(on));
2856                                 ast_copy_string(membername, o->member->membername, sizeof(membername));
2857
2858                                 if (!ast_strlen_zero(o->chan->call_forward) && !forwardsallowed) {
2859                                         ast_verb(3, "Forwarding %s to '%s' prevented.\n", in->name, o->chan->call_forward);
2860                                         numnochan++;
2861                                         do_hang(o);
2862                                         winner = NULL;
2863                                         continue;
2864                                 } else if (!ast_strlen_zero(o->chan->call_forward)) {
2865                                         char tmpchan[256];
2866                                         char *stuff;
2867                                         char *tech;
2868
2869                                         ast_copy_string(tmpchan, o->chan->call_forward, sizeof(tmpchan));
2870                                         if ((stuff = strchr(tmpchan, '/'))) {
2871                                                 *stuff++ = '\0';
2872                                                 tech = tmpchan;
2873                                         } else {
2874                                                 snprintf(tmpchan, sizeof(tmpchan), "%s@%s", o->chan->call_forward, o->chan->context);
2875                                                 stuff = tmpchan;
2876                                                 tech = "Local";
2877                                         }
2878                                         /* Before processing channel, go ahead and check for forwarding */
2879                                         ast_verb(3, "Now forwarding %s to '%s/%s' (thanks to %s)\n", in->name, tech, stuff, o->chan->name);
2880                                         /* Setup parameters */
2881                                         o->chan = ast_request(tech, in->nativeformats, stuff, &status);
2882                                         if (!o->chan) {
2883                                                 ast_log(LOG_NOTICE, "Unable to create local channel for call forward to '%s/%s'\n", tech, stuff);
2884                                                 o->stillgoing = 0;
2885                                                 numnochan++;
2886                                         } else {
2887                                                 ast_channel_inherit_variables(in, o->chan);
2888                                                 ast_channel_datastore_inherit(in, o->chan);
2889                                                 if (o->chan->cid.cid_num)
2890                                                         ast_free(o->chan->cid.cid_num);
2891                                                 o->chan->cid.cid_num = ast_strdup(in->cid.cid_num);
2892
2893                                                 if (o->chan->cid.cid_name)
2894                                                         ast_free(o->chan->cid.cid_name);
2895                                                 o->chan->cid.cid_name = ast_strdup(in->cid.cid_name);
2896
2897                                                 ast_string_field_set(o->chan, accountcode, in->accountcode);
2898                                                 o->chan->cdrflags = in->cdrflags;
2899
2900                                                 if (in->cid.cid_ani) {
2901                                                         if (o->chan->cid.cid_ani)
2902                                                                 ast_free(o->chan->cid.cid_ani);
2903                                                         o->chan->cid.cid_ani = ast_strdup(in->cid.cid_ani);
2904                                                 }
2905                                                 if (o->chan->cid.cid_rdnis)
2906                                                         ast_free(o->chan->cid.cid_rdnis);
2907                                                 o->chan->cid.cid_rdnis = ast_strdup(S_OR(in->macroexten, in->exten));
2908                                                 if (ast_call(o->chan, tmpchan, 0)) {
2909                                                         ast_log(LOG_NOTICE, "Failed to dial on local channel for call forward to '%s'\n", tmpchan);
2910                                                         do_hang(o);
2911                                                         numnochan++;
2912                                                 }
2913                                         }
2914                                         /* Hangup the original channel now, in case we needed it */
2915                                         ast_hangup(winner);
2916                                         continue;
2917                                 }
2918                                 f = ast_read(winner);
2919                                 if (f) {
2920                                         if (f->frametype == AST_FRAME_CONTROL) {
2921                                                 switch (f->subclass) {
2922                                                 case AST_CONTROL_ANSWER:
2923                                                         /* This is our guy if someone answered. */
2924                                                         if (!peer) {
2925                             &n