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