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