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