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