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