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