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