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