Debian Codegraph @

apps/app_queue.c

raw symbols SCIP
1 /*
2 * Asterisk -- An open source telephony toolkit.
3 *
4 * Copyright (C) 1999 - 2018, Digium, Inc.
5 *
6 * Mark Spencer <[email protected]>
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 <[email protected]>
24 *
25 * \par Development notes
26 * \note 2004-11-25: Persistent Dynamic Members added by:
27 * NetNation Communications (www.netnation.com)
28 * Kevin Lindsay <[email protected]>
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 <[email protected]>:
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 *
45 * Patch Version 1.07 2003-12-24 01
46 *
47 * Added servicelevel statistic by Michiel Betel <[email protected]>
48 * Added Priority jumping code for adding and removing queue members by Jonathan Stanton <[email protected]>
49 *
50 * Fixed to work with CVS as of 2004-02-25 and released as 1.07a
51 * by Matthew Enger <[email protected]>
52 *
53 * \ingroup applications
54 */
55
56 /*! \li \ref app_queues.c uses configuration file \ref queues.conf
57 * \addtogroup configuration_file
58 */
59
60 /*! \page queues.conf queues.conf
61 * \verbinclude queues.conf.sample
62 */
63
64 /*** MODULEINFO
65 <support_level>core</support_level>
66 ***/
67
68 #include "asterisk.h"
69
70 #include <sys/time.h>
71 #include <signal.h>
72 #include <netinet/in.h>
73 #include <ctype.h>
74 #include <inttypes.h>
75
76 #include "asterisk/lock.h"
77 #include "asterisk/file.h"
78 #include "asterisk/channel.h"
79 #include "asterisk/pbx.h"
80 #include "asterisk/app.h"
81 #include "asterisk/linkedlists.h"
82 #include "asterisk/module.h"
83 #include "asterisk/translate.h"
84 #include "asterisk/say.h"
85 #include "asterisk/features.h"
86 #include "asterisk/musiconhold.h"
87 #include "asterisk/cli.h"
88 #include "asterisk/manager.h"
89 #include "asterisk/config.h"
90 #include "asterisk/utils.h"
91 #include "asterisk/causes.h"
92 #include "asterisk/astdb.h"
93 #include "asterisk/devicestate.h"
94 #include "asterisk/stringfields.h"
95 #include "asterisk/astobj2.h"
96 #include "asterisk/strings.h"
97 #include "asterisk/taskprocessor.h"
98 #include "asterisk/aoc.h"
99 #include "asterisk/callerid.h"
100 #include "asterisk/term.h"
101 #include "asterisk/dial.h"
102 #include "asterisk/stasis_channels.h"
103 #include "asterisk/stasis_message_router.h"
104 #include "asterisk/bridge_after.h"
105 #include "asterisk/stasis_bridges.h"
106 #include "asterisk/core_local.h"
107 #include "asterisk/mixmonitor.h"
108 #include "asterisk/bridge_basic.h"
109 #include "asterisk/max_forwards.h"
110
111 /*!
112 * \par Please read before modifying this file.
113 * There are three locks which are regularly used
114 * throughout this file, the queue list lock, the lock
115 * for each individual queue, and the interface list lock.
116 * Please be extra careful to always lock in the following order
117 * 1) queue list lock
118 * 2) individual queue lock
119 * 3) interface list lock
120 * This order has sort of "evolved" over the lifetime of this
121 * application, but it is now in place this way, so please adhere
122 * to this order!
123 */
124
125 /*** DOCUMENTATION
126 <application name="Queue" language="en_US">
127 <since>
128 <version>0.2.0</version>
129 </since>
130 <synopsis>
131 Queue a call for a call queue.
132 </synopsis>
133 <syntax>
134 <parameter name="queuename" required="true" />
135 <parameter name="options">
136 <optionlist>
137 <option name="b" argsep="^">
138 <para>Before initiating an outgoing call, <literal>Gosub</literal> to the specified
139 location using the newly created channel. The <literal>Gosub</literal> will be
140 executed for each destination channel.</para>
141 <argument name="context" required="false" />
142 <argument name="exten" required="false" />
143 <argument name="priority" required="true" hasparams="optional" argsep="^">
144 <argument name="arg1" multiple="true" required="true" />
145 <argument name="argN" />
146 </argument>
147 </option>
148 <option name="B" argsep="^">
149 <para>Before initiating the outgoing call(s), <literal>Gosub</literal> to the
150 specified location using the current channel.</para>
151 <argument name="context" required="false" />
152 <argument name="exten" required="false" />
153 <argument name="priority" required="true" hasparams="optional" argsep="^">
154 <argument name="arg1" multiple="true" required="true" />
155 <argument name="argN" />
156 </argument>
157 </option>
158 <option name="C">
159 <para>Mark all calls as "answered elsewhere" when cancelled.</para>
160 </option>
161 <option name="c">
162 <para>Continue in the dialplan if the callee hangs up.</para>
163 </option>
164 <option name="d">
165 <para>Data-quality (modem) call (minimum delay).</para>
166 <para>This option only applies to DAHDI channels. By default,
167 DTMF is verified by muting audio TX/RX to verify the tone
168 is still present. This option disables that behavior.</para>
169 </option>
170 <option name="F" argsep="^">
171 <argument name="context" required="false" />
172 <argument name="exten" required="false" />
173 <argument name="priority" required="true" />
174 <para>When the caller hangs up, transfer the <emphasis>called member</emphasis>
175 to the specified destination and <emphasis>start</emphasis> execution at that location.</para>
176 <para>NOTE: Any channel variables you want the called channel to inherit from the caller channel must be
177 prefixed with one or two underbars ('_').</para>
178 <para>NOTE: Using this option from a Gosub() might not make sense as there would be no return points.</para>
179 </option>
180 <option name="h">
181 <para>Allow <emphasis>callee</emphasis> to hang up by pressing <literal>*</literal>.</para>
182 </option>
183 <option name="H">
184 <para>Allow <emphasis>caller</emphasis> to hang up by pressing <literal>*</literal>.</para>
185 </option>
186 <option name="i">
187 <para>Ignore call forward requests from queue members and do nothing
188 when they are requested.</para>
189 </option>
190 <option name="I">
191 <para>Asterisk will ignore any connected line update requests or any redirecting party
192 update requests it may receive on this dial attempt.</para>
193 </option>
194 <option name="k">
195 <para>Allow the <emphasis>called</emphasis> party to enable parking of the call by sending
196 the DTMF sequence defined for call parking in <filename>features.conf</filename>.</para>
197 </option>
198 <option name="K">
199 <para>Allow the <emphasis>calling</emphasis> party to enable parking of the call by sending
200 the DTMF sequence defined for call parking in <filename>features.conf</filename>.</para>
201 </option>
202 <option name="m">
203 <para>Custom music on hold class to use, which will override the music on hold class configured
204 in <filename>queues.conf</filename>, if specified.</para>
205 <para>Note that CHANNEL(musicclass), if set, will still override this option.</para>
206 </option>
207 <option name="n">
208 <para>No retries on the timeout; will exit this application and
209 go to the next step.</para>
210 </option>
211 <option name="r">
212 <para>Ring instead of playing MOH. Periodic Announcements are still made, if applicable.</para>
213 </option>
214 <option name="R">
215 <para>Ring instead of playing MOH when a member channel is actually ringing.</para>
216 </option>
217 <option name="t">
218 <para>Allow the <emphasis>called</emphasis> user to transfer the calling user.</para>
219 </option>
220 <option name="T">
221 <para>Allow the <emphasis>calling</emphasis> user to transfer the call.</para>
222 </option>
223 <option name="x">
224 <para>Allow the <emphasis>called</emphasis> user to write the conversation
225 to disk via MixMonitor.</para>
226 </option>
227 <option name="X">
228 <para>Allow the <emphasis>calling</emphasis> user to write the conversation to
229 disk via MixMonitor.</para>
230 </option>
231 </optionlist>
232 </parameter>
233 <parameter name="URL">
234 <para><replaceable>URL</replaceable> will be sent to the called party if the channel supports it.</para>
235 </parameter>
236 <parameter name="announceoverride" argsep="&amp;">
237 <para>Announcement file(s) to play to agent before bridging
238 call, overriding the announcement(s) configured in
239 <filename>queues.conf</filename>, if any.</para>
240 <para>Ampersand separated list of filenames. If the filename
241 is a relative filename (it does not begin with a slash), it
242 will be searched for in the Asterisk sounds directory. If the
243 filename is able to be parsed as a URL, Asterisk will
244 download the file and then begin playback on it. To include a
245 literal <literal>&amp;</literal> in the URL you can enclose
246 the URL in single quotes.</para>
247 <argument name="announceoverride" required="true" />
248 <argument name="announceoverride2" multiple="true" />
249 </parameter>
250 <parameter name="timeout">
251 <para>Will cause the queue to fail out after a specified number of
252 seconds, checked between each <filename>queues.conf</filename> <replaceable>timeout</replaceable> and
253 <replaceable>retry</replaceable> cycle.</para>
254 </parameter>
255 <parameter name="AGI">
256 <para>Will setup an AGI script to be executed on the calling party's channel once they are
257 connected to a queue member.</para>
258 </parameter>
259 <parameter name="gosub">
260 <para>Will run a gosub on the called party's channel (the queue member)
261 once the parties are connected. The subroutine execution starts in the
262 named context at the s exten and priority 1.</para>
263 <note><para>Macro was removed in Asterisk 21 which resulted in an
264 argument ordering change. The upgrade notice was missed for this,
265 so a note is being made here to provide a record of the change
266 for users who have not upgraded yet.</para></note>
267 </parameter>
268 <parameter name="rule">
269 <para>Will cause the queue's defaultrule to be overridden by the rule specified.</para>
270 </parameter>
271 <parameter name="position">
272 <para>Attempt to enter the caller into the queue at the numerical position specified. <literal>1</literal>
273 would attempt to enter the caller at the head of the queue, and <literal>3</literal> would attempt to place
274 the caller third in the queue.</para>
275 </parameter>
276 </syntax>
277 <description>
278 <para>In addition to transferring the call, a call may be parked and then picked
279 up by another user.</para>
280 <para>This application will return to the dialplan if the queue does not exist, or
281 any of the join options cause the caller to not enter the queue.</para>
282 <para>This application does not automatically answer and should be preceded
283 by an application such as Answer(), Progress(), or Ringing().</para>
284 <para>This application sets the following channel variables upon completion:</para>
285 <variablelist>
286 <variable name="QUEUESTATUS">
287 <para>The status of the call as a text string.</para>
288 <value name="TIMEOUT" />
289 <value name="FULL" />
290 <value name="JOINEMPTY" />
291 <value name="LEAVEEMPTY" />
292 <value name="JOINUNAVAIL" />
293 <value name="LEAVEUNAVAIL" />
294 <value name="CONTINUE" />
295 <value name="WITHDRAW" />
296 </variable>
297 <variable name="ABANDONED">
298 <para>If the call was not answered by an agent this variable will be TRUE.</para>
299 <value name="TRUE" />
300 </variable>
301 <variable name="DIALEDPEERNUMBER">
302 <para>Resource of the agent that was dialed set on the outbound channel.</para>
303 </variable>
304 <variable name="QUEUE_WITHDRAW_INFO">
305 <para>If the call was successfully withdrawn from the queue, and the withdraw request was provided with optional withdraw info, the withdraw info will be stored in this variable.</para>
306 </variable>
307 <variable name="QUEUEWAIT">
308 <para>The total amount of time, in seconds, that the caller spent waiting in the queue before being connected to an agent.</para>
309 </variable>
310 <variable name="QUEUEWAIT_MS">
311 <para>The total amount of time, in milliseconds, that the caller spent waiting in the queue before being connected to an agent.</para>
312 </variable>
313 <variable name="ANSWEREDTIME">
314 <para>The amount of time, in seconds, that the caller spent connected to an agent. If the call was never answered, this will be set to 0.</para>
315 </variable>
316 <variable name="ANSWEREDTIME_MS">
317 <para>The amount of time, in milliseconds, that the caller spent connected to an agent.</para>
318 </variable>
319 <variable name="DIALEDTIME">
320 <para>The total amount of time, in seconds, from the start of the call until it ends. This matches the behavior of Dial().</para>
321 </variable>
322 <variable name="DIALEDTIME_MS">
323 <para>The total amount of time, in milliseconds, from the start of the call until it ends.</para>
324 </variable>
325 </variablelist>
326 </description>
327 <see-also>
328 <ref type="application">Queue</ref>
329 <ref type="application">QueueLog</ref>
330 <ref type="application">AddQueueMember</ref>
331 <ref type="application">RemoveQueueMember</ref>
332 <ref type="application">PauseQueueMember</ref>
333 <ref type="application">UnpauseQueueMember</ref>
334 <ref type="function">QUEUE_VARIABLES</ref>
335 <ref type="function">QUEUE_MEMBER</ref>
336 <ref type="function">QUEUE_MEMBER_COUNT</ref>
337 <ref type="function">QUEUE_EXISTS</ref>
338 <ref type="function">QUEUE_GET_CHANNEL</ref>
339 <ref type="function">QUEUE_WAITING_COUNT</ref>
340 <ref type="function">QUEUE_MEMBER_LIST</ref>
341 <ref type="function">QUEUE_MEMBER_PENALTY</ref>
342 </see-also>
343 </application>
344 <application name="AddQueueMember" language="en_US">
345 <since>
346 <version>0.5.0</version>
347 </since>
348 <synopsis>
349 Dynamically adds queue members.
350 </synopsis>
351 <syntax>
352 <parameter name="queuename" required="true" />
353 <parameter name="interface" />
354 <parameter name="penalty" />
355 <parameter name="options">
356 <optionlist>
357 <option name="p">
358 <para>Add queue member in paused state.</para>
359 </option>
360 <option name="r">
361 <argument name="reason" required="true" />
362 <para>Specify a reason why the member is in paused state.</para>
363 </option>
364 </optionlist>
365 </parameter>
366 <parameter name="membername" />
367 <parameter name="stateinterface" />
368 <parameter name="wrapuptime" />
369 </syntax>
370 <description>
371 <para>Dynamically adds interface to an existing queue. If the interface is
372 already in the queue it will return an error.</para>
373 <para>This application sets the following channel variable upon completion:</para>
374 <variablelist>
375 <variable name="AQMSTATUS">
376 <para>The status of the attempt to add a queue member as a text string.</para>
377 <value name="ADDED" />
378 <value name="MEMBERALREADY" />
379 <value name="NOSUCHQUEUE" />
380 </variable>
381 </variablelist>
382 </description>
383 <see-also>
384 <ref type="application">Queue</ref>
385 <ref type="application">QueueLog</ref>
386 <ref type="application">AddQueueMember</ref>
387 <ref type="application">RemoveQueueMember</ref>
388 <ref type="application">PauseQueueMember</ref>
389 <ref type="application">UnpauseQueueMember</ref>
390 <ref type="function">QUEUE_VARIABLES</ref>
391 <ref type="function">QUEUE_MEMBER</ref>
392 <ref type="function">QUEUE_MEMBER_COUNT</ref>
393 <ref type="function">QUEUE_EXISTS</ref>
394 <ref type="function">QUEUE_GET_CHANNEL</ref>
395 <ref type="function">QUEUE_WAITING_COUNT</ref>
396 <ref type="function">QUEUE_MEMBER_LIST</ref>
397 <ref type="function">QUEUE_MEMBER_PENALTY</ref>
398 </see-also>
399 </application>
400 <application name="RemoveQueueMember" language="en_US">
401 <since>
402 <version>0.5.0</version>
403 </since>
404 <synopsis>
405 Dynamically removes queue members.
406 </synopsis>
407 <syntax>
408 <parameter name="queuename" required="true" />
409 <parameter name="interface" />
410 </syntax>
411 <description>
412 <para>If the interface is <emphasis>NOT</emphasis> in the queue it will return an error.</para>
413 <para>This application sets the following channel variable upon completion:</para>
414 <variablelist>
415 <variable name="RQMSTATUS">
416 <value name="REMOVED" />
417 <value name="NOTINQUEUE" />
418 <value name="NOSUCHQUEUE" />
419 <value name="NOTDYNAMIC" />
420 </variable>
421 </variablelist>
422 <example title="Remove queue member">
423 same => n,RemoveQueueMember(techsupport,SIP/3000)
424 </example>
425 </description>
426 <see-also>
427 <ref type="application">Queue</ref>
428 <ref type="application">QueueLog</ref>
429 <ref type="application">AddQueueMember</ref>
430 <ref type="application">RemoveQueueMember</ref>
431 <ref type="application">PauseQueueMember</ref>
432 <ref type="application">UnpauseQueueMember</ref>
433 <ref type="function">QUEUE_VARIABLES</ref>
434 <ref type="function">QUEUE_MEMBER</ref>
435 <ref type="function">QUEUE_MEMBER_COUNT</ref>
436 <ref type="function">QUEUE_EXISTS</ref>
437 <ref type="function">QUEUE_GET_CHANNEL</ref>
438 <ref type="function">QUEUE_WAITING_COUNT</ref>
439 <ref type="function">QUEUE_MEMBER_LIST</ref>
440 <ref type="function">QUEUE_MEMBER_PENALTY</ref>
441 </see-also>
442 </application>
443 <application name="PauseQueueMember" language="en_US">
444 <since>
445 <version>1.2.0</version>
446 </since>
447 <synopsis>
448 Pauses a queue member.
449 </synopsis>
450 <syntax>
451 <parameter name="queuename" />
452 <parameter name="interface" required="true" />
453 <parameter name="options" />
454 <parameter name="reason">
455 <para>Is used to add extra information to the appropriate queue_log entries and manager events.</para>
456 </parameter>
457 </syntax>
458 <description>
459 <para>Pauses (blocks calls for) a queue member. The given interface will be paused in the given queue.
460 This prevents any calls from being sent from the queue to the interface until it is
461 unpaused with UnpauseQueueMember or the manager interface. If no queuename is given,
462 the interface is paused in every queue it is a member of. The application will fail if the
463 interface is not found.</para>
464 <para>This application sets the following channel variable upon completion:</para>
465 <variablelist>
466 <variable name="PQMSTATUS">
467 <para>The status of the attempt to pause a queue member as a text string.</para>
468 <value name="PAUSED" />
469 <value name="NOTFOUND" />
470 </variable>
471 </variablelist>
472 <example title="Pause queue member">
473 same => n,PauseQueueMember(,SIP/3000)
474 </example>
475 </description>
476 <see-also>
477 <ref type="application">Queue</ref>
478 <ref type="application">QueueLog</ref>
479 <ref type="application">AddQueueMember</ref>
480 <ref type="application">RemoveQueueMember</ref>
481 <ref type="application">PauseQueueMember</ref>
482 <ref type="application">UnpauseQueueMember</ref>
483 <ref type="function">QUEUE_VARIABLES</ref>
484 <ref type="function">QUEUE_MEMBER</ref>
485 <ref type="function">QUEUE_MEMBER_COUNT</ref>
486 <ref type="function">QUEUE_EXISTS</ref>
487 <ref type="function">QUEUE_GET_CHANNEL</ref>
488 <ref type="function">QUEUE_WAITING_COUNT</ref>
489 <ref type="function">QUEUE_MEMBER_LIST</ref>
490 <ref type="function">QUEUE_MEMBER_PENALTY</ref>
491 </see-also>
492 </application>
493 <application name="UnpauseQueueMember" language="en_US">
494 <since>
495 <version>1.2.0</version>
496 </since>
497 <synopsis>
498 Unpauses a queue member.
499 </synopsis>
500 <syntax>
501 <parameter name="queuename" />
502 <parameter name="interface" required="true" />
503 <parameter name="options" />
504 <parameter name="reason">
505 <para>Is used to add extra information to the appropriate queue_log entries and manager events.</para>
506 </parameter>
507 </syntax>
508 <description>
509 <para>Unpauses (resumes calls to) a queue member. This is the counterpart to <literal>PauseQueueMember()</literal>
510 and operates exactly the same way, except it unpauses instead of pausing the given interface.</para>
511 <para>This application sets the following channel variable upon completion:</para>
512 <variablelist>
513 <variable name="UPQMSTATUS">
514 <para>The status of the attempt to unpause a queue member as a text string.</para>
515 <value name="UNPAUSED" />
516 <value name="NOTFOUND" />
517 </variable>
518 </variablelist>
519 <example title="Unpause queue member">
520 same => n,UnpauseQueueMember(,SIP/3000)
521 </example>
522 </description>
523 <see-also>
524 <ref type="application">Queue</ref>
525 <ref type="application">QueueLog</ref>
526 <ref type="application">AddQueueMember</ref>
527 <ref type="application">RemoveQueueMember</ref>
528 <ref type="application">PauseQueueMember</ref>
529 <ref type="application">UnpauseQueueMember</ref>
530 <ref type="function">QUEUE_VARIABLES</ref>
531 <ref type="function">QUEUE_MEMBER</ref>
532 <ref type="function">QUEUE_MEMBER_COUNT</ref>
533 <ref type="function">QUEUE_EXISTS</ref>
534 <ref type="function">QUEUE_GET_CHANNEL</ref>
535 <ref type="function">QUEUE_WAITING_COUNT</ref>
536 <ref type="function">QUEUE_MEMBER_LIST</ref>
537 <ref type="function">QUEUE_MEMBER_PENALTY</ref>
538 </see-also>
539 </application>
540 <application name="QueueLog" language="en_US">
541 <since>
542 <version>1.4.0</version>
543 </since>
544 <synopsis>
545 Writes to the queue_log file.
546 </synopsis>
547 <syntax>
548 <parameter name="queuename" required="true" />
549 <parameter name="uniqueid" required="true" />
550 <parameter name="agent" required="true" />
551 <parameter name="event" required="true" />
552 <parameter name="additionalinfo" />
553 </syntax>
554 <description>
555 <para>Allows you to write your own events into the queue log.</para>
556 <example title="Log custom queue event">
557 same => n,QueueLog(101,${UNIQUEID},${AGENT},WENTONBREAK,600)
558 </example>
559 </description>
560 <see-also>
561 <ref type="application">Queue</ref>
562 <ref type="application">QueueLog</ref>
563 <ref type="application">AddQueueMember</ref>
564 <ref type="application">RemoveQueueMember</ref>
565 <ref type="application">PauseQueueMember</ref>
566 <ref type="application">UnpauseQueueMember</ref>
567 <ref type="function">QUEUE_VARIABLES</ref>
568 <ref type="function">QUEUE_MEMBER</ref>
569 <ref type="function">QUEUE_MEMBER_COUNT</ref>
570 <ref type="function">QUEUE_EXISTS</ref>
571 <ref type="function">QUEUE_GET_CHANNEL</ref>
572 <ref type="function">QUEUE_WAITING_COUNT</ref>
573 <ref type="function">QUEUE_MEMBER_LIST</ref>
574 <ref type="function">QUEUE_MEMBER_PENALTY</ref>
575 </see-also>
576 </application>
577 <application name="QueueUpdate" language="en_US">
578 <since>
579 <version>15.0.0</version>
580 </since>
581 <synopsis>
582 Writes to the queue_log file for outbound calls and updates Realtime Data.
583 Is used at h extension to be able to have all the parameters.
584 </synopsis>
585 <syntax>
586 <parameter name="queuename" required="true" />
587 <parameter name="uniqueid" required="true" />
588 <parameter name="agent" required="true" />
589 <parameter name="status" required="true" />
590 <parameter name="talktime" required="true" />
591 <parameter name="params" required="false" />
592 </syntax>
593 <description>
594 <para>Allows you to write Outbound events into the queue log.</para>
595 <example title="Write outbound event into queue log">
596 exten => h,1,QueueUpdate(${QUEUE}, ${UNIQUEID}, ${AGENT}, ${DIALSTATUS}, ${ANSWEREDTIME}, ${DIALEDTIME} | ${DIALEDNUMBER})
597 </example>
598 </description>
599 </application>
600 <function name="QUEUE_VARIABLES" language="en_US">
601 <since>
602 <version>1.6.0</version>
603 </since>
604 <synopsis>
605 Return Queue information in variables.
606 </synopsis>
607 <syntax>
608 <parameter name="queuename" required="true">
609 <enumlist>
610 <enum name="QUEUEMAX">
611 <para>Maximum number of calls allowed.</para>
612 </enum>
613 <enum name="QUEUESTRATEGY">
614 <para>The strategy of the queue.</para>
615 </enum>
616 <enum name="QUEUECALLS">
617 <para>Number of calls currently in the queue.</para>
618 </enum>
619 <enum name="QUEUEHOLDTIME">
620 <para>Current average hold time.</para>
621 </enum>
622 <enum name="QUEUECOMPLETED">
623 <para>Number of completed calls for the queue.</para>
624 </enum>
625 <enum name="QUEUEABANDONED">
626 <para>Number of abandoned calls.</para>
627 </enum>
628 <enum name="QUEUESRVLEVEL">
629 <para>Queue service level.</para>
630 </enum>
631 <enum name="QUEUESRVLEVELPERF">
632 <para>Current service level performance.</para>
633 </enum>
634 </enumlist>
635 </parameter>
636 </syntax>
637 <description>
638 <para>Makes the following queue variables available.</para>
639 <para>Returns <literal>0</literal> if queue is found and setqueuevar is defined, <literal>-1</literal> otherwise.</para>
640 </description>
641 <see-also>
642 <ref type="application">Queue</ref>
643 <ref type="application">QueueLog</ref>
644 <ref type="application">AddQueueMember</ref>
645 <ref type="application">RemoveQueueMember</ref>
646 <ref type="application">PauseQueueMember</ref>
647 <ref type="application">UnpauseQueueMember</ref>
648 <ref type="function">QUEUE_VARIABLES</ref>
649 <ref type="function">QUEUE_MEMBER</ref>
650 <ref type="function">QUEUE_MEMBER_COUNT</ref>
651 <ref type="function">QUEUE_EXISTS</ref>
652 <ref type="function">QUEUE_GET_CHANNEL</ref>
653 <ref type="function">QUEUE_WAITING_COUNT</ref>
654 <ref type="function">QUEUE_MEMBER_LIST</ref>
655 <ref type="function">QUEUE_MEMBER_PENALTY</ref>
656 </see-also>
657 </function>
658 <function name="QUEUE_MEMBER" language="en_US">
659 <since>
660 <version>1.6.0</version>
661 </since>
662 <synopsis>
663 Provides a count of queue members based on the provided criteria, or updates a
664 queue member's settings.
665 </synopsis>
666 <syntax>
667 <parameter name="queuename" required="false" />
668 <parameter name="option" required="true">
669 <enumlist>
670 <enum name="logged">
671 <para>Returns the number of logged-in members for the specified queue.</para>
672 </enum>
673 <enum name="free">
674 <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>
675 </enum>
676 <enum name="ready">
677 <para>Returns the number of logged-in members for the specified queue that are immediately available to answer a call.</para>
678 </enum>
679 <enum name="count">
680 <para>Returns the total number of members for the specified queue.</para>
681 </enum>
682 <enum name="penalty">
683 <para>Gets or sets queue member penalty. If
684 <replaceable>queuename</replaceable> is not specified
685 when setting the penalty then the penalty is set in all queues
686 the interface is a member.</para>
687 </enum>
688 <enum name="paused">
689 <para>Gets or sets queue member paused status. If
690 <replaceable>queuename</replaceable> is not specified
691 when setting the paused status then the paused status is set
692 in all queues the interface is a member.</para>
693 </enum>
694 <enum name="ringinuse">
695 <para>Gets or sets queue member ringinuse. If
696 <replaceable>queuename</replaceable> is not specified
697 when setting ringinuse then ringinuse is set
698 in all queues the interface is a member.</para>
699 </enum>
700 </enumlist>
701 </parameter>
702 <parameter name="interface" required="false" />
703 </syntax>
704 <description>
705 <para>Allows access to queue counts [R] and member information [R/W].</para>
706 <para><replaceable>queuename</replaceable> is required for all read operations.</para>
707 <para><replaceable>interface</replaceable> is required for all member operations.</para>
708 </description>
709 <see-also>
710 <ref type="application">Queue</ref>
711 <ref type="application">QueueLog</ref>
712 <ref type="application">AddQueueMember</ref>
713 <ref type="application">RemoveQueueMember</ref>
714 <ref type="application">PauseQueueMember</ref>
715 <ref type="application">UnpauseQueueMember</ref>
716 <ref type="function">QUEUE_VARIABLES</ref>
717 <ref type="function">QUEUE_MEMBER</ref>
718 <ref type="function">QUEUE_MEMBER_COUNT</ref>
719 <ref type="function">QUEUE_EXISTS</ref>
720 <ref type="function">QUEUE_GET_CHANNEL</ref>
721 <ref type="function">QUEUE_WAITING_COUNT</ref>
722 <ref type="function">QUEUE_MEMBER_LIST</ref>
723 <ref type="function">QUEUE_MEMBER_PENALTY</ref>
724 </see-also>
725 </function>
726 <function name="QUEUE_MEMBER_COUNT" language="en_US">
727 <since>
728 <version>1.4.0</version>
729 </since>
730 <synopsis>
731 Count number of members answering a queue.
732 </synopsis>
733 <syntax>
734 <parameter name="queuename" required="true" />
735 </syntax>
736 <description>
737 <para>Returns the number of members currently associated with the specified <replaceable>queuename</replaceable>.</para>
738 <warning><para>This function has been deprecated in favor of the <literal>QUEUE_MEMBER()</literal> function</para></warning>
739 </description>
740 <see-also>
741 <ref type="application">Queue</ref>
742 <ref type="application">QueueLog</ref>
743 <ref type="application">AddQueueMember</ref>
744 <ref type="application">RemoveQueueMember</ref>
745 <ref type="application">PauseQueueMember</ref>
746 <ref type="application">UnpauseQueueMember</ref>
747 <ref type="function">QUEUE_VARIABLES</ref>
748 <ref type="function">QUEUE_MEMBER</ref>
749 <ref type="function">QUEUE_MEMBER_COUNT</ref>
750 <ref type="function">QUEUE_EXISTS</ref>
751 <ref type="function">QUEUE_GET_CHANNEL</ref>
752 <ref type="function">QUEUE_WAITING_COUNT</ref>
753 <ref type="function">QUEUE_MEMBER_LIST</ref>
754 <ref type="function">QUEUE_MEMBER_PENALTY</ref>
755 </see-also>
756 </function>
757 <function name="QUEUE_EXISTS" language="en_US">
758 <since>
759 <version>1.8.0</version>
760 </since>
761 <synopsis>
762 Check if a named queue exists on this server
763 </synopsis>
764 <syntax>
765 <parameter name="queuename" />
766 </syntax>
767 <description>
768 <para>Returns 1 if the specified queue exists, 0 if it does not</para>
769 </description>
770 <see-also>
771 <ref type="application">Queue</ref>
772 <ref type="application">QueueLog</ref>
773 <ref type="application">AddQueueMember</ref>
774 <ref type="application">RemoveQueueMember</ref>
775 <ref type="application">PauseQueueMember</ref>
776 <ref type="application">UnpauseQueueMember</ref>
777 <ref type="function">QUEUE_VARIABLES</ref>
778 <ref type="function">QUEUE_MEMBER</ref>
779 <ref type="function">QUEUE_MEMBER_COUNT</ref>
780 <ref type="function">QUEUE_EXISTS</ref>
781 <ref type="function">QUEUE_GET_CHANNEL</ref>
782 <ref type="function">QUEUE_WAITING_COUNT</ref>
783 <ref type="function">QUEUE_MEMBER_LIST</ref>
784 <ref type="function">QUEUE_MEMBER_PENALTY</ref>
785 </see-also>
786 </function>
787 <function name="QUEUE_GET_CHANNEL" language="en_US">
788 <since>
789 <version>14.0.0</version>
790 </since>
791 <synopsis>
792 Return caller at the specified position in a queue.
793 </synopsis>
794 <syntax>
795 <parameter name="queuename" required="true" />
796 <parameter name="position" />
797 </syntax>
798 <description>
799 <para>Returns the caller channel at <replaceable>position</replaceable> in the specified <replaceable>queuename</replaceable>.</para>
800 <para>If <replaceable>position</replaceable> is unspecified the first channel is returned.</para>
801 </description>
802 <see-also>
803 <ref type="application">Queue</ref>
804 <ref type="application">QueueLog</ref>
805 <ref type="application">AddQueueMember</ref>
806 <ref type="application">RemoveQueueMember</ref>
807 <ref type="application">PauseQueueMember</ref>
808 <ref type="application">UnpauseQueueMember</ref>
809 <ref type="function">QUEUE_VARIABLES</ref>
810 <ref type="function">QUEUE_MEMBER</ref>
811 <ref type="function">QUEUE_MEMBER_COUNT</ref>
812 <ref type="function">QUEUE_EXISTS</ref>
813 <ref type="function">QUEUE_WAITING_COUNT</ref>
814 <ref type="function">QUEUE_MEMBER_LIST</ref>
815 <ref type="function">QUEUE_MEMBER_PENALTY</ref>
816 </see-also>
817 </function>
818 <function name="QUEUE_WAITING_COUNT" language="en_US">
819 <since>
820 <version>1.4.0</version>
821 </since>
822 <synopsis>
823 Count number of calls currently waiting in a queue.
824 </synopsis>
825 <syntax>
826 <parameter name="queuename" />
827 </syntax>
828 <description>
829 <para>Returns the number of callers currently waiting in the specified <replaceable>queuename</replaceable>.</para>
830 </description>
831 <see-also>
832 <ref type="application">Queue</ref>
833 <ref type="application">QueueLog</ref>
834 <ref type="application">AddQueueMember</ref>
835 <ref type="application">RemoveQueueMember</ref>
836 <ref type="application">PauseQueueMember</ref>
837 <ref type="application">UnpauseQueueMember</ref>
838 <ref type="function">QUEUE_VARIABLES</ref>
839 <ref type="function">QUEUE_MEMBER</ref>
840 <ref type="function">QUEUE_MEMBER_COUNT</ref>
841 <ref type="function">QUEUE_EXISTS</ref>
842 <ref type="function">QUEUE_GET_CHANNEL</ref>
843 <ref type="function">QUEUE_WAITING_COUNT</ref>
844 <ref type="function">QUEUE_MEMBER_LIST</ref>
845 <ref type="function">QUEUE_MEMBER_PENALTY</ref>
846 </see-also>
847 </function>
848 <function name="QUEUE_MEMBER_LIST" language="en_US">
849 <since>
850 <version>1.4.0</version>
851 </since>
852 <synopsis>
853 Returns a list of interfaces on a queue.
854 </synopsis>
855 <syntax>
856 <parameter name="queuename" required="true" />
857 </syntax>
858 <description>
859 <para>Returns a comma-separated list of members associated with the specified <replaceable>queuename</replaceable>.</para>
860 </description>
861 <see-also>
862 <ref type="application">Queue</ref>
863 <ref type="application">QueueLog</ref>
864 <ref type="application">AddQueueMember</ref>
865 <ref type="application">RemoveQueueMember</ref>
866 <ref type="application">PauseQueueMember</ref>
867 <ref type="application">UnpauseQueueMember</ref>
868 <ref type="function">QUEUE_VARIABLES</ref>
869 <ref type="function">QUEUE_MEMBER</ref>
870 <ref type="function">QUEUE_MEMBER_COUNT</ref>
871 <ref type="function">QUEUE_EXISTS</ref>
872 <ref type="function">QUEUE_GET_CHANNEL</ref>
873 <ref type="function">QUEUE_WAITING_COUNT</ref>
874 <ref type="function">QUEUE_MEMBER_LIST</ref>
875 <ref type="function">QUEUE_MEMBER_PENALTY</ref>
876 </see-also>
877 </function>
878 <function name="QUEUE_MEMBER_PENALTY" language="en_US">
879 <since>
880 <version>1.6.0</version>
881 </since>
882 <synopsis>
883 Gets or sets queue members penalty.
884 </synopsis>
885 <syntax>
886 <parameter name="queuename" required="true" />
887 <parameter name="interface" required="true" />
888 </syntax>
889 <description>
890 <para>Gets or sets queue members penalty.</para>
891 <warning><para>This function has been deprecated in favor of the <literal>QUEUE_MEMBER()</literal> function</para></warning>
892 </description>
893 <see-also>
894 <ref type="application">Queue</ref>
895 <ref type="application">QueueLog</ref>
896 <ref type="application">AddQueueMember</ref>
897 <ref type="application">RemoveQueueMember</ref>
898 <ref type="application">PauseQueueMember</ref>
899 <ref type="application">UnpauseQueueMember</ref>
900 <ref type="function">QUEUE_VARIABLES</ref>
901 <ref type="function">QUEUE_MEMBER</ref>
902 <ref type="function">QUEUE_MEMBER_COUNT</ref>
903 <ref type="function">QUEUE_EXISTS</ref>
904 <ref type="function">QUEUE_GET_CHANNEL</ref>
905 <ref type="function">QUEUE_WAITING_COUNT</ref>
906 <ref type="function">QUEUE_MEMBER_LIST</ref>
907 <ref type="function">QUEUE_MEMBER_PENALTY</ref>
908 </see-also>
909 </function>
910 <manager name="QueueStatus" language="en_US">
911 <since>
912 <version>0.5.0</version>
913 </since>
914 <synopsis>
915 Show queue status.
916 </synopsis>
917 <syntax>
918 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
919 <parameter name="Queue">
920 <para>Limit the response to the status of the specified queue.</para>
921 </parameter>
922 <parameter name="Member">
923 <para>Limit the response to the status of the specified member.</para>
924 </parameter>
925 </syntax>
926 <description>
927 <para>Check the status of one or more queues.</para>
928 </description>
929 </manager>
930 <manager name="QueueSummary" language="en_US">
931 <since>
932 <version>1.6.0</version>
933 </since>
934 <synopsis>
935 Show queue summary.
936 </synopsis>
937 <syntax>
938 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
939 <parameter name="Queue">
940 <para>Queue for which the summary is requested.</para>
941 </parameter>
942 </syntax>
943 <description>
944 <para>Request the manager to send a QueueSummary event.</para>
945 </description>
946 </manager>
947 <manager name="QueueAdd" language="en_US">
948 <since>
949 <version>1.0.0</version>
950 </since>
951 <synopsis>
952 Add interface to queue.
953 </synopsis>
954 <syntax>
955 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
956 <parameter name="Queue" required="true">
957 <para>Queue's name.</para>
958 </parameter>
959 <parameter name="Interface" required="true">
960 <para>The name of the interface (tech/name) to add to the queue.</para>
961 </parameter>
962 <parameter name="Penalty">
963 <para>A penalty (number) to apply to this member. Asterisk will distribute calls to members with higher penalties only after attempting to distribute calls to those with lower penalty.</para>
964 </parameter>
965 <parameter name="Paused">
966 <para>To pause or not the member initially (true/false or 1/0).</para>
967 </parameter>
968 <parameter name="Reason" required="false">
969 <para>Text description why the member is paused.</para>
970 </parameter>
971 <parameter name="MemberName">
972 <para>Text alias for the interface.</para>
973 </parameter>
974 <parameter name="StateInterface" />
975 </syntax>
976 <description>
977 </description>
978 </manager>
979 <manager name="QueueRemove" language="en_US">
980 <since>
981 <version>1.0.0</version>
982 </since>
983 <synopsis>
984 Remove interface from queue.
985 </synopsis>
986 <syntax>
987 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
988 <parameter name="Queue" required="true">
989 <para>The name of the queue to take action on.</para>
990 </parameter>
991 <parameter name="Interface" required="true">
992 <para>The interface (tech/name) to remove from queue.</para>
993 </parameter>
994 </syntax>
995 <description>
996 </description>
997 </manager>
998 <manager name="QueuePause" language="en_US">
999 <since>
1000 <version>1.2.0</version>
1001 </since>
1002 <synopsis>
1003 Makes a queue member temporarily unavailable.
1004 </synopsis>
1005 <syntax>
1006 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
1007 <parameter name="Interface" required="true">
1008 <para>The name of the interface (tech/name) to pause or unpause.</para>
1009 </parameter>
1010 <parameter name="Paused" required="true">
1011 <para>Pause or unpause the interface. Set to 'true' to pause the member or 'false' to unpause.</para>
1012 </parameter>
1013 <parameter name="Queue" required="false">
1014 <para>The name of the queue in which to pause or unpause this member. If not specified, the member will be paused or unpaused in all the queues it is a member of.</para>
1015 </parameter>
1016 <parameter name="Reason" required="false">
1017 <para>Text description, returned in the event QueueMemberPause.</para>
1018 </parameter>
1019 </syntax>
1020 <description>
1021 <para>Pause or unpause a member in a queue.</para>
1022 </description>
1023 </manager>
1024 <manager name="QueueLog" language="en_US">
1025 <since>
1026 <version>1.6.0</version>
1027 </since>
1028 <synopsis>
1029 Adds custom entry in queue_log.
1030 </synopsis>
1031 <syntax>
1032 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
1033 <parameter name="Queue" required="true" />
1034 <parameter name="Event" required="true" />
1035 <parameter name="Uniqueid" />
1036 <parameter name="Interface" />
1037 <parameter name="Message" />
1038 </syntax>
1039 <description>
1040 </description>
1041 </manager>
1042 <manager name="QueuePenalty" language="en_US">
1043 <since>
1044 <version>1.6.0</version>
1045 </since>
1046 <synopsis>
1047 Set the penalty for a queue member.
1048 </synopsis>
1049 <syntax>
1050 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
1051 <parameter name="Interface" required="true">
1052 <para>The interface (tech/name) of the member whose penalty to change.</para>
1053 </parameter>
1054 <parameter name="Penalty" required="true">
1055 <para>The new penalty (number) for the member. Must be nonnegative.</para>
1056 </parameter>
1057 <parameter name="Queue">
1058 <para>If specified, only set the penalty for the member of this queue. Otherwise, set the penalty for the member in all queues to which the member belongs.</para>
1059 </parameter>
1060 </syntax>
1061 <description>
1062 <para>Change the penalty of a queue member</para>
1063 </description>
1064 </manager>
1065 <manager name="QueueMemberRingInUse" language="en_US">
1066 <since>
1067 <version>11.0.0</version>
1068 </since>
1069 <synopsis>
1070 Set the ringinuse value for a queue member.
1071 </synopsis>
1072 <syntax>
1073 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
1074 <parameter name="Interface" required="true" />
1075 <parameter name="RingInUse" required="true" />
1076 <parameter name="Queue" />
1077 </syntax>
1078 <description>
1079 </description>
1080 </manager>
1081 <manager name="QueueRule" language="en_US">
1082 <since>
1083 <version>1.6.0</version>
1084 </since>
1085 <synopsis>
1086 Queue Rules.
1087 </synopsis>
1088 <syntax>
1089 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
1090 <parameter name="Rule">
1091 <para>The name of the rule in queuerules.conf whose contents to list.</para>
1092 </parameter>
1093 </syntax>
1094 <description>
1095 <para>List queue rules defined in queuerules.conf</para>
1096 </description>
1097 </manager>
1098 <manager name="QueueReload" language="en_US">
1099 <since>
1100 <version>1.6.2.0</version>
1101 </since>
1102 <synopsis>
1103 Reload a queue, queues, or any sub-section of a queue or queues.
1104 </synopsis>
1105 <syntax>
1106 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
1107 <parameter name="Queue">
1108 <para>The name of the queue to take action on. If no queue name is specified, then all queues are affected.</para>
1109 </parameter>
1110 <parameter name="Members">
1111 <para>Whether to reload the queue's members.</para>
1112 <enumlist>
1113 <enum name="yes" />
1114 <enum name="no" />
1115 </enumlist>
1116 </parameter>
1117 <parameter name="Rules">
1118 <para>Whether to reload queuerules.conf</para>
1119 <enumlist>
1120 <enum name="yes" />
1121 <enum name="no" />
1122 </enumlist>
1123 </parameter>
1124 <parameter name="Parameters">
1125 <para>Whether to reload the other queue options.</para>
1126 <enumlist>
1127 <enum name="yes" />
1128 <enum name="no" />
1129 </enumlist>
1130 </parameter>
1131 </syntax>
1132 <description>
1133 </description>
1134 </manager>
1135 <manager name="QueueReset" language="en_US">
1136 <since>
1137 <version>1.6.2.0</version>
1138 </since>
1139 <synopsis>
1140 Reset queue statistics.
1141 </synopsis>
1142 <syntax>
1143 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
1144 <parameter name="Queue">
1145 <para>The name of the queue on which to reset statistics.</para>
1146 </parameter>
1147 </syntax>
1148 <description>
1149 <para>Reset the statistics for a queue.</para>
1150 </description>
1151 </manager>
1152 <manager name="QueueChangePriorityCaller" language="en_US">
1153 <since>
1154 <version>15.0.0</version>
1155 </since>
1156 <synopsis>
1157 Change priority of a caller on queue.
1158 </synopsis>
1159 <syntax>
1160 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
1161 <parameter name="Queue" required="true">
1162 <para>The name of the queue to take action on.</para>
1163 </parameter>
1164 <parameter name="Caller" required="true">
1165 <para>The caller (channel) to change priority on queue.</para>
1166 </parameter>
1167
1168 <parameter name="Priority" required="true">
1169 <para>Priority value for change for caller on queue.</para>
1170 </parameter>
1171 <parameter name="Immediate">
1172 <para>When set to yes will cause the priority change to be reflected immediately, causing the channel to change position within the queue.</para>
1173 </parameter>
1174 </syntax>
1175 <description>
1176 </description>
1177 </manager>
1178 <manager name="QueueWithdrawCaller" language="en_US">
1179 <since>
1180 <version>19.3.0</version>
1181 <version>18.11.0</version>
1182 <version>16.25.0</version>
1183 </since>
1184 <synopsis>
1185 Request to withdraw a caller from the queue back to the dialplan.
1186 </synopsis>
1187 <syntax>
1188 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
1189 <parameter name="Queue" required="true">
1190 <para>The name of the queue to take action on.</para>
1191 </parameter>
1192 <parameter name="Caller" required="true">
1193 <para>The caller (channel) to withdraw from the queue.</para>
1194 </parameter>
1195 <parameter name="WithdrawInfo" required="false">
1196 <para>Optional info to store. If the call is successfully withdrawn from the queue, this information will be available in the QUEUE_WITHDRAW_INFO variable.</para>
1197 </parameter>
1198 </syntax>
1199 <description>
1200 </description>
1201 </manager>
1202
1203 <managerEvent language="en_US" name="QueueParams">
1204 <managerEventInstance class="EVENT_FLAG_AGENT">
1205 <since>
1206 <version>16.24.0</version>
1207 <version>18.10.0</version>
1208 <version>19.2.0</version>
1209 </since>
1210 <synopsis>Raised in response to the QueueStatus action.</synopsis>
1211 <syntax>
1212 <parameter name="Max">
1213 <para>The name of the queue.</para>
1214 </parameter>
1215 <parameter name="Strategy">
1216 <para>The strategy of the queue.</para>
1217 </parameter>
1218 <parameter name="Calls">
1219 <para>The queue member's channel technology or location.</para>
1220 </parameter>
1221 <parameter name="Holdtime">
1222 <para>The queue's hold time.</para>
1223 </parameter>
1224 <parameter name="TalkTime">
1225 <para>The queue's talk time.</para>
1226 </parameter>
1227 <parameter name="Completed">
1228 <para>The queue's completion time.</para>
1229 </parameter>
1230 <parameter name="Abandoned">
1231 <para>The queue's call abandonment metric.</para>
1232 </parameter>
1233 <parameter name="ServiceLevelPerf">
1234 <para>Primary service level performance metric.</para>
1235 </parameter>
1236 <parameter name="ServiceLevelPerf2">
1237 <para>Secondary service level performance metric.</para>
1238 </parameter>
1239 </syntax>
1240 <see-also>
1241 <ref type="managerEvent">QueueMember</ref>
1242 <ref type="managerEvent">QueueEntry</ref>
1243 </see-also>
1244 </managerEventInstance>
1245 </managerEvent>
1246 <managerEvent language="en_US" name="QueueEntry">
1247 <managerEventInstance class="EVENT_FLAG_AGENT">
1248 <since>
1249 <version>16.24.0</version>
1250 <version>18.10.0</version>
1251 <version>19.2.0</version>
1252 </since>
1253 <synopsis>Raised in response to the QueueStatus action.</synopsis>
1254 <syntax>
1255 <parameter name="Queue">
1256 <para>The name of the queue.</para>
1257 </parameter>
1258 <parameter name="Position">
1259 <para>The caller's position within the queue.</para>
1260 </parameter>
1261 <parameter name="Channel">
1262 <para>The name of the caller's channel.</para>
1263 </parameter>
1264 <parameter name="Uniqueid">
1265 <para>The unique ID of the channel.</para>
1266 </parameter>
1267 <parameter name="CallerIDNum">
1268 <para>The Caller ID number.</para>
1269 </parameter>
1270 <parameter name="CallerIDName">
1271 <para>The Caller ID name.</para>
1272 </parameter>
1273 <parameter name="ConnectedLineNum">
1274 <para>The bridged party's number.</para>
1275 </parameter>
1276 <parameter name="ConnectedLineName">
1277 <para>The bridged party's name.</para>
1278 </parameter>
1279 <parameter name="Wait">
1280 <para>The caller's wait time.</para>
1281 </parameter>
1282 <parameter name="Priority">
1283 <para>The caller's priority within the queue.</para>
1284 </parameter>
1285 </syntax>
1286 <see-also>
1287 <ref type="managerEvent">QueueParams</ref>
1288 <ref type="managerEvent">QueueMember</ref>
1289 </see-also>
1290 </managerEventInstance>
1291 </managerEvent>
1292 <managerEvent language="en_US" name="QueueMemberStatus">
1293 <managerEventInstance class="EVENT_FLAG_AGENT">
1294 <since>
1295 <version>12.0.0</version>
1296 </since>
1297 <synopsis>Raised when a Queue member's status has changed.</synopsis>
1298 <syntax>
1299 <parameter name="Queue">
1300 <para>The name of the queue.</para>
1301 </parameter>
1302 <parameter name="MemberName">
1303 <para>The name of the queue member.</para>
1304 </parameter>
1305 <parameter name="Interface">
1306 <para>The queue member's channel technology or location.</para>
1307 </parameter>
1308 <parameter name="StateInterface">
1309 <para>Channel technology or location from which to read device state changes.</para>
1310 </parameter>
1311 <parameter name="Membership">
1312 <enumlist>
1313 <enum name="dynamic"/>
1314 <enum name="realtime"/>
1315 <enum name="static"/>
1316 </enumlist>
1317 </parameter>
1318 <parameter name="Penalty">
1319 <para>The penalty associated with the queue member.</para>
1320 </parameter>
1321 <parameter name="CallsTaken">
1322 <para>The number of calls this queue member has serviced.</para>
1323 </parameter>
1324 <parameter name="LastCall">
1325 <para>The time this member last took a call, expressed in seconds since 00:00, Jan 1, 1970 UTC.</para>
1326 </parameter>
1327 <parameter name="LastPause">
1328 <para>The time when started last paused the queue member.</para>
1329 </parameter>
1330 <parameter name="LoginTime">
1331 <para>The time this member logged in to the queue, expressed in seconds since 00:00, Jan 1, 1970 UTC.</para>
1332 </parameter>
1333 <parameter name="InCall">
1334 <para>Set to 1 if member is in call. Set to 0 after LastCall time is updated.</para>
1335 <enumlist>
1336 <enum name="0"/>
1337 <enum name="1"/>
1338 </enumlist>
1339 </parameter>
1340 <parameter name="Status">
1341 <para>The numeric device state status of the queue member.</para>
1342 <enumlist>
1343 <enum name="0"><para>AST_DEVICE_UNKNOWN</para></enum>
1344 <enum name="1"><para>AST_DEVICE_NOT_INUSE</para></enum>
1345 <enum name="2"><para>AST_DEVICE_INUSE</para></enum>
1346 <enum name="3"><para>AST_DEVICE_BUSY</para></enum>
1347 <enum name="4"><para>AST_DEVICE_INVALID</para></enum>
1348 <enum name="5"><para>AST_DEVICE_UNAVAILABLE</para></enum>
1349 <enum name="6"><para>AST_DEVICE_RINGING</para></enum>
1350 <enum name="7"><para>AST_DEVICE_RINGINUSE</para></enum>
1351 <enum name="8"><para>AST_DEVICE_ONHOLD</para></enum>
1352 </enumlist>
1353 </parameter>
1354 <parameter name="Paused">
1355 <enumlist>
1356 <enum name="0"/>
1357 <enum name="1"/>
1358 </enumlist>
1359 </parameter>
1360 <parameter name="PausedReason">
1361 <para>If set when paused, the reason the queue member was paused.</para>
1362 </parameter>
1363 <parameter name="Ringinuse">
1364 <enumlist>
1365 <enum name="0"/>
1366 <enum name="1"/>
1367 </enumlist>
1368 </parameter>
1369 <parameter name="Wrapuptime">
1370 <para>The Wrapup Time of the queue member. If this value is set will override the wrapup time of queue.</para>
1371 </parameter>
1372 </syntax>
1373 </managerEventInstance>
1374 </managerEvent>
1375 <managerEvent language="en_US" name="QueueMemberAdded">
1376 <managerEventInstance class="EVENT_FLAG_AGENT">
1377 <since>
1378 <version>12.0.0</version>
1379 </since>
1380 <synopsis>Raised when a member is added to the queue.</synopsis>
1381 <syntax>
1382 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter)" />
1383 </syntax>
1384 <see-also>
1385 <ref type="managerEvent">QueueMemberRemoved</ref>
1386 <ref type="application">AddQueueMember</ref>
1387 </see-also>
1388 </managerEventInstance>
1389 </managerEvent>
1390 <managerEvent language="en_US" name="QueueMemberRemoved">
1391 <managerEventInstance class="EVENT_FLAG_AGENT">
1392 <since>
1393 <version>12.0.0</version>
1394 </since>
1395 <synopsis>Raised when a member is removed from the queue.</synopsis>
1396 <syntax>
1397 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter)" />
1398 </syntax>
1399 <see-also>
1400 <ref type="managerEvent">QueueMemberAdded</ref>
1401 <ref type="application">RemoveQueueMember</ref>
1402 </see-also>
1403 </managerEventInstance>
1404 </managerEvent>
1405 <managerEvent language="en_US" name="QueueMemberPause">
1406 <managerEventInstance class="EVENT_FLAG_AGENT">
1407 <since>
1408 <version>12.2.0</version>
1409 </since>
1410 <synopsis>Raised when a member is paused/unpaused in the queue.</synopsis>
1411 <syntax>
1412 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter)" />
1413 </syntax>
1414 <see-also>
1415 <ref type="application">PauseQueueMember</ref>
1416 <ref type="application">UnpauseQueueMember</ref>
1417 </see-also>
1418 </managerEventInstance>
1419 </managerEvent>
1420 <managerEvent language="en_US" name="QueueMemberPenalty">
1421 <managerEventInstance class="EVENT_FLAG_AGENT">
1422 <since>
1423 <version>12.0.0</version>
1424 </since>
1425 <synopsis>Raised when a member's penalty is changed.</synopsis>
1426 <syntax>
1427 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter)" />
1428 </syntax>
1429 <see-also>
1430 <ref type="function">QUEUE_MEMBER</ref>
1431 </see-also>
1432 </managerEventInstance>
1433 </managerEvent>
1434 <managerEvent language="en_US" name="QueueMemberRinginuse">
1435 <managerEventInstance class="EVENT_FLAG_AGENT">
1436 <since>
1437 <version>12.0.0</version>
1438 </since>
1439 <synopsis>Raised when a member's ringinuse setting is changed.</synopsis>
1440 <syntax>
1441 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter)" />
1442 </syntax>
1443 <see-also>
1444 <ref type="function">QUEUE_MEMBER</ref>
1445 </see-also>
1446 </managerEventInstance>
1447 </managerEvent>
1448 <managerEvent language="en_US" name="QueueCallerJoin">
1449 <managerEventInstance class="EVENT_FLAG_AGENT">
1450 <since>
1451 <version>12.0.0</version>
1452 </since>
1453 <synopsis>Raised when a caller joins a Queue.</synopsis>
1454 <syntax>
1455 <channel_snapshot/>
1456 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='Queue'])" />
1457 <parameter name="Position">
1458 <para>This channel's current position in the queue.</para>
1459 </parameter>
1460 <parameter name="Count">
1461 <para>The total number of channels in the queue.</para>
1462 </parameter>
1463 </syntax>
1464 <see-also>
1465 <ref type="managerEvent">QueueCallerLeave</ref>
1466 <ref type="application">Queue</ref>
1467 </see-also>
1468 </managerEventInstance>
1469 </managerEvent>
1470 <managerEvent language="en_US" name="QueueCallerLeave">
1471 <managerEventInstance class="EVENT_FLAG_AGENT">
1472 <since>
1473 <version>12.0.0</version>
1474 </since>
1475 <synopsis>Raised when a caller leaves a Queue.</synopsis>
1476 <syntax>
1477 <channel_snapshot/>
1478 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='Queue'])" />
1479 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueCallerJoin']/managerEventInstance/syntax/parameter[@name='Count'])" />
1480 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueCallerJoin']/managerEventInstance/syntax/parameter[@name='Position'])" />
1481 </syntax>
1482 <see-also>
1483 <ref type="managerEvent">QueueCallerJoin</ref>
1484 </see-also>
1485 </managerEventInstance>
1486 </managerEvent>
1487 <managerEvent language="en_US" name="QueueCallerAbandon">
1488 <managerEventInstance class="EVENT_FLAG_AGENT">
1489 <since>
1490 <version>12.0.0</version>
1491 </since>
1492 <synopsis>Raised when a caller abandons the queue.</synopsis>
1493 <syntax>
1494 <channel_snapshot/>
1495 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='Queue'])" />
1496 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueCallerJoin']/managerEventInstance/syntax/parameter[@name='Position'])" />
1497 <parameter name="OriginalPosition">
1498 <para>The channel's original position in the queue.</para>
1499 </parameter>
1500 <parameter name="HoldTime">
1501 <para>The time the channel was in the queue, expressed in seconds since 00:00, Jan 1, 1970 UTC.</para>
1502 </parameter>
1503 </syntax>
1504 </managerEventInstance>
1505 </managerEvent>
1506 <managerEvent language="en_US" name="AgentCalled">
1507 <managerEventInstance class="EVENT_FLAG_AGENT">
1508 <since>
1509 <version>12.0.0</version>
1510 </since>
1511 <synopsis>Raised when an queue member is notified of a caller in the queue.</synopsis>
1512 <syntax>
1513 <channel_snapshot/>
1514 <channel_snapshot prefix="Dest"/>
1515 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='Queue'])" />
1516 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='MemberName'])" />
1517 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='Interface'])" />
1518 </syntax>
1519 <see-also>
1520 <ref type="managerEvent">AgentRingNoAnswer</ref>
1521 <ref type="managerEvent">AgentComplete</ref>
1522 <ref type="managerEvent">AgentConnect</ref>
1523 </see-also>
1524 </managerEventInstance>
1525 </managerEvent>
1526 <managerEvent language="en_US" name="AgentRingNoAnswer">
1527 <managerEventInstance class="EVENT_FLAG_AGENT">
1528 <since>
1529 <version>12.0.0</version>
1530 </since>
1531 <synopsis>Raised when a queue member is notified of a caller in the queue and fails to answer.</synopsis>
1532 <syntax>
1533 <channel_snapshot/>
1534 <channel_snapshot prefix="Dest"/>
1535 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='Queue'])" />
1536 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='MemberName'])" />
1537 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='Interface'])" />
1538 <parameter name="RingTime">
1539 <para>The time the queue member was rung, expressed in seconds since 00:00, Jan 1, 1970 UTC.</para>
1540 </parameter>
1541 </syntax>
1542 <see-also>
1543 <ref type="managerEvent">AgentCalled</ref>
1544 </see-also>
1545 </managerEventInstance>
1546 </managerEvent>
1547 <managerEvent language="en_US" name="AgentComplete">
1548 <managerEventInstance class="EVENT_FLAG_AGENT">
1549 <since>
1550 <version>12.0.0</version>
1551 </since>
1552 <synopsis>Raised when a queue member has finished servicing a caller in the queue.</synopsis>
1553 <syntax>
1554 <channel_snapshot/>
1555 <channel_snapshot prefix="Dest"/>
1556 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='Queue'])" />
1557 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='MemberName'])" />
1558 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='Interface'])" />
1559 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueCallerAbandon']/managerEventInstance/syntax/parameter[@name='HoldTime'])" />
1560 <parameter name="TalkTime">
1561 <para>The time the queue member talked with the caller in the queue, expressed in seconds since 00:00, Jan 1, 1970 UTC.</para>
1562 </parameter>
1563 <parameter name="Reason">
1564 <enumlist>
1565 <enum name="caller"/>
1566 <enum name="agent"/>
1567 <enum name="transfer"/>
1568 </enumlist>
1569 </parameter>
1570 </syntax>
1571 <see-also>
1572 <ref type="managerEvent">AgentCalled</ref>
1573 <ref type="managerEvent">AgentConnect</ref>
1574 </see-also>
1575 </managerEventInstance>
1576 </managerEvent>
1577 <managerEvent language="en_US" name="AgentDump">
1578 <managerEventInstance class="EVENT_FLAG_AGENT">
1579 <since>
1580 <version>12.0.0</version>
1581 </since>
1582 <synopsis>Raised when a queue member hangs up on a caller in the queue.</synopsis>
1583 <syntax>
1584 <channel_snapshot/>
1585 <channel_snapshot prefix="Dest"/>
1586 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='Queue'])" />
1587 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='MemberName'])" />
1588 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='Interface'])" />
1589 </syntax>
1590 <see-also>
1591 <ref type="managerEvent">AgentCalled</ref>
1592 <ref type="managerEvent">AgentConnect</ref>
1593 </see-also>
1594 </managerEventInstance>
1595 </managerEvent>
1596 <managerEvent language="en_US" name="AgentConnect">
1597 <managerEventInstance class="EVENT_FLAG_AGENT">
1598 <since>
1599 <version>12.0.0</version>
1600 </since>
1601 <synopsis>Raised when a queue member answers and is bridged to a caller in the queue.</synopsis>
1602 <syntax>
1603 <channel_snapshot/>
1604 <channel_snapshot prefix="Dest"/>
1605 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='Queue'])" />
1606 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='MemberName'])" />
1607 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='Interface'])" />
1608 <xi:include xpointer="xpointer(/docs/managerEvent[@name='AgentRingNoAnswer']/managerEventInstance/syntax/parameter[@name='RingTime'])" />
1609 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueCallerAbandon']/managerEventInstance/syntax/parameter[@name='HoldTime'])" />
1610 </syntax>
1611 <see-also>
1612 <ref type="managerEvent">AgentCalled</ref>
1613 <ref type="managerEvent">AgentComplete</ref>
1614 <ref type="managerEvent">AgentDump</ref>
1615 </see-also>
1616 </managerEventInstance>
1617 </managerEvent>
1618 ***/
1619
1620 enum {
1621 OPT_MARK_AS_ANSWERED = (1 << 0),
1622 OPT_GO_ON = (1 << 1),
1623 OPT_DATA_QUALITY = (1 << 2),
1624 OPT_CALLEE_GO_ON = (1 << 3),
1625 OPT_CALLEE_HANGUP = (1 << 4),
1626 OPT_CALLER_HANGUP = (1 << 5),
1627 OPT_IGNORE_CALL_FW = (1 << 6),
1628 OPT_IGNORE_CONNECTEDLINE = (1 << 7),
1629 OPT_CALLEE_PARK = (1 << 8),
1630 OPT_CALLER_PARK = (1 << 9),
1631 OPT_NO_RETRY = (1 << 10),
1632 OPT_RINGING = (1 << 11),
1633 OPT_RING_WHEN_RINGING = (1 << 12),
1634 OPT_CALLEE_TRANSFER = (1 << 13),
1635 OPT_CALLER_TRANSFER = (1 << 14),
1636 OPT_CALLEE_AUTOMIXMON = (1 << 15),
1637 OPT_CALLER_AUTOMIXMON = (1 << 16),
1638 OPT_CALLEE_AUTOMON = (1 << 17),
1639 OPT_CALLER_AUTOMON = (1 << 18),
1640 OPT_PREDIAL_CALLEE = (1 << 19),
1641 OPT_PREDIAL_CALLER = (1 << 20),
1642 OPT_MUSICONHOLD_CLASS = (1 << 21),
1643 };
1644
1645 enum {
1646 OPT_ARG_CALLEE_GO_ON = 0,
1647 OPT_ARG_PREDIAL_CALLEE,
1648 OPT_ARG_PREDIAL_CALLER,
1649 OPT_ARG_MUSICONHOLD_CLASS,
1650 /* note: this entry _MUST_ be the last one in the enum */
1651 OPT_ARG_ARRAY_SIZE
1652 };
1653
1654 AST_APP_OPTIONS(queue_exec_options, BEGIN_OPTIONS
1655 AST_APP_OPTION_ARG('b', OPT_PREDIAL_CALLEE, OPT_ARG_PREDIAL_CALLEE),
1656 AST_APP_OPTION_ARG('B', OPT_PREDIAL_CALLER, OPT_ARG_PREDIAL_CALLER),
1657 AST_APP_OPTION('C', OPT_MARK_AS_ANSWERED),
1658 AST_APP_OPTION('c', OPT_GO_ON),
1659 AST_APP_OPTION('d', OPT_DATA_QUALITY),
1660 AST_APP_OPTION_ARG('F', OPT_CALLEE_GO_ON, OPT_ARG_CALLEE_GO_ON),
1661 AST_APP_OPTION('h', OPT_CALLEE_HANGUP),
1662 AST_APP_OPTION('H', OPT_CALLER_HANGUP),
1663 AST_APP_OPTION('i', OPT_IGNORE_CALL_FW),
1664 AST_APP_OPTION('I', OPT_IGNORE_CONNECTEDLINE),
1665 AST_APP_OPTION('k', OPT_CALLEE_PARK),
1666 AST_APP_OPTION('K', OPT_CALLER_PARK),
1667 AST_APP_OPTION_ARG('m', OPT_MUSICONHOLD_CLASS, OPT_ARG_MUSICONHOLD_CLASS),
1668 AST_APP_OPTION('n', OPT_NO_RETRY),
1669 AST_APP_OPTION('r', OPT_RINGING),
1670 AST_APP_OPTION('R', OPT_RING_WHEN_RINGING),
1671 AST_APP_OPTION('t', OPT_CALLEE_TRANSFER),
1672 AST_APP_OPTION('T', OPT_CALLER_TRANSFER),
1673 AST_APP_OPTION('x', OPT_CALLEE_AUTOMIXMON),
1674 AST_APP_OPTION('X', OPT_CALLER_AUTOMIXMON),
1675 AST_APP_OPTION('w', OPT_CALLEE_AUTOMON),
1676 AST_APP_OPTION('W', OPT_CALLER_AUTOMON),
1677 END_OPTIONS);
1678
1679
1680 enum aqm_flags {
1681 AQMFLAG_PAUSED = (1 << 1),
1682 AQMFLAG_REASON = (1 << 2),
1683 };
1684
1685 enum aqm_args {
1686 AQM_OPT_ARG_PAUSE_REASON = 0,
1687 AQM_OPT_ARG_ARRAY_SIZE, /* Always last element of the enum */
1688 };
1689
1690 AST_APP_OPTIONS(aqm_opts, {
1691 AST_APP_OPTION('p', AQMFLAG_PAUSED),
1692 AST_APP_OPTION_ARG('r', AQMFLAG_REASON, AQM_OPT_ARG_PAUSE_REASON),
1693 });
1694
1695 enum {
1696 QUEUE_STRATEGY_RINGALL = 0,
1697 QUEUE_STRATEGY_LEASTRECENT,
1698 QUEUE_STRATEGY_FEWESTCALLS,
1699 QUEUE_STRATEGY_RANDOM,
1700 QUEUE_STRATEGY_RRMEMORY,
1701 QUEUE_STRATEGY_LINEAR,
1702 QUEUE_STRATEGY_WRANDOM,
1703 QUEUE_STRATEGY_RRORDERED,
1704 };
1705
1706 enum {
1707 QUEUE_AUTOPAUSE_OFF = 0,
1708 QUEUE_AUTOPAUSE_ON,
1709 QUEUE_AUTOPAUSE_ALL
1710 };
1711
1712 enum queue_reload_mask {
1713 QUEUE_RELOAD_PARAMETERS = (1 << 0),
1714 QUEUE_RELOAD_MEMBER = (1 << 1),
1715 QUEUE_RELOAD_RULES = (1 << 2),
1716 QUEUE_RESET_STATS = (1 << 3),
1717 };
1718
1719 static const struct strategy {
1720 int strategy;
1721 const char *name;
1722 } strategies[] = {
1723 { QUEUE_STRATEGY_RINGALL, "ringall" },
1724 { QUEUE_STRATEGY_LEASTRECENT, "leastrecent" },
1725 { QUEUE_STRATEGY_FEWESTCALLS, "fewestcalls" },
1726 { QUEUE_STRATEGY_RANDOM, "random" },
1727 { QUEUE_STRATEGY_RRMEMORY, "rrmemory" },
1728 { QUEUE_STRATEGY_RRMEMORY, "roundrobin" },
1729 { QUEUE_STRATEGY_LINEAR, "linear" },
1730 { QUEUE_STRATEGY_WRANDOM, "wrandom"},
1731 { QUEUE_STRATEGY_RRORDERED, "rrordered"},
1732 };
1733
1734 static const struct autopause {
1735 int autopause;
1736 const char *name;
1737 } autopausesmodes [] = {
1738 { QUEUE_AUTOPAUSE_OFF,"no" },
1739 { QUEUE_AUTOPAUSE_ON, "yes" },
1740 { QUEUE_AUTOPAUSE_ALL,"all" },
1741 };
1742
1743 #define DEFAULT_RETRY 5
1744 #define DEFAULT_TIMEOUT 15
1745 #define RECHECK 1 /*!< Recheck every second to see we we're at the top yet */
1746 #define MAX_PERIODIC_ANNOUNCEMENTS 10 /*!< The maximum periodic announcements we can have */
1747 /*!
1748 * \brief The minimum number of seconds between position announcements.
1749 * \note The default value of 15 provides backwards compatibility.
1750 */
1751 #define DEFAULT_MIN_ANNOUNCE_FREQUENCY 15
1752
1753 #define MAX_QUEUE_BUCKETS 53
1754
1755 #define RES_OKAY 0 /*!< Action completed */
1756 #define RES_EXISTS (-1) /*!< Entry already exists */
1757 #define RES_OUTOFMEMORY (-2) /*!< Out of memory */
1758 #define RES_NOSUCHQUEUE (-3) /*!< No such queue */
1759 #define RES_NOT_DYNAMIC (-4) /*!< Member is not dynamic */
1760 #define RES_NOT_CALLER (-5) /*!< Caller not found */
1761
1762 static char *app = "Queue";
1763
1764 static char *app_aqm = "AddQueueMember" ;
1765
1766 static char *app_rqm = "RemoveQueueMember" ;
1767
1768 static char *app_pqm = "PauseQueueMember" ;
1769
1770 static char *app_upqm = "UnpauseQueueMember" ;
1771
1772 static char *app_ql = "QueueLog" ;
1773
1774 static char *app_qupd = "QueueUpdate";
1775
1776 /*! \brief Persistent Members astdb family */
1777 static const char * const pm_family = "Queue/PersistentMembers";
1778
1779 /*! \brief queues.conf [general] option */
1780 static int queue_persistent_members;
1781
1782 /*! \brief Records that one or more queues use weight */
1783 static int use_weight;
1784
1785 /*! \brief queues.conf [general] option */
1786 static int autofill_default;
1787
1788 /*! \brief queues.conf [general] option */
1789 static int montype_default;
1790
1791 /*! \brief queues.conf [general] option */
1792 static int shared_lastcall;
1793
1794 /*! \brief queuerules.conf [general] option */
1795 static int realtime_rules;
1796
1797 /*! \brief Subscription to device state change messages */
1798 static struct stasis_subscription *device_state_sub;
1799
1800 /*! \brief queues.conf [general] option */
1801 static int negative_penalty_invalid;
1802
1803 /*! \brief queues.conf [general] option */
1804 static int log_membername_as_agent;
1805
1806 /*! \brief queues.conf [general] option */
1807 static int force_longest_waiting_caller;
1808
1809 /*! \brief queues.conf [general] option */
1810 static int log_caller_id_name;
1811
1812 /*! \brief queues.conf [general] option */
1813 static int log_unpause_on_reason_change;
1814
1815 /*! \brief name of the ringinuse field in the realtime database */
1816 static char *realtime_ringinuse_field;
1817
1818 /*! \brief does realtime backend support reason_paused */
1819 static int realtime_reason_paused;
1820
1821 enum queue_result {
1822 QUEUE_UNKNOWN = 0,
1823 QUEUE_TIMEOUT = 1,
1824 QUEUE_JOINEMPTY = 2,
1825 QUEUE_LEAVEEMPTY = 3,
1826 QUEUE_JOINUNAVAIL = 4,
1827 QUEUE_LEAVEUNAVAIL = 5,
1828 QUEUE_FULL = 6,
1829 QUEUE_CONTINUE = 7,
1830 QUEUE_WITHDRAW = 8,
1831 };
1832
1833 static const struct {
1834 enum queue_result id;
1835 char *text;
1836 } queue_results[] = {
1837 { QUEUE_UNKNOWN, "UNKNOWN" },
1838 { QUEUE_TIMEOUT, "TIMEOUT" },
1839 { QUEUE_JOINEMPTY,"JOINEMPTY" },
1840 { QUEUE_LEAVEEMPTY, "LEAVEEMPTY" },
1841 { QUEUE_JOINUNAVAIL, "JOINUNAVAIL" },
1842 { QUEUE_LEAVEUNAVAIL, "LEAVEUNAVAIL" },
1843 { QUEUE_FULL, "FULL" },
1844 { QUEUE_CONTINUE, "CONTINUE" },
1845 { QUEUE_WITHDRAW, "WITHDRAW" },
1846 };
1847
1848 enum queue_timeout_priority {
1849 TIMEOUT_PRIORITY_APP,
1850 TIMEOUT_PRIORITY_CONF,
1851 };
1852
1853 /*! \brief We define a custom "local user" structure because we
1854 * use it not only for keeping track of what is in use but
1855 * also for keeping track of who we're dialing.
1856 *
1857 * There are two "links" defined in this structure, q_next and call_next.
1858 * q_next links ALL defined callattempt structures into a linked list. call_next is
1859 * a link which allows for a subset of the callattempts to be traversed. This subset
1860 * is used in wait_for_answer so that irrelevant callattempts are not traversed. This
1861 * also is helpful so that queue logs are always accurate in the case where a call to
1862 * a member times out, especially if using the ringall strategy.
1863 */
1864
1865 struct callattempt {
1866 struct callattempt *q_next;
1867 struct callattempt *call_next;
1868 struct ast_channel *chan;
1869 char interface[256]; /*!< An Asterisk dial string (not a channel name) */
1870 int metric;
1871 struct member *member;
1872 /*! Saved connected party info from an AST_CONTROL_CONNECTED_LINE. */
1873 struct ast_party_connected_line connected;
1874 /*! TRUE if an AST_CONTROL_CONNECTED_LINE update was saved to the connected element. */
1875 unsigned int pending_connected_update:1;
1876 /*! TRUE if the connected line update is blocked. */
1877 unsigned int block_connected_update:1;
1878 /*! TRUE if caller id is not available for connected line */
1879 unsigned int dial_callerid_absent:1;
1880 /*! TRUE if the call is still active */
1881 unsigned int stillgoing:1;
1882 struct ast_aoc_decoded *aoc_s_rate_list;
1883 /*! Original channel name. Must be freed. Could be NULL if allocation failed. */
1884 char *orig_chan_name;
1885 };
1886
1887
1888 struct queue_ent {
1889 struct call_queue *parent; /*!< What queue is our parent */
1890 char moh[MAX_MUSICCLASS]; /*!< Name of musiconhold to be used */
1891 char announce[PATH_MAX]; /*!< Announcement to play for member when call is answered */
1892 char context[AST_MAX_CONTEXT]; /*!< Context when user exits queue */
1893 char digits[AST_MAX_EXTENSION]; /*!< Digits entered while in queue */
1894 const char *predial_callee; /*!< Gosub app arguments for outgoing calls. NULL if not supplied. */
1895 int valid_digits; /*!< Digits entered correspond to valid extension. Exited */
1896 int pos; /*!< Where we are in the queue */
1897 int prio; /*!< Our priority */
1898 int last_pos_said; /*!< Last position we told the user */
1899 int ring_when_ringing; /*!< Should we only use ring indication when a channel is ringing? */
1900 time_t last_periodic_announce_time; /*!< The last time we played a periodic announcement */
1901 int last_periodic_announce_sound; /*!< The last periodic announcement we made */
1902 time_t last_pos; /*!< Last time we told the user their position */
1903 int opos; /*!< Where we started in the queue */
1904 int handled; /*!< Whether our call was handled */
1905 int pending; /*!< Non-zero if we are attempting to call a member */
1906 int max_penalty; /*!< Limit the members that can take this call to this penalty or lower */
1907 int min_penalty; /*!< Limit the members that can take this call to this penalty or higher */
1908 int raise_penalty; /*!< Float lower penalty members to a minimum penalty */
1909 int raise_respect_min; /*!< A switch raise_penalty should respect min_penalty not just max_penalty */
1910 int linpos; /*!< If using linear strategy, what position are we at? */
1911 int linwrapped; /*!< Is the linpos wrapped? */
1912 time_t start; /*!< When we started holding */
1913 time_t expire; /*!< When this entry should expire (time out of queue) */
1914 int cancel_answered_elsewhere; /*!< Whether we should force the CAE flag on this call (C) option*/
1915 unsigned int withdraw:1; /*!< Should this call exit the queue at its next iteration? Used for QueueWithdrawCaller */
1916 char *withdraw_info; /*!< Optional info passed by the caller of QueueWithdrawCaller */
1917 struct ast_channel *chan; /*!< Our channel */
1918 AST_LIST_HEAD_NOLOCK(,penalty_rule) qe_rules; /*!< Local copy of the queue's penalty rules */
1919 struct penalty_rule *pr; /*!< Pointer to the next penalty rule to implement */
1920 struct queue_ent *next; /*!< The next queue entry */
1921 };
1922
1923 struct member {
1924 char interface[AST_CHANNEL_NAME]; /*!< Technology/Location to dial to reach this member*/
1925 char state_exten[AST_MAX_EXTENSION]; /*!< Extension to get state from (if using hint) */
1926 char state_context[AST_MAX_CONTEXT]; /*!< Context to use when getting state (if using hint) */
1927 char state_interface[AST_CHANNEL_NAME]; /*!< Technology/Location from which to read devicestate changes */
1928 int state_id; /*!< Extension state callback id (if using hint) */
1929 char membername[80]; /*!< Member name to use in queue logs */
1930 int penalty; /*!< Are we a last resort? */
1931 int calls; /*!< Number of calls serviced by this member */
1932 int dynamic; /*!< Are we dynamically added? */
1933 int realtime; /*!< Is this member realtime? */
1934 int status; /*!< Status of queue member */
1935 int paused; /*!< Are we paused (not accepting calls)? */
1936 char reason_paused[80]; /*!< Reason of paused if member is paused */
1937 int queuepos; /*!< In what order (pertains to certain strategies) should this member be called? */
1938 int callcompletedinsl; /*!< Whether the current call was completed within service level */
1939 int wrapuptime; /*!< Wrapup Time */
1940 time_t starttime; /*!< The time at which the member answered the current caller. */
1941 time_t lastcall; /*!< When last successful call was hungup */
1942 time_t lastpause; /*!< When started the last pause */
1943 time_t logintime; /*!< The time when started the login */
1944 struct call_queue *lastqueue; /*!< Last queue we received a call */
1945 unsigned int dead:1; /*!< Used to detect members deleted in realtime */
1946 unsigned int delme:1; /*!< Flag to delete entry on reload */
1947 char rt_uniqueid[80]; /*!< Unique id of realtime member entry */
1948 unsigned int ringinuse:1; /*!< Flag to ring queue members even if their status is 'inuse' */
1949 };
1950
1951 enum empty_conditions {
1952 QUEUE_EMPTY_PENALTY = (1 << 0),
1953 QUEUE_EMPTY_PAUSED = (1 << 1),
1954 QUEUE_EMPTY_INUSE = (1 << 2),
1955 QUEUE_EMPTY_RINGING = (1 << 3),
1956 QUEUE_EMPTY_UNAVAILABLE = (1 << 4),
1957 QUEUE_EMPTY_INVALID = (1 << 5),
1958 QUEUE_EMPTY_UNKNOWN = (1 << 6),
1959 QUEUE_EMPTY_WRAPUP = (1 << 7),
1960 };
1961
1962 enum member_properties {
1963 MEMBER_PENALTY = 0,
1964 MEMBER_RINGINUSE = 1,
1965 };
1966
1967 /* values used in multi-bit flags in call_queue */
1968 #define ANNOUNCEHOLDTIME_ALWAYS 1
1969 #define ANNOUNCEHOLDTIME_ONCE 2
1970 #define QUEUE_EVENT_VARIABLES 3
1971
1972 struct penalty_rule {
1973 int time; /*!< Number of seconds that need to pass before applying this rule */
1974 int max_value; /*!< The amount specified in the penalty rule for max penalty */
1975 int min_value; /*!< The amount specified in the penalty rule for min penalty */
1976 int raise_value; /*!< The amount specified in the penalty rule for min penalty */
1977 int max_relative; /*!< Is the max adjustment relative? 1 for relative, 0 for absolute */
1978 int min_relative; /*!< Is the min adjustment relative? 1 for relative, 0 for absolute */
1979 int raise_relative; /*!< Is the min adjustment relative? 1 for relative, 0 for absolute */
1980 int raise_respect_min; /*!< A switch raise_penalty should respect min_penalty not just max_penalty */
1981 AST_LIST_ENTRY(penalty_rule) list; /*!< Next penalty_rule */
1982 };
1983
1984 #define ANNOUNCEPOSITION_YES 1 /*!< We announce position */
1985 #define ANNOUNCEPOSITION_NO 2 /*!< We don't announce position */
1986 #define ANNOUNCEPOSITION_MORE_THAN 3 /*!< We say "Currently there are more than <limit>" */
1987 #define ANNOUNCEPOSITION_LIMIT 4 /*!< We not announce position more than \<limit\> */
1988
1989 #define FORCELONGESTWAITINGCALLER_NO 0
1990 #define FORCELONGESTWAITINGCALLER_YES 1
1991 #define FORCELONGESTWAITINGCALLER_PRIO 2 /*!< Account for call priorities when forcing longest waiting caller */
1992
1993 struct call_queue {
1994 AST_DECLARE_STRING_FIELDS(
1995 /*! Queue name */
1996 AST_STRING_FIELD(name);
1997 /*! Music on Hold class */
1998 AST_STRING_FIELD(moh);
1999 /*! Announcement to play when call is answered */
2000 AST_STRING_FIELD(announce);
2001 /*! Exit context */
2002 AST_STRING_FIELD(context);
2003 /*! Gosub to run upon member connection */
2004 AST_STRING_FIELD(membergosub);
2005 /*! Default rule to use if none specified in call to Queue() */
2006 AST_STRING_FIELD(defaultrule);
2007 /*! Sound file: "Your call is now first in line" (def. queue-youarenext) */
2008 AST_STRING_FIELD(sound_next);
2009 /*! Sound file: "There are currently" (def. queue-thereare) */
2010 AST_STRING_FIELD(sound_thereare);
2011 /*! Sound file: "calls waiting to speak to a representative." (def. queue-callswaiting) */
2012 AST_STRING_FIELD(sound_calls);
2013 /*! Sound file: "Currently there are more than" (def. queue-quantity1) */
2014 AST_STRING_FIELD(queue_quantity1);
2015 /*! Sound file: "callers waiting to speak with a representative" (def. queue-quantity2) */
2016 AST_STRING_FIELD(queue_quantity2);
2017 /*! Sound file: "The current estimated total holdtime is" (def. queue-holdtime) */
2018 AST_STRING_FIELD(sound_holdtime);
2019 /*! Sound file: "minutes." (def. queue-minutes) */
2020 AST_STRING_FIELD(sound_minutes);
2021 /*! Sound file: "minute." (def. queue-minute) */
2022 AST_STRING_FIELD(sound_minute);
2023 /*! Sound file: "seconds." (def. queue-seconds) */
2024 AST_STRING_FIELD(sound_seconds);
2025 /*! Sound file: "Thank you for your patience." (def. queue-thankyou) */
2026 AST_STRING_FIELD(sound_thanks);
2027 /*! Sound file: Custom announce for caller, no default */
2028 AST_STRING_FIELD(sound_callerannounce);
2029 /*! Sound file: "Hold time" (def. queue-reporthold) */
2030 AST_STRING_FIELD(sound_reporthold);
2031 );
2032 /*! Sound files: Custom announce, no default */
2033 struct ast_str *sound_periodicannounce[MAX_PERIODIC_ANNOUNCEMENTS];
2034 unsigned int dead:1;
2035 unsigned int ringinuse:1;
2036 unsigned int announce_to_first_user:1; /*!< Whether or not we announce to the first user in a queue */
2037 unsigned int setinterfacevar:1;
2038 unsigned int setqueuevar:1;
2039 unsigned int setqueueentryvar:1;
2040 unsigned int reportholdtime:1;
2041 unsigned int wrapped:1;
2042 unsigned int timeoutrestart:1;
2043 unsigned int announceholdtime:2;
2044 unsigned int announceposition:3;
2045 unsigned int announceposition_only_up:1; /*!< Only announce position if it has improved */
2046 int strategy:4;
2047 unsigned int realtime:1;
2048 unsigned int found:1;
2049 unsigned int relativeperiodicannounce:1;
2050 unsigned int autopausebusy:1;
2051 unsigned int autopauseunavail:1;
2052 enum empty_conditions joinempty;
2053 enum empty_conditions leavewhenempty;
2054 int announcepositionlimit; /*!< How many positions we announce? */
2055 int announcefrequency; /*!< How often to announce their position */
2056 int minannouncefrequency; /*!< The minimum number of seconds between position announcements (def. 15) */
2057 int periodicannouncestartdelay; /*!< How long into the queue should the periodic accouncement start */
2058 int periodicannouncefrequency; /*!< How often to play periodic announcement */
2059 int numperiodicannounce; /*!< The number of periodic announcements configured */
2060 int randomperiodicannounce; /*!< Are periodic announcements randomly chosen */
2061 int roundingseconds; /*!< How many seconds do we round to? */
2062 int holdtime; /*!< Current avg holdtime, based on an exponential average */
2063 int talktime; /*!< Current avg talktime, based on the same exponential average */
2064 int callscompleted; /*!< Number of queue calls completed */
2065 int callsabandoned; /*!< Number of queue calls abandoned */
2066 int callsabandonedinsl; /*!< Number of queue calls abandoned in servicelevel */
2067 int servicelevel; /*!< seconds setting for servicelevel*/
2068 int callscompletedinsl; /*!< Number of calls answered with servicelevel*/
2069 char monfmt[8]; /*!< Format to use when recording calls */
2070 int count; /*!< How many entries */
2071 int maxlen; /*!< Max number of entries */
2072 int wrapuptime; /*!< Wrapup Time */
2073 int penaltymemberslimit; /*!< Disregard penalty when queue has fewer than this many members */
2074
2075 int retry; /*!< Retry calling everyone after this amount of time */
2076 int timeout; /*!< How long to wait for an answer */
2077 int weight; /*!< Respective weight */
2078 int autopause; /*!< Auto pause queue members if they fail to answer */
2079 int autopausedelay; /*!< Delay auto pause for autopausedelay seconds since last call */
2080 int timeoutpriority; /*!< Do we allow a fraction of the timeout to occur for a ring? */
2081
2082 /* Queue strategy things */
2083 int rrpos; /*!< Round Robin - position */
2084 int memberdelay; /*!< Seconds to delay connecting member to caller */
2085 int autofill; /*!< Ignore the head call status and ring an available agent */
2086
2087 int log_restricted_caller_id:1; /*!< Whether log Restricted Caller ID */
2088
2089 struct ao2_container *members; /*!< Head of the list of members */
2090 struct queue_ent *head; /*!< Head of the list of callers */
2091 AST_LIST_ENTRY(call_queue) list; /*!< Next call queue */
2092 AST_LIST_HEAD_NOLOCK(, penalty_rule) rules; /*!< The list of penalty rules to invoke */
2093 };
2094
2095 struct rule_list {
2096 char name[80];
2097 AST_LIST_HEAD_NOLOCK(,penalty_rule) rules;
2098 AST_LIST_ENTRY(rule_list) list;
2099 };
2100
2101 static AST_LIST_HEAD_STATIC(rule_lists, rule_list);
2102
2103 static struct ao2_container *queues;
2104
2105 static void update_realtime_members(struct call_queue *q);
2106 static struct member *interface_exists(struct call_queue *q, const char *interface);
2107 static int set_member_paused(const char *queuename, const char *interface, const char *reason, int paused);
2108 static int update_queue(struct call_queue *q, struct member *member, int callcompletedinsl, time_t starttime);
2109
2110 static struct member *find_member_by_queuename_and_interface(const char *queuename, const char *interface);
2111 /*! \brief sets the QUEUESTATUS channel variable */
2112 static void set_queue_result(struct ast_channel *chan, enum queue_result res)
2113 {
2114 int i;
2115
2116 for (i = 0; i < ARRAY_LEN(queue_results); i++) {
2117 if (queue_results[i].id == res) {
2118 pbx_builtin_setvar_helper(chan, "QUEUESTATUS", queue_results[i].text);
2119 return;
2120 }
2121 }
2122 }
2123
2124 static const char *int2strat(int strategy)
2125 {
2126 int x;
2127
2128 for (x = 0; x < ARRAY_LEN(strategies); x++) {
2129 if (strategy == strategies[x].strategy) {
2130 return strategies[x].name;
2131 }
2132 }
2133
2134 return "<unknown>";
2135 }
2136
2137 static int strat2int(const char *strategy)
2138 {
2139 int x;
2140
2141 for (x = 0; x < ARRAY_LEN(strategies); x++) {
2142 if (!strcasecmp(strategy, strategies[x].name)) {
2143 return strategies[x].strategy;
2144 }
2145 }
2146
2147 return -1;
2148 }
2149
2150 static int autopause2int(const char *autopause)
2151 {
2152 int x;
2153 /*This 'double check' that default value is OFF */
2154 if (ast_strlen_zero(autopause)) {
2155 return QUEUE_AUTOPAUSE_OFF;
2156 }
2157
2158 /*This 'double check' is to ensure old values works */
2159 if(ast_true(autopause)) {
2160 return QUEUE_AUTOPAUSE_ON;
2161 }
2162
2163 for (x = 0; x < ARRAY_LEN(autopausesmodes); x++) {
2164 if (!strcasecmp(autopause, autopausesmodes[x].name)) {
2165 return autopausesmodes[x].autopause;
2166 }
2167 }
2168
2169 /*This 'double check' that default value is OFF */
2170 return QUEUE_AUTOPAUSE_OFF;
2171 }
2172
2173 static int queue_hash_cb(const void *obj, const int flags)
2174 {
2175 const struct call_queue *q = obj;
2176
2177 return ast_str_case_hash(q->name);
2178 }
2179
2180 static int queue_cmp_cb(void *obj, void *arg, int flags)
2181 {
2182 struct call_queue *q = obj, *q2 = arg;
2183 return !strcasecmp(q->name, q2->name) ? CMP_MATCH | CMP_STOP : 0;
2184 }
2185
2186 /*!
2187 * \brief Return wrapuptime
2188 *
2189 * This function checks if wrapuptime in member is set and return this value.
2190 * Otherwise return value the wrapuptime in the queue configuration
2191 * \return integer value
2192 */
2193 static int get_wrapuptime(struct call_queue *q, struct member *member)
2194 {
2195 if (member->wrapuptime) {
2196 return member->wrapuptime;
2197 }
2198 return q->wrapuptime;
2199 }
2200
2201 /*! \internal
2202 * \brief ao2_callback, Decreases queuepos of all followers with a queuepos greater than arg.
2203 * \param obj the member being acted on
2204 * \param arg pointer to an integer containing the position value that was removed and requires reduction for anything above
2205 * \param flag unused
2206 */
2207 static int queue_member_decrement_followers(void *obj, void *arg, int flag)
2208 {
2209 struct member *mem = obj;
2210 int *decrement_followers_after = arg;
2211
2212 if (mem->queuepos > *decrement_followers_after) {
2213 mem->queuepos--;
2214 }
2215
2216 return 0;
2217 }
2218
2219 /*! \internal
2220 * \brief ao2_callback, finds members in a queue marked for deletion and in a cascading fashion runs queue_member_decrement_followers
2221 * on them. This callback should always be ran before performing mass unlinking of delmarked members from queues.
2222 * \param obj member being acted on
2223 * \param arg pointer to the queue members are being removed from
2224 * \param flag unused
2225 */
2226 static int queue_delme_members_decrement_followers(void *obj, void *arg, int flag)
2227 {
2228 struct member *mem = obj;
2229 struct call_queue *queue = arg;
2230 int rrpos = mem->queuepos;
2231
2232 if (mem->delme) {
2233 ao2_callback(queue->members, OBJ_NODATA | OBJ_MULTIPLE, queue_member_decrement_followers, &rrpos);
2234 }
2235
2236 return 0;
2237 }
2238
2239 /*! \internal
2240 * \brief Use this to decrement followers during removal of a member
2241 * \param queue which queue the member is being removed from
2242 * \param mem which member is being removed from the queue
2243 */
2244 static void queue_member_follower_removal(struct call_queue *queue, struct member *mem)
2245 {
2246 int pos = mem->queuepos;
2247
2248 /* 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
2249 * who would have been next otherwise. */
2250 if (pos < queue->rrpos) {
2251 queue->rrpos--;
2252 }
2253
2254 ao2_callback(queue->members, OBJ_NODATA | OBJ_MULTIPLE, queue_member_decrement_followers, &pos);
2255 }
2256
2257 #define queue_ref(q) ao2_bump(q)
2258 #define queue_unref(q) ({ ao2_cleanup(q); NULL; })
2259 #define queue_t_ref(q, tag) ao2_t_bump(q, tag)
2260 #define queue_t_unref(q, tag) ({ ao2_t_cleanup(q, tag); NULL; })
2261 #define queues_t_link(c, q, tag) ao2_t_link(c, q, tag)
2262 #define queues_t_unlink(c, q, tag) ao2_t_unlink(c, q, tag)
2263
2264 /*! \brief Set variables of queue */
2265 static void set_queue_variables(struct call_queue *q, struct ast_channel *chan)
2266 {
2267 char interfacevar[256]="";
2268 float sl = 0;
2269
2270 ao2_lock(q);
2271
2272 if (q->setqueuevar) {
2273 sl = 0;
2274 if (q->callscompleted > 0) {
2275 sl = 100 * ((float) q->callscompletedinsl / (float) q->callscompleted);
2276 }
2277
2278 snprintf(interfacevar, sizeof(interfacevar),
2279 "QUEUENAME=%s,QUEUEMAX=%d,QUEUESTRATEGY=%s,QUEUECALLS=%d,QUEUEHOLDTIME=%d,QUEUETALKTIME=%d,QUEUECOMPLETED=%d,QUEUEABANDONED=%d,QUEUESRVLEVEL=%d,QUEUESRVLEVELPERF=%2.1f",
2280 q->name, q->maxlen, int2strat(q->strategy), q->count, q->holdtime, q->talktime, q->callscompleted, q->callsabandoned, q->servicelevel, sl);
2281
2282 ao2_unlock(q);
2283
2284 pbx_builtin_setvar_multiple(chan, interfacevar);
2285 } else {
2286 ao2_unlock(q);
2287 }
2288 }
2289
2290 /*! \brief Insert the 'new' entry after the 'prev' entry of queue 'q' */
2291 static inline void insert_entry(struct call_queue *q, struct queue_ent *prev, struct queue_ent *new, int *pos)
2292 {
2293 struct queue_ent *cur;
2294
2295 if (!q || !new)
2296 return;
2297 if (prev) {
2298 cur = prev->next;
2299 prev->next = new;
2300 } else {
2301 cur = q->head;
2302 q->head = new;
2303 }
2304 new->next = cur;
2305
2306 /* every queue_ent must have a reference to it's parent call_queue, this
2307 * reference does not go away until the end of the queue_ent's life, meaning
2308 * that even when the queue_ent leaves the call_queue this ref must remain. */
2309 if (!new->parent) {
2310 queue_ref(q);
2311 new->parent = q;
2312 }
2313 new->pos = ++(*pos);
2314 new->opos = *pos;
2315 }
2316
2317 static struct ast_manager_event_blob *queue_channel_to_ami(const char *type, struct stasis_message *message)
2318 {
2319 struct ast_channel_blob *obj = stasis_message_data(message);
2320 RAII_VAR(struct ast_str *, channel_string, NULL, ast_free);
2321 RAII_VAR(struct ast_str *, event_string, NULL, ast_free);
2322
2323 channel_string = ast_manager_build_channel_state_string(obj->snapshot);
2324 event_string = ast_manager_str_from_json_object(obj->blob, NULL);
2325 if (!channel_string || !event_string) {
2326 return NULL;
2327 }
2328
2329 return ast_manager_event_blob_create(EVENT_FLAG_AGENT, type,
2330 "%s"
2331 "%s",
2332 ast_str_buffer(channel_string),
2333 ast_str_buffer(event_string));
2334 }
2335
2336 static struct ast_manager_event_blob *queue_caller_join_to_ami(struct stasis_message *message)
2337 {
2338 return queue_channel_to_ami("QueueCallerJoin", message);
2339 }
2340
2341 static struct ast_manager_event_blob *queue_caller_leave_to_ami(struct stasis_message *message)
2342 {
2343 return queue_channel_to_ami("QueueCallerLeave", message);
2344 }
2345
2346 static struct ast_manager_event_blob *queue_caller_abandon_to_ami(struct stasis_message *message)
2347 {
2348 return queue_channel_to_ami("QueueCallerAbandon", message);
2349 }
2350
2351 STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_caller_join_type,
2352 .to_ami = queue_caller_join_to_ami,
2353 );
2354 STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_caller_leave_type,
2355 .to_ami = queue_caller_leave_to_ami,
2356 );
2357 STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_caller_abandon_type,
2358 .to_ami = queue_caller_abandon_to_ami,
2359 );
2360
2361 static struct ast_manager_event_blob *queue_member_to_ami(const char *type, struct stasis_message *message)
2362 {
2363 struct ast_json_payload *payload = stasis_message_data(message);
2364 RAII_VAR(struct ast_str *, event_string, NULL, ast_free);
2365
2366 event_string = ast_manager_str_from_json_object(payload->json, NULL);
2367 if (!event_string) {
2368 return NULL;
2369 }
2370
2371 return ast_manager_event_blob_create(EVENT_FLAG_AGENT, type,
2372 "%s",
2373 ast_str_buffer(event_string));
2374 }
2375
2376 static struct ast_manager_event_blob *queue_member_status_to_ami(struct stasis_message *message)
2377 {
2378 return queue_member_to_ami("QueueMemberStatus", message);
2379 }
2380
2381 static struct ast_manager_event_blob *queue_member_added_to_ami(struct stasis_message *message)
2382 {
2383 return queue_member_to_ami("QueueMemberAdded", message);
2384 }
2385
2386 static struct ast_manager_event_blob *queue_member_removed_to_ami(struct stasis_message *message)
2387 {
2388 return queue_member_to_ami("QueueMemberRemoved", message);
2389 }
2390
2391 static struct ast_manager_event_blob *queue_member_pause_to_ami(struct stasis_message *message)
2392 {
2393 return queue_member_to_ami("QueueMemberPause", message);
2394 }
2395
2396 static struct ast_manager_event_blob *queue_member_penalty_to_ami(struct stasis_message *message)
2397 {
2398 return queue_member_to_ami("QueueMemberPenalty", message);
2399 }
2400
2401 static struct ast_manager_event_blob *queue_member_ringinuse_to_ami(struct stasis_message *message)
2402 {
2403 return queue_member_to_ami("QueueMemberRinginuse", message);
2404 }
2405
2406 STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_member_status_type,
2407 .to_ami = queue_member_status_to_ami,
2408 );
2409 STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_member_added_type,
2410 .to_ami = queue_member_added_to_ami,
2411 );
2412 STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_member_removed_type,
2413 .to_ami = queue_member_removed_to_ami,
2414 );
2415 STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_member_pause_type,
2416 .to_ami = queue_member_pause_to_ami,
2417 );
2418 STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_member_penalty_type,
2419 .to_ami = queue_member_penalty_to_ami,
2420 );
2421 STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_member_ringinuse_type,
2422 .to_ami = queue_member_ringinuse_to_ami,
2423 );
2424
2425 static struct ast_manager_event_blob *queue_multi_channel_to_ami(const char *type, struct stasis_message *message)
2426 {
2427 struct ast_multi_channel_blob *obj = stasis_message_data(message);
2428 struct ast_channel_snapshot *caller;
2429 struct ast_channel_snapshot *agent;
2430 RAII_VAR(struct ast_str *, caller_event_string, NULL, ast_free);
2431 RAII_VAR(struct ast_str *, agent_event_string, NULL, ast_free);
2432 RAII_VAR(struct ast_str *, event_string, NULL, ast_free);
2433
2434 caller = ast_multi_channel_blob_get_channel(obj, "caller");
2435 if (caller) {
2436 caller_event_string = ast_manager_build_channel_state_string(caller);
2437 if (!caller_event_string) {
2438 ast_log(LOG_NOTICE, "No caller event string, bailing\n");
2439 return NULL;
2440 }
2441 }
2442
2443 agent = ast_multi_channel_blob_get_channel(obj, "agent");
2444 if (agent) {
2445 agent_event_string = ast_manager_build_channel_state_string_prefix(agent, "Dest");
2446 if (!agent_event_string) {
2447 ast_log(LOG_NOTICE, "No agent event string, bailing\n");
2448 return NULL;
2449 }
2450 }
2451
2452 event_string = ast_manager_str_from_json_object(ast_multi_channel_blob_get_json(obj), NULL);
2453 if (!event_string) {
2454 return NULL;
2455 }
2456
2457 return ast_manager_event_blob_create(EVENT_FLAG_AGENT, type,
2458 "%s"
2459 "%s"
2460 "%s",
2461 caller_event_string ? ast_str_buffer(caller_event_string) : "",
2462 agent_event_string ? ast_str_buffer(agent_event_string) : "",
2463 ast_str_buffer(event_string));
2464 }
2465
2466 static struct ast_manager_event_blob *queue_agent_called_to_ami(struct stasis_message *message)
2467 {
2468 return queue_multi_channel_to_ami("AgentCalled", message);
2469 }
2470
2471 static struct ast_manager_event_blob *queue_agent_connect_to_ami(struct stasis_message *message)
2472 {
2473 return queue_multi_channel_to_ami("AgentConnect", message);
2474 }
2475
2476 static struct ast_manager_event_blob *queue_agent_complete_to_ami(struct stasis_message *message)
2477 {
2478 return queue_multi_channel_to_ami("AgentComplete", message);
2479 }
2480
2481 static struct ast_manager_event_blob *queue_agent_dump_to_ami(struct stasis_message *message)
2482 {
2483 return queue_multi_channel_to_ami("AgentDump", message);
2484 }
2485
2486 static struct ast_manager_event_blob *queue_agent_ringnoanswer_to_ami(struct stasis_message *message)
2487 {
2488 return queue_multi_channel_to_ami("AgentRingNoAnswer", message);
2489 }
2490
2491 STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_agent_called_type,
2492 .to_ami = queue_agent_called_to_ami,
2493 );
2494 STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_agent_connect_type,
2495 .to_ami = queue_agent_connect_to_ami,
2496 );
2497 STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_agent_complete_type,
2498 .to_ami = queue_agent_complete_to_ami,
2499 );
2500 STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_agent_dump_type,
2501 .to_ami = queue_agent_dump_to_ami,
2502 );
2503 STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_agent_ringnoanswer_type,
2504 .to_ami = queue_agent_ringnoanswer_to_ami,
2505 );
2506
2507 static void queue_publish_multi_channel_snapshot_blob(struct stasis_topic *topic,
2508 struct ast_channel_snapshot *caller_snapshot,
2509 struct ast_channel_snapshot *agent_snapshot,
2510 struct stasis_message_type *type, struct ast_json *blob)
2511 {
2512 RAII_VAR(struct ast_multi_channel_blob *, payload, NULL, ao2_cleanup);
2513 RAII_VAR(struct stasis_message *, msg, NULL, ao2_cleanup);
2514
2515 if (!type) {
2516 return;
2517 }
2518
2519 payload = ast_multi_channel_blob_create(blob);
2520 if (!payload) {
2521 return;
2522 }
2523
2524 if (caller_snapshot) {
2525 ast_multi_channel_blob_add_channel(payload, "caller", caller_snapshot);
2526 } else {
2527 ast_debug(1, "Empty caller_snapshot; sending incomplete event\n");
2528 }
2529
2530 if (agent_snapshot) {
2531 ast_multi_channel_blob_add_channel(payload, "agent", agent_snapshot);
2532 }
2533
2534 msg = stasis_message_create(type, payload);
2535 if (!msg) {
2536 return;
2537 }
2538
2539 stasis_publish(topic, msg);
2540 }
2541
2542 static void queue_publish_multi_channel_blob(struct ast_channel *caller, struct ast_channel *agent,
2543 struct stasis_message_type *type, struct ast_json *blob)
2544 {
2545 RAII_VAR(struct ast_channel_snapshot *, caller_snapshot, NULL, ao2_cleanup);
2546 RAII_VAR(struct ast_channel_snapshot *, agent_snapshot, NULL, ao2_cleanup);
2547
2548 ast_channel_lock(caller);
2549 caller_snapshot = ast_channel_snapshot_create(caller);
2550 ast_channel_unlock(caller);
2551 ast_channel_lock(agent);
2552 agent_snapshot = ast_channel_snapshot_create(agent);
2553 ast_channel_unlock(agent);
2554
2555 if (!caller_snapshot || !agent_snapshot) {
2556 return;
2557 }
2558
2559 queue_publish_multi_channel_snapshot_blob(ast_channel_topic(caller), caller_snapshot,
2560 agent_snapshot, type, blob);
2561 }
2562
2563 /*!
2564 * \internal
2565 * \brief Publish the member blob.
2566 * \since 12.0.0
2567 *
2568 * \param type Stasis message type to publish.
2569 * \param blob The information being published.
2570 *
2571 * \note The json blob reference is passed to this function.
2572 */
2573 static void queue_publish_member_blob(struct stasis_message_type *type, struct ast_json *blob)
2574 {
2575 RAII_VAR(struct ast_json_payload *, payload, NULL, ao2_cleanup);
2576 RAII_VAR(struct stasis_message *, msg, NULL, ao2_cleanup);
2577
2578 if (!blob || !type) {
2579 ast_json_unref(blob);
2580 return;
2581 }
2582
2583 payload = ast_json_payload_create(blob);
2584 ast_json_unref(blob);
2585 if (!payload) {
2586 return;
2587 }
2588
2589 msg = stasis_message_create(type, payload);
2590 if (!msg) {
2591 return;
2592 }
2593
2594 stasis_publish(ast_manager_get_topic(), msg);
2595 }
2596
2597 static struct ast_json *queue_member_blob_create(struct call_queue *q, struct member *mem)
2598 {
2599 return ast_json_pack("{s: s, s: s, s: s, s: s, s: s, s: i, s: i, s: i, s: i, s: i, s: i, s: i, s: i, s: s, s: i, s: i}",
2600 "Queue", q->name,
2601 "MemberName", mem->membername,
2602 "Interface", mem->interface,
2603 "StateInterface", mem->state_interface,
2604 "Membership", (mem->dynamic ? "dynamic" : (mem->realtime ? "realtime" : "static")),
2605 "Penalty", mem->penalty,
2606 "CallsTaken", mem->calls,
2607 "LastCall", (int)mem->lastcall,
2608 "LastPause", (int)mem->lastpause,
2609 "LoginTime", (int)mem->logintime,
2610 "InCall", mem->starttime ? 1 : 0,
2611 "Status", mem->status,
2612 "Paused", mem->paused,
2613 "PausedReason", mem->reason_paused,
2614 "Ringinuse", mem->ringinuse,
2615 "Wrapuptime", mem->wrapuptime);
2616 }
2617
2618 /*! \brief Check if members are available
2619 *
2620 * This function checks to see if members are available to be called. If any member
2621 * is available, the function immediately returns 0. If no members are available,
2622 * then -1 is returned.
2623 */
2624 static int get_member_status(struct call_queue *q, int max_penalty, int min_penalty, int raise_penalty, enum empty_conditions conditions, int devstate, int raise_respect_min)
2625 {
2626 struct member *member;
2627 struct ao2_iterator mem_iter;
2628
2629 ao2_lock(q);
2630 mem_iter = ao2_iterator_init(q->members, 0);
2631 for (; (member = ao2_iterator_next(&mem_iter)); ao2_ref(member, -1)) {
2632 int penalty = member->penalty;
2633 if (raise_penalty != INT_MAX && penalty < raise_penalty) {
2634 /* Check if we should respect minimum penalty threshold */
2635 if (raise_respect_min && penalty < min_penalty) {
2636 ast_debug(4, "%s penalty %d not raised (below min %d)\n", member->membername, penalty, min_penalty);
2637 } else {
2638 ast_debug(4, "%s is having his penalty raised up from %d to %d\n", member->membername, penalty, raise_penalty);
2639 penalty = raise_penalty;
2640 }
2641 }
2642 if ((max_penalty != INT_MAX && penalty > max_penalty) || (min_penalty != INT_MAX && penalty < min_penalty)) {
2643 if (conditions & QUEUE_EMPTY_PENALTY) {
2644 ast_debug(4, "%s is unavailable because his penalty is not between %d and %d\n", member->membername, min_penalty, max_penalty);
2645 continue;
2646 }
2647 }
2648
2649 switch (devstate ? ast_device_state(member->state_interface) : member->status) {
2650 case AST_DEVICE_INVALID:
2651 if (conditions & QUEUE_EMPTY_INVALID) {
2652 ast_debug(4, "%s is unavailable because his device state is 'invalid'\n", member->membername);
2653 break;
2654 }
2655 goto default_case;
2656 case AST_DEVICE_UNAVAILABLE:
2657 if (conditions & QUEUE_EMPTY_UNAVAILABLE) {
2658 ast_debug(4, "%s is unavailable because his device state is 'unavailable'\n", member->membername);
2659 break;
2660 }
2661 goto default_case;
2662 case AST_DEVICE_INUSE:
2663 if (conditions & QUEUE_EMPTY_INUSE) {
2664 ast_debug(4, "%s is unavailable because his device state is 'inuse'\n", member->membername);
2665 break;
2666 }
2667 goto default_case;
2668 case AST_DEVICE_RINGING:
2669 if (conditions & QUEUE_EMPTY_RINGING) {
2670 ast_debug(4, "%s is unavailable because his device state is 'ringing'\n", member->membername);
2671 break;
2672 }
2673 goto default_case;
2674 case AST_DEVICE_UNKNOWN:
2675 if (conditions & QUEUE_EMPTY_UNKNOWN) {
2676 ast_debug(4, "%s is unavailable because his device state is 'unknown'\n", member->membername);
2677 break;
2678 }
2679 /* Fall-through */
2680 default:
2681 default_case:
2682 if (member->paused && (conditions & QUEUE_EMPTY_PAUSED)) {
2683 ast_debug(4, "%s is unavailable because he is paused'\n", member->membername);
2684 break;
2685 } else if ((conditions & QUEUE_EMPTY_WRAPUP)
2686 && member->lastcall
2687 && get_wrapuptime(q, member)
2688 && (time(NULL) - get_wrapuptime(q, member) < member->lastcall)) {
2689 ast_debug(4, "%s is unavailable because it has only been %d seconds since his last call (wrapup time is %d)\n",
2690 member->membername, (int) (time(NULL) - member->lastcall), get_wrapuptime(q, member));
2691 break;
2692 } else {
2693 ao2_ref(member, -1);
2694 ao2_iterator_destroy(&mem_iter);
2695 ao2_unlock(q);
2696 ast_debug(4, "%s is available.\n", member->membername);
2697 return 0;
2698 }
2699 break;
2700 }
2701 }
2702 ao2_iterator_destroy(&mem_iter);
2703 ao2_unlock(q);
2704
2705 if (!devstate && (conditions & QUEUE_EMPTY_RINGING)) {
2706 /* member state still may be RINGING due to lag in event message - check again with device state */
2707 return get_member_status(q, max_penalty, min_penalty, raise_penalty, conditions, 1, raise_respect_min);
2708 }
2709 return -1;
2710 }
2711
2712 /*
2713 * A "pool" of member objects that calls are currently pending on. If an
2714 * agent is a member of multiple queues it's possible for that agent to be
2715 * called by each of the queues at the same time. This happens because device
2716 * state is slow to notify the queue app of one of it's member's being rung.
2717 * This "pool" allows us to track which members are currently being rung while
2718 * we wait on the device state change.
2719 */
2720 static struct ao2_container *pending_members;
2721 #define MAX_CALL_ATTEMPT_BUCKETS 353
2722
2723 static int pending_members_hash(const void *obj, const int flags)
2724 {
2725 const struct member *object;
2726 const char *key;
2727
2728 switch (flags & OBJ_SEARCH_MASK) {
2729 case OBJ_SEARCH_KEY:
2730 key = obj;
2731 break;
2732 case OBJ_SEARCH_OBJECT:
2733 object = obj;
2734 key = object->interface;
2735 break;
2736 default:
2737 ast_assert(0);
2738 return 0;
2739 }
2740 return ast_str_case_hash(key);
2741 }
2742
2743 static int pending_members_cmp(void *obj, void *arg, int flags)
2744 {
2745 const struct member *object_left = obj;
2746 const struct member *object_right = arg;
2747 const char *right_key = arg;
2748 int cmp;
2749
2750 switch (flags & OBJ_SEARCH_MASK) {
2751 case OBJ_SEARCH_OBJECT:
2752 right_key = object_right->interface;
2753 /* Fall through */
2754 case OBJ_SEARCH_KEY:
2755 cmp = strcasecmp(object_left->interface, right_key);
2756 break;
2757 case OBJ_SEARCH_PARTIAL_KEY:
2758 /* Not supported by container. */
2759 ast_assert(0);
2760 return 0;
2761 default:
2762 cmp = 0;
2763 break;
2764 }
2765 if (cmp) {
2766 return 0;
2767 }
2768 return CMP_MATCH;
2769 }
2770
2771 static void pending_members_remove(struct member *mem)
2772 {
2773 ast_debug(3, "Removed %s from pending_members\n", mem->membername);
2774 ao2_find(pending_members, mem, OBJ_POINTER | OBJ_NODATA | OBJ_UNLINK);
2775 }
2776
2777 /*! \brief set a member's status based on device state of that member's state_interface.
2778 *
2779 * Lock interface list find sc, iterate through each queues queue_member list for member to
2780 * update state inside queues
2781 */
2782 static void update_status(struct call_queue *q, struct member *m, const int status)
2783 {
2784 if (m->status != status) {
2785 /* If this member has transitioned to being available then update their queue
2786 * information. If they are currently in a call then the leg to the agent will be
2787 * considered done and the call finished.
2788 */
2789 if (status == AST_DEVICE_NOT_INUSE) {
2790 update_queue(q, m, m->callcompletedinsl, m->starttime);
2791 }
2792
2793 m->status = status;
2794
2795 /* Remove the member from the pending members pool only when the status changes.
2796 * This is not done unconditionally because we can occasionally see multiple
2797 * device state notifications of not in use after a previous call has ended,
2798 * including after we have initiated a new call. This is more likely to
2799 * happen when there is latency in the connection to the member.
2800 */
2801 pending_members_remove(m);
2802
2803 queue_publish_member_blob(queue_member_status_type(), queue_member_blob_create(q, m));
2804 }
2805 }
2806
2807 /*!
2808 * \internal
2809 * \brief Determine if a queue member is available
2810 * \retval 1 if the member is available
2811 * \retval 0 if the member is not available
2812 */
2813 static int is_member_available(struct call_queue *q, struct member *mem)
2814 {
2815 int available = 0;
2816 int wrapuptime;
2817
2818 switch (mem->status) {
2819 case AST_DEVICE_INVALID:
2820 case AST_DEVICE_UNAVAILABLE:
2821 break;
2822 case AST_DEVICE_INUSE:
2823 case AST_DEVICE_BUSY:
2824 case AST_DEVICE_RINGING:
2825 case AST_DEVICE_RINGINUSE:
2826 case AST_DEVICE_ONHOLD:
2827 if (!mem->ringinuse) {
2828 break;
2829 }
2830 /* else fall through */
2831 case AST_DEVICE_NOT_INUSE:
2832 case AST_DEVICE_UNKNOWN:
2833 if (!mem->paused) {
2834 available = 1;
2835 }
2836 break;
2837 }
2838
2839 /* Let wrapuptimes override device state availability */
2840 wrapuptime = get_wrapuptime(q, mem);
2841 if (mem->lastcall && wrapuptime && (time(NULL) - wrapuptime < mem->lastcall)) {
2842 available = 0;
2843 }
2844 return available;
2845 }
2846
2847 /*! \brief set a member's status based on device state of that member's interface*/
2848 static void device_state_cb(void *unused, struct stasis_subscription *sub, struct stasis_message *msg)
2849 {
2850 struct ao2_iterator miter, qiter;
2851 struct ast_device_state_message *dev_state;
2852 struct member *m;
2853 struct call_queue *q;
2854 char interface[80], *slash_pos;
2855 int found = 0; /* Found this member in any queue */
2856 int found_member; /* Found this member in this queue */
2857 int avail = 0; /* Found an available member in this queue */
2858
2859 if (ast_device_state_message_type() != stasis_message_type(msg)) {
2860 return;
2861 }
2862
2863 dev_state = stasis_message_data(msg);
2864 if (dev_state->eid) {
2865 /* ignore non-aggregate states */
2866 return;
2867 }
2868
2869 qiter = ao2_iterator_init(queues, 0);
2870 while ((q = ao2_t_iterator_next(&qiter, "Iterate over queues"))) {
2871 ao2_lock(q);
2872
2873 avail = 0;
2874 found_member = 0;
2875 miter = ao2_iterator_init(q->members, 0);
2876 for (; (m = ao2_iterator_next(&miter)); ao2_ref(m, -1)) {
2877 if (!found_member) {
2878 ast_copy_string(interface, m->state_interface, sizeof(interface));
2879
2880 if ((slash_pos = strchr(interface, '/'))) {
2881 if (!strncasecmp(interface, "Local/", 6) && (slash_pos = strchr(slash_pos + 1, '/'))) {
2882 *slash_pos = '\0';
2883 }
2884 }
2885
2886 if (!strcasecmp(interface, dev_state->device)) {
2887 found_member = 1;
2888 update_status(q, m, dev_state->state);
2889 }
2890 }
2891
2892 /* check every member until we find one NOT_INUSE */
2893 if (!avail) {
2894 avail = is_member_available(q, m);
2895 }
2896 if (avail && found_member) {
2897 /* early exit as we've found an available member and the member of interest */
2898 ao2_ref(m, -1);
2899 break;
2900 }
2901 }
2902
2903 if (found_member) {
2904 found = 1;
2905 if (avail) {
2906 ast_devstate_changed(AST_DEVICE_NOT_INUSE, AST_DEVSTATE_CACHABLE, "Queue:%s_avail", q->name);
2907 } else {
2908 ast_devstate_changed(AST_DEVICE_INUSE, AST_DEVSTATE_CACHABLE, "Queue:%s_avail", q->name);
2909 }
2910 }
2911
2912 ao2_iterator_destroy(&miter);
2913
2914 ao2_unlock(q);
2915 queue_t_unref(q, "Done with iterator");
2916 }
2917 ao2_iterator_destroy(&qiter);
2918
2919 if (found) {
2920 ast_debug(1, "Device '%s' changed to state '%u' (%s)\n",
2921 dev_state->device,
2922 dev_state->state,
2923 ast_devstate2str(dev_state->state));
2924 } else {
2925 ast_debug(3, "Device '%s' changed to state '%u' (%s) but we don't care because they're not a member of any queue.\n",
2926 dev_state->device,
2927 dev_state->state,
2928 ast_devstate2str(dev_state->state));
2929 }
2930
2931 return;
2932 }
2933
2934 /*! \brief Helper function which converts from extension state to device state values */
2935 static int extensionstate2devicestate(int state)
2936 {
2937 switch (state) {
2938 case AST_EXTENSION_NOT_INUSE:
2939 state = AST_DEVICE_NOT_INUSE;
2940 break;
2941 case AST_EXTENSION_INUSE:
2942 state = AST_DEVICE_INUSE;
2943 break;
2944 case AST_EXTENSION_BUSY:
2945 state = AST_DEVICE_BUSY;
2946 break;
2947 case AST_EXTENSION_RINGING:
2948 state = AST_DEVICE_RINGING;
2949 break;
2950 case AST_EXTENSION_INUSE | AST_EXTENSION_RINGING:
2951 state = AST_DEVICE_RINGINUSE;
2952 break;
2953 case AST_EXTENSION_ONHOLD:
2954 state = AST_DEVICE_ONHOLD;
2955 break;
2956 case AST_EXTENSION_INUSE | AST_EXTENSION_ONHOLD:
2957 state = AST_DEVICE_INUSE;
2958 break;
2959 case AST_EXTENSION_UNAVAILABLE:
2960 state = AST_DEVICE_UNAVAILABLE;
2961 break;
2962 case AST_EXTENSION_REMOVED:
2963 case AST_EXTENSION_DEACTIVATED:
2964 default:
2965 state = AST_DEVICE_INVALID;
2966 break;
2967 }
2968
2969 return state;
2970 }
2971
2972 /*!
2973 * \brief Returns if one context includes another context
2974 *
2975 * \param parent Parent context to search for child
2976 * \param child Context to check for inclusion in parent
2977 *
2978 * This function recursively checks if the context child is included in the context parent.
2979 *
2980 * \retval 1 if child is included in parent
2981 * \retval 0 if not
2982 */
2983 static int context_included(const char *parent, const char *child);
2984 static int context_included(const char *parent, const char *child)
2985 {
2986 struct ast_context *c = NULL;
2987
2988 c = ast_context_find(parent);
2989 if (!c) {
2990 /* well, if parent doesn't exist, how can the child be included in it? */
2991 return 0;
2992 }
2993 if (!strcmp(ast_get_context_name(c), parent)) {
2994 /* found the context of the hint app_queue is using. Now, see
2995 if that context includes the one that just changed state */
2996 struct ast_include *inc = NULL;
2997
2998 while ((inc = (struct ast_include*) ast_walk_context_includes(c, inc))) {
2999 const char *includename = ast_get_include_name(inc);
3000 if (!strcasecmp(child, includename)) {
3001 return 1;
3002 }
3003 /* recurse on this context, for nested includes. The
3004 PBX extension parser will prevent infinite recursion. */
3005 if (context_included(includename, child)) {
3006 return 1;
3007 }
3008 }
3009 }
3010 return 0;
3011 }
3012
3013 static int extension_state_cb(const char *context, const char *exten, struct ast_state_cb_info *info, void *data)
3014 {
3015 struct ao2_iterator miter, qiter;
3016 struct member *m;
3017 struct call_queue *q;
3018 int state = info->exten_state;
3019 int found = 0, device_state = extensionstate2devicestate(state);
3020
3021 /* only interested in extension state updates involving device states */
3022 if (info->reason != AST_HINT_UPDATE_DEVICE) {
3023 return 0;
3024 }
3025
3026 qiter = ao2_iterator_init(queues, 0);
3027 while ((q = ao2_t_iterator_next(&qiter, "Iterate through queues"))) {
3028 ao2_lock(q);
3029
3030 miter = ao2_iterator_init(q->members, 0);
3031 for (; (m = ao2_iterator_next(&miter)); ao2_ref(m, -1)) {
3032 if (!strcmp(m->state_exten, exten) &&
3033 (!strcmp(m->state_context, context) || context_included(m->state_context, context))) {
3034 /* context could be included in m->state_context. We need to check. */
3035 found = 1;
3036 update_status(q, m, device_state);
3037 }
3038 }
3039 ao2_iterator_destroy(&miter);
3040
3041 ao2_unlock(q);
3042 queue_t_unref(q, "Done with iterator");
3043 }
3044 ao2_iterator_destroy(&qiter);
3045
3046 if (found) {
3047 ast_debug(1, "Extension '%s@%s' changed to state '%d' (%s)\n", exten, context, device_state, ast_devstate2str(device_state));
3048 } else {
3049 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",
3050 exten, context, device_state, ast_devstate2str(device_state));
3051 }
3052
3053 return 0;
3054 }
3055
3056 /*! \brief Return the current state of a member */
3057 static int get_queue_member_status(struct member *cur)
3058 {
3059 return ast_strlen_zero(cur->state_exten) ? ast_device_state(cur->state_interface) : extensionstate2devicestate(ast_extension_state(NULL, cur->state_context, cur->state_exten));
3060 }
3061
3062 static void destroy_queue_member_cb(void *obj)
3063 {
3064 struct member *mem = obj;
3065
3066 if (mem->state_id != -1) {
3067 ast_extension_state_del(mem->state_id, extension_state_cb);
3068 }
3069 }
3070
3071 /*! \brief allocate space for new queue member and set fields based on parameters passed */
3072 static struct member *create_queue_member(const char *interface, const char *membername, int penalty, int paused, const char *state_interface, int ringinuse, int wrapuptime)
3073 {
3074 struct member *cur;
3075
3076 if ((cur = ao2_alloc(sizeof(*cur), destroy_queue_member_cb))) {
3077 cur->ringinuse = ringinuse;
3078 cur->penalty = penalty;
3079 cur->paused = paused;
3080 cur->wrapuptime = wrapuptime;
3081 if (paused) {
3082 time(&cur->lastpause); /* Update time of last pause */
3083 }
3084 time(&cur->logintime);
3085 ast_copy_string(cur->interface, interface, sizeof(cur->interface));
3086 if (!ast_strlen_zero(state_interface)) {
3087 ast_copy_string(cur->state_interface, state_interface, sizeof(cur->state_interface));
3088 } else {
3089 ast_copy_string(cur->state_interface, interface, sizeof(cur->state_interface));
3090 }
3091 if (!ast_strlen_zero(membername)) {
3092 ast_copy_string(cur->membername, membername, sizeof(cur->membername));
3093 } else {
3094 ast_copy_string(cur->membername, interface, sizeof(cur->membername));
3095 }
3096 if (!strchr(cur->interface, '/')) {
3097 ast_log(LOG_WARNING, "No location at interface '%s'\n", interface);
3098 }
3099 if (!strncmp(cur->state_interface, "hint:", 5)) {
3100 char *tmp = ast_strdupa(cur->state_interface), *context = tmp;
3101 char *exten = strsep(&context, "@") + 5;
3102
3103 ast_copy_string(cur->state_exten, exten, sizeof(cur->state_exten));
3104 ast_copy_string(cur->state_context, S_OR(context, "default"), sizeof(cur->state_context));
3105
3106 cur->state_id = ast_extension_state_add(cur->state_context, cur->state_exten, extension_state_cb, NULL);
3107 } else {
3108 cur->state_id = -1;
3109 }
3110 cur->status = get_queue_member_status(cur);
3111 }
3112
3113 return cur;
3114 }
3115
3116
3117 static int compress_char(const char c)
3118 {
3119 if (c < 32) {
3120 return 0;
3121 } else if (c > 96) {
3122 return c - 64;
3123 }
3124 return c - 32;
3125 }
3126
3127 static int member_hash_fn(const void *obj, const int flags)
3128 {
3129 const struct member *mem = obj;
3130 const char *interface = (flags & OBJ_KEY) ? obj : mem->interface;
3131 const char *chname = strchr(interface, '/');
3132 int ret = 0, i;
3133
3134 if (!chname) {
3135 chname = interface;
3136 }
3137 for (i = 0; i < 5 && chname[i]; i++) {
3138 ret += compress_char(chname[i]) << (i * 6);
3139 }
3140 return ret;
3141 }
3142
3143 static int member_cmp_fn(void *obj1, void *obj2, int flags)
3144 {
3145 struct member *mem1 = obj1;
3146 struct member *mem2 = obj2;
3147 const char *interface = (flags & OBJ_KEY) ? obj2 : mem2->interface;
3148
3149 return strcasecmp(mem1->interface, interface) ? 0 : CMP_MATCH | CMP_STOP;
3150 }
3151
3152 /*!
3153 * \brief Initialize Queue default values.
3154 * \note the queue's lock must be held before executing this function
3155 */
3156 static void init_queue(struct call_queue *q)
3157 {
3158 int i;
3159 struct penalty_rule *pr_iter;
3160
3161 q->dead = 0;
3162 q->retry = DEFAULT_RETRY;
3163 q->timeout = DEFAULT_TIMEOUT;
3164 q->maxlen = 0;
3165
3166 ast_string_field_set(q, announce, "");
3167 ast_string_field_set(q, context, "");
3168 ast_string_field_set(q, membergosub, "");
3169 ast_string_field_set(q, defaultrule, "");
3170
3171 q->announcefrequency = 0;
3172 q->minannouncefrequency = DEFAULT_MIN_ANNOUNCE_FREQUENCY;
3173 q->announceholdtime = 1;
3174 q->announceposition_only_up = 0;
3175 q->announcepositionlimit = 10; /* Default 10 positions */
3176 q->announceposition = ANNOUNCEPOSITION_YES; /* Default yes */
3177 q->roundingseconds = 0; /* Default - don't announce seconds */
3178 q->servicelevel = 0;
3179 q->ringinuse = 1;
3180 q->announce_to_first_user = 0;
3181 q->setinterfacevar = 0;
3182 q->setqueuevar = 0;
3183 q->setqueueentryvar = 0;
3184 q->autofill = autofill_default;
3185 q->monfmt[0] = '\0';
3186 q->reportholdtime = 0;
3187 q->wrapuptime = 0;
3188 q->penaltymemberslimit = 0;
3189 q->joinempty = 0;
3190 q->leavewhenempty = 0;
3191 q->memberdelay = 0;
3192 q->weight = 0;
3193 q->timeoutrestart = 0;
3194 q->periodicannouncefrequency = 0;
3195 q->periodicannouncestartdelay = -1;
3196 q->randomperiodicannounce = 0;
3197 q->numperiodicannounce = 0;
3198 q->relativeperiodicannounce = 0;
3199 q->autopause = QUEUE_AUTOPAUSE_OFF;
3200 q->autopausebusy = 0;
3201 q->autopauseunavail = 0;
3202 q->timeoutpriority = TIMEOUT_PRIORITY_APP;
3203 q->autopausedelay = 0;
3204 q->log_restricted_caller_id = 1;
3205 if (!q->members) {
3206 if (q->strategy == QUEUE_STRATEGY_LINEAR || q->strategy == QUEUE_STRATEGY_RRORDERED) {
3207 /* linear strategy depends on order, so we have to place all members in a list */
3208 q->members = ao2_container_alloc_list(AO2_ALLOC_OPT_LOCK_MUTEX, 0, NULL, member_cmp_fn);
3209 } else {
3210 q->members = ao2_container_alloc_hash(AO2_ALLOC_OPT_LOCK_MUTEX, 0, 37,
3211 member_hash_fn, NULL, member_cmp_fn);
3212 }
3213 }
3214 q->found = 1;
3215
3216 ast_string_field_set(q, moh, "");
3217 ast_string_field_set(q, sound_next, "queue-youarenext");
3218 ast_string_field_set(q, sound_thereare, "queue-thereare");
3219 ast_string_field_set(q, sound_calls, "queue-callswaiting");
3220 ast_string_field_set(q, queue_quantity1, "queue-quantity1");
3221 ast_string_field_set(q, queue_quantity2, "queue-quantity2");
3222 ast_string_field_set(q, sound_holdtime, "queue-holdtime");
3223 ast_string_field_set(q, sound_minutes, "queue-minutes");
3224 ast_string_field_set(q, sound_minute, "queue-minute");
3225 ast_string_field_set(q, sound_seconds, "queue-seconds");
3226 ast_string_field_set(q, sound_thanks, "queue-thankyou");
3227 ast_string_field_set(q, sound_callerannounce, "");
3228 ast_string_field_set(q, sound_reporthold, "queue-reporthold");
3229
3230 if (!q->sound_periodicannounce[0]) {
3231 q->sound_periodicannounce[0] = ast_str_create(32);
3232 }
3233
3234 if (q->sound_periodicannounce[0]) {
3235 ast_str_set(&q->sound_periodicannounce[0], 0, "queue-periodic-announce");
3236 }
3237
3238 for (i = 1; i < MAX_PERIODIC_ANNOUNCEMENTS; i++) {
3239 if (q->sound_periodicannounce[i]) {
3240 ast_str_set(&q->sound_periodicannounce[i], 0, "%s", "");
3241 }
3242 }
3243
3244 while ((pr_iter = AST_LIST_REMOVE_HEAD(&q->rules,list))) {
3245 ast_free(pr_iter);
3246 }
3247
3248 /* On restart assume no members are available.
3249 * The queue_avail hint is a boolean state to indicate whether a member is available or not.
3250 *
3251 * This seems counter intuitive, but is required to light a BLF
3252 * AST_DEVICE_INUSE indicates no members are available.
3253 * AST_DEVICE_NOT_INUSE indicates a member is available.
3254 */
3255 ast_devstate_changed(AST_DEVICE_INUSE, AST_DEVSTATE_CACHABLE, "Queue:%s_avail", q->name);
3256 }
3257
3258 static void clear_queue(struct call_queue *q)
3259 {
3260 q->holdtime = 0;
3261 q->callscompleted = 0;
3262 q->callsabandoned = 0;
3263 q->callscompletedinsl = 0;
3264 q->callsabandonedinsl = 0;
3265 q->talktime = 0;
3266
3267 if (q->members) {
3268 struct member *mem;
3269 struct ao2_iterator mem_iter = ao2_iterator_init(q->members, 0);
3270 while ((mem = ao2_iterator_next(&mem_iter))) {
3271 mem->calls = 0;
3272 mem->callcompletedinsl = 0;
3273 mem->lastcall = 0;
3274 mem->starttime = 0;
3275 ao2_ref(mem, -1);
3276 }
3277 ao2_iterator_destroy(&mem_iter);
3278 }
3279 }
3280
3281 /*!
3282 * \brief Change queue penalty by adding rule.
3283 *
3284 * Check rule for errors with time or formatting, see if rule is relative to rest
3285 * of queue, iterate list of rules to find correct insertion point, insert and return.
3286 * \retval -1 on failure
3287 * \retval 0 on success
3288 * \note Call this with the rule_lists locked
3289 */
3290 static int insert_penaltychange(const char *list_name, const char *content, const int linenum)
3291 {
3292 char *timestr, *maxstr, *minstr, *raisestr, *contentdup;
3293 struct penalty_rule *rule = NULL, *rule_iter;
3294 struct rule_list *rl_iter;
3295 int penaltychangetime, inserted = 0;
3296
3297 if (!(rule = ast_calloc(1, sizeof(*rule)))) {
3298 return -1;
3299 }
3300
3301 contentdup = ast_strdupa(content);
3302
3303 if (!(maxstr = strchr(contentdup, ','))) {
3304 ast_log(LOG_WARNING, "Improperly formatted penaltychange rule at line %d. Ignoring.\n", linenum);
3305 ast_free(rule);
3306 return -1;
3307 }
3308
3309 *maxstr++ = '\0';
3310 if ((minstr = strchr(maxstr,','))) {
3311 *minstr++ = '\0';
3312 if ((raisestr = strchr(minstr,','))) {
3313 *raisestr++ = '\0';
3314 }
3315 } else {
3316 raisestr = NULL;
3317 }
3318
3319 timestr = contentdup;
3320 if ((penaltychangetime = atoi(timestr)) < 0) {
3321 ast_log(LOG_WARNING, "Improper time parameter specified for penaltychange rule at line %d. Ignoring.\n", linenum);
3322 ast_free(rule);
3323 return -1;
3324 }
3325
3326 rule->time = penaltychangetime;
3327
3328 /* The last check will evaluate true if either no penalty change is indicated for a given rule
3329 * OR if a min penalty change is indicated but no max penalty change is */
3330 if (*maxstr == '+' || *maxstr == '-' || *maxstr == '\0') {
3331 rule->max_relative = 1;
3332 }
3333
3334 rule->max_value = atoi(maxstr);
3335
3336 if (!ast_strlen_zero(minstr)) {
3337 if (*minstr == '+' || *minstr == '-') {
3338 rule->min_relative = 1;
3339 }
3340 rule->min_value = atoi(minstr);
3341 } else { /*there was no minimum specified, so assume this means no change*/
3342 rule->min_relative = 1;
3343 }
3344
3345 if (!ast_strlen_zero(raisestr)) {
3346 rule->raise_respect_min = 0; /* Initialize to 0 */
3347 if (*raisestr == 'r') {
3348 rule->raise_respect_min = 1; /* Set the flag */
3349 raisestr++;
3350 }
3351 if (*raisestr == '+' || *raisestr == '-') {
3352 rule->raise_relative = 1;
3353 }
3354 rule->raise_value = atoi(raisestr);
3355 } else { /*there was no raise specified, so assume this means no change*/
3356 rule->raise_relative = 1;
3357 }
3358
3359 /*We have the rule made, now we need to insert it where it belongs*/
3360 AST_LIST_TRAVERSE(&rule_lists, rl_iter, list){
3361 if (strcasecmp(rl_iter->name, list_name)) {
3362 continue;
3363 }
3364
3365 AST_LIST_TRAVERSE_SAFE_BEGIN(&rl_iter->rules, rule_iter, list) {
3366 if (rule->time < rule_iter->time) {
3367 AST_LIST_INSERT_BEFORE_CURRENT(rule, list);
3368 inserted = 1;
3369 break;
3370 }
3371 }
3372 AST_LIST_TRAVERSE_SAFE_END;
3373
3374 if (!inserted) {
3375 AST_LIST_INSERT_TAIL(&rl_iter->rules, rule, list);
3376 inserted = 1;
3377 }
3378
3379 break;
3380 }
3381
3382 if (!inserted) {
3383 ast_log(LOG_WARNING, "Unknown rule list name %s; ignoring.\n", list_name);
3384 ast_free(rule);
3385 return -1;
3386 }
3387 return 0;
3388 }
3389
3390 /*!
3391 * \brief Load queue rules from realtime.
3392 *
3393 * Check rule for errors with time or formatting, see if rule is relative to rest
3394 * of queue, iterate list of rules to find correct insertion point, insert and return.
3395 * \retval -1 on failure
3396 * \retval 0 on success
3397 * \note Call this with the rule_lists locked
3398 */
3399 static int load_realtime_rules(void)
3400 {
3401 struct ast_config *cfg;
3402 struct rule_list *rl_iter, *new_rl;
3403 struct penalty_rule *pr_iter;
3404 char *rulecat = NULL;
3405
3406 if (!ast_check_realtime("queue_rules")) {
3407 ast_log(LOG_WARNING, "Missing \"queue_rules\" in extconfig.conf\n");
3408 return 0;
3409 }
3410 if (!(cfg = ast_load_realtime_multientry("queue_rules", "rule_name LIKE", "%", SENTINEL))) {
3411 ast_log(LOG_WARNING, "Failed to load queue rules from realtime\n");
3412 return 0;
3413 }
3414 while ((rulecat = ast_category_browse(cfg, rulecat))) {
3415 const char *timestr, *maxstr, *minstr, *raisestr, *rule_name;
3416 int penaltychangetime, rule_exists = 0, inserted = 0;
3417 int max_penalty = 0, min_penalty = 0, raise_penalty = 0;
3418 int min_relative = 0, max_relative = 0, raise_relative = 0;
3419 struct penalty_rule *new_penalty_rule = NULL;
3420
3421 rule_name = ast_variable_retrieve(cfg, rulecat, "rule_name");
3422 if (ast_strlen_zero(rule_name)) {
3423 continue;
3424 }
3425
3426 AST_LIST_TRAVERSE(&rule_lists, rl_iter, list) {
3427 if (!(strcasecmp(rl_iter->name, rule_name))) {
3428 rule_exists = 1;
3429 new_rl = rl_iter;
3430 break;
3431 }
3432 }
3433 if (!rule_exists) {
3434 if (!(new_rl = ast_calloc(1, sizeof(*new_rl)))) {
3435 ast_config_destroy(cfg);
3436 return -1;
3437 }
3438 ast_copy_string(new_rl->name, rule_name, sizeof(new_rl->name));
3439 AST_LIST_INSERT_TAIL(&rule_lists, new_rl, list);
3440 }
3441 timestr = ast_variable_retrieve(cfg, rulecat, "time");
3442 if (!(timestr) || sscanf(timestr, "%30d", &penaltychangetime) != 1) {
3443 ast_log(LOG_NOTICE, "Failed to parse time (%s) for one of the %s rules, skipping it\n",
3444 (ast_strlen_zero(timestr) ? "invalid value" : timestr), rule_name);
3445 continue;
3446 }
3447 if (!(new_penalty_rule = ast_calloc(1, sizeof(*new_penalty_rule)))) {
3448 ast_config_destroy(cfg);
3449 return -1;
3450 }
3451 if (!(maxstr = ast_variable_retrieve(cfg, rulecat, "max_penalty")) ||
3452 ast_strlen_zero(maxstr) || sscanf(maxstr, "%30d", &max_penalty) != 1) {
3453 max_penalty = 0;
3454 max_relative = 1;
3455 } else {
3456 if (*maxstr == '+' || *maxstr == '-') {
3457 max_relative = 1;
3458 }
3459 }
3460 if (!(minstr = ast_variable_retrieve(cfg, rulecat, "min_penalty")) ||
3461 ast_strlen_zero(minstr) || sscanf(minstr, "%30d", &min_penalty) != 1) {
3462 min_penalty = 0;
3463 min_relative = 1;
3464 } else {
3465 if (*minstr == '+' || *minstr == '-') {
3466 min_relative = 1;
3467 }
3468 }
3469 if (!(raisestr = ast_variable_retrieve(cfg, rulecat, "raise_penalty")) ||
3470 ast_strlen_zero(raisestr) ) {
3471 raise_penalty = 0;
3472 raise_relative = 1;
3473 } else {
3474 if (*raisestr == 'r') {
3475 new_penalty_rule->raise_respect_min = 1;
3476 raisestr++;
3477 } else {
3478 new_penalty_rule->raise_respect_min = 0;
3479 }
3480 if (*raisestr == '+' || *raisestr == '-') {
3481 raise_relative = 1;
3482 }
3483 if (sscanf(raisestr, "%30d", &raise_penalty) != 1) {
3484 raise_penalty = 0;
3485 raise_relative = 1;
3486 }
3487 }
3488 new_penalty_rule->time = penaltychangetime;
3489 new_penalty_rule->max_relative = max_relative;
3490 new_penalty_rule->max_value = max_penalty;
3491 new_penalty_rule->min_relative = min_relative;
3492 new_penalty_rule->min_value = min_penalty;
3493 new_penalty_rule->raise_relative = raise_relative;
3494 new_penalty_rule->raise_value = raise_penalty;
3495 AST_LIST_TRAVERSE_SAFE_BEGIN(&new_rl->rules, pr_iter, list) {
3496 if (new_penalty_rule->time < pr_iter->time) {
3497 AST_LIST_INSERT_BEFORE_CURRENT(new_penalty_rule, list);
3498 inserted = 1;
3499 }
3500 }
3501 AST_LIST_TRAVERSE_SAFE_END;
3502 if (!inserted) {
3503 AST_LIST_INSERT_TAIL(&new_rl->rules, new_penalty_rule, list);
3504 }
3505 }
3506
3507 ast_config_destroy(cfg);
3508 return 0;
3509 }
3510
3511 static void parse_empty_options(const char *value, enum empty_conditions *empty, int joinempty)
3512 {
3513 char *value_copy = ast_strdupa(value);
3514 char *option = NULL;
3515 while ((option = strsep(&value_copy, ","))) {
3516 if (!strcasecmp(option, "paused")) {
3517 *empty |= QUEUE_EMPTY_PAUSED;
3518 } else if (!strcasecmp(option, "penalty")) {
3519 *empty |= QUEUE_EMPTY_PENALTY;
3520 } else if (!strcasecmp(option, "inuse")) {
3521 *empty |= QUEUE_EMPTY_INUSE;
3522 } else if (!strcasecmp(option, "ringing")) {
3523 *empty |= QUEUE_EMPTY_RINGING;
3524 } else if (!strcasecmp(option, "invalid")) {
3525 *empty |= QUEUE_EMPTY_INVALID;
3526 } else if (!strcasecmp(option, "wrapup")) {
3527 *empty |= QUEUE_EMPTY_WRAPUP;
3528 } else if (!strcasecmp(option, "unavailable")) {
3529 *empty |= QUEUE_EMPTY_UNAVAILABLE;
3530 } else if (!strcasecmp(option, "unknown")) {
3531 *empty |= QUEUE_EMPTY_UNKNOWN;
3532 } else if (!strcasecmp(option, "loose")) {
3533 *empty = (QUEUE_EMPTY_PENALTY | QUEUE_EMPTY_INVALID);
3534 } else if (!strcasecmp(option, "strict")) {
3535 *empty = (QUEUE_EMPTY_PENALTY | QUEUE_EMPTY_INVALID | QUEUE_EMPTY_PAUSED | QUEUE_EMPTY_UNAVAILABLE);
3536 } else if ((ast_false(option) && joinempty) || (ast_true(option) && !joinempty)) {
3537 *empty = (QUEUE_EMPTY_PENALTY | QUEUE_EMPTY_INVALID | QUEUE_EMPTY_PAUSED);
3538 } else if ((ast_false(option) && !joinempty) || (ast_true(option) && joinempty)) {
3539 *empty = 0;
3540 } else {
3541 ast_log(LOG_WARNING, "Unknown option %s for '%s'\n", option, joinempty ? "joinempty" : "leavewhenempty");
3542 }
3543 }
3544 }
3545
3546 /*! \brief Configure a queue parameter.
3547 *
3548 * The failunknown flag is set for config files (and static realtime) to show
3549 * errors for unknown parameters. It is cleared for dynamic realtime to allow
3550 * extra fields in the tables.
3551 * \note For error reporting, line number is passed for .conf static configuration,
3552 * for Realtime queues, linenum is -1.
3553 */
3554 static void queue_set_param(struct call_queue *q, const char *param, const char *val, int linenum, int failunknown)
3555 {
3556 if (!strcasecmp(param, "musicclass") ||
3557 !strcasecmp(param, "music") || !strcasecmp(param, "musiconhold")) {
3558 ast_string_field_set(q, moh, val);
3559 } else if (!strcasecmp(param, "announce")) {
3560 ast_string_field_set(q, announce, val);
3561 } else if (!strcasecmp(param, "context")) {
3562 ast_string_field_set(q, context, val);
3563 } else if (!strcasecmp(param, "timeout")) {
3564 q->timeout = atoi(val);
3565 if (q->timeout < 0) {
3566 q->timeout = DEFAULT_TIMEOUT;
3567 }
3568 } else if (!strcasecmp(param, "ringinuse")) {
3569 q->ringinuse = ast_true(val);
3570 } else if (!strcasecmp(param, "setinterfacevar")) {
3571 q->setinterfacevar = ast_true(val);
3572 } else if (!strcasecmp(param, "setqueuevar")) {
3573 q->setqueuevar = ast_true(val);
3574 } else if (!strcasecmp(param, "setqueueentryvar")) {
3575 q->setqueueentryvar = ast_true(val);
3576 } else if (!strcasecmp(param, "monitor-format")) {
3577 ast_copy_string(q->monfmt, val, sizeof(q->monfmt));
3578 } else if (!strcasecmp(param, "membergosub")) {
3579 ast_string_field_set(q, membergosub, val);
3580 } else if (!strcasecmp(param, "queue-youarenext")) {
3581 ast_string_field_set(q, sound_next, val);
3582 } else if (!strcasecmp(param, "queue-thereare")) {
3583 ast_string_field_set(q, sound_thereare, val);
3584 } else if (!strcasecmp(param, "queue-callswaiting")) {
3585 ast_string_field_set(q, sound_calls, val);
3586 } else if (!strcasecmp(param, "queue-quantity1")) {
3587 ast_string_field_set(q, queue_quantity1, val);
3588 } else if (!strcasecmp(param, "queue-quantity2")) {
3589 ast_string_field_set(q, queue_quantity2, val);
3590 } else if (!strcasecmp(param, "queue-holdtime")) {
3591 ast_string_field_set(q, sound_holdtime, val);
3592 } else if (!strcasecmp(param, "queue-minutes")) {
3593 ast_string_field_set(q, sound_minutes, val);
3594 } else if (!strcasecmp(param, "queue-minute")) {
3595 ast_string_field_set(q, sound_minute, val);
3596 } else if (!strcasecmp(param, "queue-seconds")) {
3597 ast_string_field_set(q, sound_seconds, val);
3598 } else if (!strcasecmp(param, "queue-thankyou")) {
3599 ast_string_field_set(q, sound_thanks, val);
3600 } else if (!strcasecmp(param, "queue-callerannounce")) {
3601 ast_string_field_set(q, sound_callerannounce, val);
3602 } else if (!strcasecmp(param, "queue-reporthold")) {
3603 ast_string_field_set(q, sound_reporthold, val);
3604 } else if (!strcasecmp(param, "announce-frequency")) {
3605 q->announcefrequency = atoi(val);
3606 } else if (!strcasecmp(param, "announce-to-first-user")) {
3607 q->announce_to_first_user = ast_true(val);
3608 } else if (!strcasecmp(param, "min-announce-frequency")) {
3609 q->minannouncefrequency = atoi(val);
3610 ast_debug(1, "%s=%s for queue '%s'\n", param, val, q->name);
3611 } else if (!strcasecmp(param, "announce-round-seconds")) {
3612 q->roundingseconds = atoi(val);
3613 /* Rounding to any other values just doesn't make sense... */
3614 if (!(q->roundingseconds == 0 || q->roundingseconds == 5 || q->roundingseconds == 10
3615 || q->roundingseconds == 15 || q->roundingseconds == 20 || q->roundingseconds == 30)) {
3616 if (linenum >= 0) {
3617 ast_log(LOG_WARNING, "'%s' isn't a valid value for %s "
3618 "using 0 instead for queue '%s' at line %d of queues.conf\n",
3619 val, param, q->name, linenum);
3620 } else {
3621 ast_log(LOG_WARNING, "'%s' isn't a valid value for %s "
3622 "using 0 instead for queue '%s'\n", val, param, q->name);
3623 }
3624 q->roundingseconds=0;
3625 }
3626 } else if (!strcasecmp(param, "announce-holdtime")) {
3627 if (!strcasecmp(val, "once")) {
3628 q->announceholdtime = ANNOUNCEHOLDTIME_ONCE;
3629 } else if (ast_true(val)) {
3630 q->announceholdtime = ANNOUNCEHOLDTIME_ALWAYS;
3631 } else {
3632 q->announceholdtime = 0;
3633 }
3634 } else if (!strcasecmp(param, "announce-position")) {
3635 if (!strcasecmp(val, "limit")) {
3636 q->announceposition = ANNOUNCEPOSITION_LIMIT;
3637 } else if (!strcasecmp(val, "more")) {
3638 q->announceposition = ANNOUNCEPOSITION_MORE_THAN;
3639 } else if (ast_true(val)) {
3640 q->announceposition = ANNOUNCEPOSITION_YES;
3641 } else {
3642 q->announceposition = ANNOUNCEPOSITION_NO;
3643 }
3644 } else if (!strcasecmp(param, "announce-position-only-up")) {
3645 q->announceposition_only_up = ast_true(val);
3646 } else if (!strcasecmp(param, "announce-position-limit")) {
3647 q->announcepositionlimit = atoi(val);
3648 } else if (!strcasecmp(param, "periodic-announce")) {
3649 if (strchr(val, ',')) {
3650 char *s, *buf = ast_strdupa(val);
3651 unsigned int i = 0;
3652
3653 while ((s = strsep(&buf, ",|"))) {
3654 if (!q->sound_periodicannounce[i]) {
3655 q->sound_periodicannounce[i] = ast_str_create(16);
3656 }
3657 ast_str_set(&q->sound_periodicannounce[i], 0, "%s", s);
3658 i++;
3659 if (i == MAX_PERIODIC_ANNOUNCEMENTS) {
3660 break;
3661 }
3662 }
3663 q->numperiodicannounce = i;
3664 } else {
3665 ast_str_set(&q->sound_periodicannounce[0], 0, "%s", val);
3666 q->numperiodicannounce = 1;
3667 }
3668 } else if (!strcasecmp(param, "periodic-announce-startdelay")) {
3669 q->periodicannouncestartdelay = atoi(val);
3670 } else if (!strcasecmp(param, "periodic-announce-frequency")) {
3671 q->periodicannouncefrequency = atoi(val);
3672 } else if (!strcasecmp(param, "relative-periodic-announce")) {
3673 q->relativeperiodicannounce = ast_true(val);
3674 } else if (!strcasecmp(param, "random-periodic-announce")) {
3675 q->randomperiodicannounce = ast_true(val);
3676 } else if (!strcasecmp(param, "retry")) {
3677 q->retry = atoi(val);
3678 if (q->retry <= 0) {
3679 q->retry = DEFAULT_RETRY;
3680 }
3681 } else if (!strcasecmp(param, "wrapuptime")) {
3682 q->wrapuptime = atoi(val);
3683 } else if (!strcasecmp(param, "penaltymemberslimit")) {
3684 if ((sscanf(val, "%10d", &q->penaltymemberslimit) != 1)) {
3685 q->penaltymemberslimit = 0;
3686 }
3687 } else if (!strcasecmp(param, "autofill")) {
3688 q->autofill = ast_true(val);
3689 } else if (!strcasecmp(param, "autopause")) {
3690 q->autopause = autopause2int(val);
3691 } else if (!strcasecmp(param, "autopausedelay")) {
3692 q->autopausedelay = atoi(val);
3693 } else if (!strcasecmp(param, "autopausebusy")) {
3694 q->autopausebusy = ast_true(val);
3695 } else if (!strcasecmp(param, "autopauseunavail")) {
3696 q->autopauseunavail = ast_true(val);
3697 } else if (!strcasecmp(param, "maxlen")) {
3698 q->maxlen = atoi(val);
3699 if (q->maxlen < 0) {
3700 q->maxlen = 0;
3701 }
3702 } else if (!strcasecmp(param, "servicelevel")) {
3703 q->servicelevel= atoi(val);
3704 } else if (!strcasecmp(param, "strategy")) {
3705 int strategy;
3706
3707 /* We are a static queue and already have set this, no need to do it again */
3708 if (failunknown) {
3709 return;
3710 }
3711 strategy = strat2int(val);
3712 if (strategy < 0) {
3713 ast_log(LOG_WARNING, "'%s' isn't a valid strategy for queue '%s', using ringall instead\n",
3714 val, q->name);
3715 strategy = QUEUE_STRATEGY_RINGALL;
3716 }
3717 if (strategy == q->strategy) {
3718 return;
3719 }
3720 if (strategy == QUEUE_STRATEGY_LINEAR) {
3721 ast_log(LOG_WARNING, "Changing to the linear strategy currently requires asterisk to be restarted.\n");
3722 return;
3723 }
3724 q->strategy = strategy;
3725 } else if (!strcasecmp(param, "joinempty")) {
3726 parse_empty_options(val, &q->joinempty, 1);
3727 } else if (!strcasecmp(param, "leavewhenempty")) {
3728 parse_empty_options(val, &q->leavewhenempty, 0);
3729 } else if (!strcasecmp(param, "reportholdtime")) {
3730 q->reportholdtime = ast_true(val);
3731 } else if (!strcasecmp(param, "memberdelay")) {
3732 q->memberdelay = atoi(val);
3733 } else if (!strcasecmp(param, "weight")) {
3734 q->weight = atoi(val);
3735 } else if (!strcasecmp(param, "timeoutrestart")) {
3736 q->timeoutrestart = ast_true(val);
3737 } else if (!strcasecmp(param, "defaultrule")) {
3738 ast_string_field_set(q, defaultrule, val);
3739 } else if (!strcasecmp(param, "timeoutpriority")) {
3740 if (!strcasecmp(val, "conf")) {
3741 q->timeoutpriority = TIMEOUT_PRIORITY_CONF;
3742 } else {
3743 q->timeoutpriority = TIMEOUT_PRIORITY_APP;
3744 }
3745 } else if (!strcasecmp(param, "log-restricted-caller-id")) {
3746 q->log_restricted_caller_id = ast_true(val);
3747 } else if (failunknown) {
3748 if (linenum >= 0) {
3749 ast_log(LOG_WARNING, "Unknown keyword in queue '%s': %s at line %d of queues.conf\n",
3750 q->name, param, linenum);
3751 } else {
3752 ast_log(LOG_WARNING, "Unknown keyword in queue '%s': %s\n", q->name, param);
3753 }
3754 }
3755 }
3756
3757
3758 #define QUEUE_PAUSED_DEVSTATE AST_DEVICE_INUSE
3759 #define QUEUE_UNPAUSED_DEVSTATE AST_DEVICE_NOT_INUSE
3760 #define QUEUE_UNKNOWN_PAUSED_DEVSTATE AST_DEVICE_NOT_INUSE
3761
3762 /*! \internal
3763 * \brief If adding a single new member to a queue, use this function instead of ao2_linking.
3764 * This adds round robin queue position data for a fresh member as well as links it.
3765 * \param queue Which queue the member is being added to
3766 * \param mem Which member is being added to the queue
3767 */
3768 static void member_add_to_queue(struct call_queue *queue, struct member *mem)
3769 {
3770 ao2_lock(queue->members);
3771 mem->queuepos = ao2_container_count(queue->members);
3772 ao2_link(queue->members, mem);
3773 ast_devstate_changed(mem->paused ? QUEUE_PAUSED_DEVSTATE : QUEUE_UNPAUSED_DEVSTATE,
3774 AST_DEVSTATE_CACHABLE, "Queue:%s_pause_%s", queue->name, mem->interface);
3775 ao2_unlock(queue->members);
3776 }
3777
3778 /*! \internal
3779 * \brief If removing a single member from a queue, use this function instead of ao2_unlinking.
3780 * This will perform round robin queue position reordering for the remaining members.
3781 * \param queue Which queue the member is being removed from
3782 * \param mem Which member is being removed from the queue
3783 */
3784 static void member_remove_from_queue(struct call_queue *queue, struct member *mem)
3785 {
3786 pending_members_remove(mem);
3787 ao2_lock(queue->members);
3788 ast_devstate_changed(QUEUE_UNKNOWN_PAUSED_DEVSTATE, AST_DEVSTATE_CACHABLE, "Queue:%s_pause_%s", queue->name, mem->interface);
3789 queue_member_follower_removal(queue, mem);
3790 ao2_unlink(queue->members, mem);
3791 ao2_unlock(queue->members);
3792 }
3793
3794 /*!
3795 * \brief Find rt member record to update otherwise create one.
3796 *
3797 * Search for member in queue, if found update penalty/paused state,
3798 * if no member exists create one flag it as a RT member and add to queue member list.
3799 */
3800 static void rt_handle_member_record(struct call_queue *q, char *category, struct ast_config *member_config)
3801 {
3802 struct member *m;
3803 struct ao2_iterator mem_iter;
3804 int penalty = 0;
3805 int paused = 0;
3806 int found = 0;
3807 int wrapuptime = 0;
3808 int ringinuse = q->ringinuse;
3809
3810 const char *config_val;
3811 const char *interface = ast_variable_retrieve(member_config, category, "interface");
3812 const char *rt_uniqueid = ast_variable_retrieve(member_config, category, "uniqueid");
3813 const char *membername = S_OR(ast_variable_retrieve(member_config, category, "membername"), interface);
3814 const char *state_interface = S_OR(ast_variable_retrieve(member_config, category, "state_interface"), interface);
3815 const char *penalty_str = ast_variable_retrieve(member_config, category, "penalty");
3816 const char *paused_str = ast_variable_retrieve(member_config, category, "paused");
3817 const char *wrapuptime_str = ast_variable_retrieve(member_config, category, "wrapuptime");
3818 const char *reason_paused = ast_variable_retrieve(member_config, category, "reason_paused");
3819
3820 if (ast_strlen_zero(rt_uniqueid)) {
3821 ast_log(LOG_WARNING, "Realtime field 'uniqueid' is empty for member %s\n",
3822 S_OR(membername, "NULL"));
3823 return;
3824 }
3825
3826 if (ast_strlen_zero(interface)) {
3827 ast_log(LOG_WARNING, "Realtime field 'interface' is empty for member %s\n",
3828 S_OR(membername, "NULL"));
3829 return;
3830 }
3831
3832 if (penalty_str) {
3833 penalty = atoi(penalty_str);
3834 if ((penalty < 0) && negative_penalty_invalid) {
3835 return;
3836 } else if (penalty < 0) {
3837 penalty = 0;
3838 }
3839 }
3840
3841 if (paused_str) {
3842 paused = atoi(paused_str);
3843 if (paused < 0) {
3844 paused = 0;
3845 }
3846 }
3847
3848 if (wrapuptime_str) {
3849 wrapuptime = atoi(wrapuptime_str);
3850 if (wrapuptime < 0) {
3851 wrapuptime = 0;
3852 }
3853 }
3854
3855 if ((config_val = ast_variable_retrieve(member_config, category, realtime_ringinuse_field))) {
3856 if (ast_true(config_val)) {
3857 ringinuse = 1;
3858 } else if (ast_false(config_val)) {
3859 ringinuse = 0;
3860 } else {
3861 ast_log(LOG_WARNING, "Invalid value of '%s' field for %s in queue '%s'\n", realtime_ringinuse_field, interface, q->name);
3862 }
3863 }
3864
3865 /* Find member by realtime uniqueid and update */
3866 mem_iter = ao2_iterator_init(q->members, 0);
3867 while ((m = ao2_iterator_next(&mem_iter))) {
3868 if (!strcasecmp(m->rt_uniqueid, rt_uniqueid)) {
3869 m->dead = 0; /* Do not delete this one. */
3870 ast_copy_string(m->rt_uniqueid, rt_uniqueid, sizeof(m->rt_uniqueid));
3871 if (paused_str) {
3872 m->paused = paused;
3873 if (paused && m->lastpause == 0) {
3874 time(&m->lastpause); /* XXX: Should this come from realtime? */
3875 }
3876 ast_devstate_changed(m->paused ? QUEUE_PAUSED_DEVSTATE : QUEUE_UNPAUSED_DEVSTATE,
3877 AST_DEVSTATE_CACHABLE, "Queue:%s_pause_%s", q->name, m->interface);
3878 }
3879 if (strcasecmp(state_interface, m->state_interface)) {
3880 ast_copy_string(m->state_interface, state_interface, sizeof(m->state_interface));
3881 }
3882 m->penalty = penalty;
3883 m->ringinuse = ringinuse;
3884 m->wrapuptime = wrapuptime;
3885 if (realtime_reason_paused) {
3886 ast_copy_string(m->reason_paused, S_OR(reason_paused, ""), sizeof(m->reason_paused));
3887 }
3888 found = 1;
3889 ao2_ref(m, -1);
3890 break;
3891 }
3892 ao2_ref(m, -1);
3893 }
3894 ao2_iterator_destroy(&mem_iter);
3895
3896 /* Create a new member */
3897 if (!found) {
3898 if ((m = create_queue_member(interface, membername, penalty, paused, state_interface, ringinuse, wrapuptime))) {
3899 m->dead = 0;
3900 m->realtime = 1;
3901 ast_copy_string(m->rt_uniqueid, rt_uniqueid, sizeof(m->rt_uniqueid));
3902 if (!ast_strlen_zero(reason_paused)) {
3903 ast_copy_string(m->reason_paused, reason_paused, sizeof(m->reason_paused));
3904 }
3905 if (!log_membername_as_agent) {
3906 ast_queue_log(q->name, "REALTIME", m->interface, "ADDMEMBER", "%s", paused ? "PAUSED" : "");
3907 } else {
3908 ast_queue_log(q->name, "REALTIME", m->membername, "ADDMEMBER", "%s", paused ? "PAUSED" : "");
3909 }
3910 member_add_to_queue(q, m);
3911 ao2_ref(m, -1);
3912 m = NULL;
3913 }
3914 }
3915 }
3916
3917 /*! \brief Iterate through queue's member list and delete them */
3918 static void free_members(struct call_queue *q, int all)
3919 {
3920 /* Free non-dynamic members */
3921 struct member *cur;
3922 struct ao2_iterator mem_iter = ao2_iterator_init(q->members, 0);
3923
3924 while ((cur = ao2_iterator_next(&mem_iter))) {
3925 if (all || !cur->dynamic) {
3926 member_remove_from_queue(q, cur);
3927 }
3928 ao2_ref(cur, -1);
3929 }
3930 ao2_iterator_destroy(&mem_iter);
3931 }
3932
3933 /*! \brief Free queue's member list then its string fields */
3934 static void destroy_queue(void *obj)
3935 {
3936 struct call_queue *q = obj;
3937 int i;
3938
3939 free_members(q, 1);
3940 ast_string_field_free_memory(q);
3941 for (i = 0; i < MAX_PERIODIC_ANNOUNCEMENTS; i++) {
3942 if (q->sound_periodicannounce[i]) {
3943 ast_free(q->sound_periodicannounce[i]);
3944 }
3945 }
3946 ao2_ref(q->members, -1);
3947 }
3948
3949 static struct call_queue *alloc_queue(const char *queuename)
3950 {
3951 struct call_queue *q;
3952
3953 if ((q = ao2_t_alloc(sizeof(*q), destroy_queue, "Allocate queue"))) {
3954 if (ast_string_field_init(q, 64)) {
3955 queue_t_unref(q, "String field allocation failed");
3956 return NULL;
3957 }
3958 ast_string_field_set(q, name, queuename);
3959 }
3960 return q;
3961 }
3962
3963 /*!
3964 * \brief Reload a single queue via realtime.
3965 *
3966 * Check for statically defined queue first, check if deleted RT queue,
3967 * check for new RT queue, if queue vars are not defined init them with defaults.
3968 * reload RT queue vars, set RT queue members dead and reload them, return finished queue.
3969 * \retval the queue,
3970 * \retval NULL if it doesn't exist.
3971 * \note Should be called with the "queues" container locked.
3972 */
3973 static struct call_queue *find_queue_by_name_rt(const char *queuename, struct ast_variable *queue_vars, struct ast_config *member_config)
3974 {
3975 struct ast_variable *v;
3976 struct call_queue *q, tmpq = {
3977 .name = queuename,
3978 };
3979 struct member *m;
3980 struct ao2_iterator mem_iter;
3981 char *category = NULL;
3982 const char *tmp_name;
3983 char *tmp;
3984 char tmpbuf[64]; /* Must be longer than the longest queue param name. */
3985
3986 /* Static queues override realtime. */
3987 if ((q = ao2_t_find(queues, &tmpq, OBJ_POINTER, "Check if static queue exists"))) {
3988 ao2_lock(q);
3989 if (!q->realtime) {
3990 if (q->dead) {
3991 ao2_unlock(q);
3992 queue_t_unref(q, "Queue is dead; can't return it");
3993 return NULL;
3994 }
3995 ast_log(LOG_WARNING, "Static queue '%s' already exists. Not loading from realtime\n", q->name);
3996 ao2_unlock(q);
3997 return q;
3998 }
3999 } else if (!member_config) {
4000 /* Not found in the list, and it's not realtime ... */
4001 return NULL;
4002 }
4003 /* Check if queue is defined in realtime. */
4004 if (!queue_vars) {
4005 /* Delete queue from in-core list if it has been deleted in realtime. */
4006 if (q) {
4007 /*! \note Hmm, can't seem to distinguish a DB failure from a not
4008 found condition... So we might delete an in-core queue
4009 in case of DB failure. */
4010 ast_debug(1, "Queue %s not found in realtime.\n", queuename);
4011
4012 q->dead = 1;
4013 /* Delete if unused (else will be deleted when last caller leaves). */
4014 queues_t_unlink(queues, q, "Unused; removing from container");
4015 ao2_unlock(q);
4016 queue_t_unref(q, "Queue is dead; can't return it");
4017 }
4018 return NULL;
4019 }
4020
4021 /* Create a new queue if an in-core entry does not exist yet. */
4022 if (!q) {
4023 struct ast_variable *tmpvar = NULL;
4024 if (!(q = alloc_queue(queuename))) {
4025 return NULL;
4026 }
4027 ao2_lock(q);
4028 clear_queue(q);
4029 q->realtime = 1;
4030 /*Before we initialize the queue, we need to set the strategy, so that linear strategy
4031 * will allocate the members properly
4032 */
4033 for (tmpvar = queue_vars; tmpvar; tmpvar = tmpvar->next) {
4034 if (!strcasecmp(tmpvar->name, "strategy")) {
4035 q->strategy = strat2int(tmpvar->value);
4036 if (q->strategy < 0) {
4037 ast_log(LOG_WARNING, "'%s' isn't a valid strategy for queue '%s', using ringall instead\n",
4038 tmpvar->value, q->name);
4039 q->strategy = QUEUE_STRATEGY_RINGALL;
4040 }
4041 break;
4042 }
4043 }
4044 /* We traversed all variables and didn't find a strategy */
4045 if (!tmpvar) {
4046 q->strategy = QUEUE_STRATEGY_RINGALL;
4047 }
4048 queues_t_link(queues, q, "Add queue to container");
4049 }
4050 init_queue(q); /* Ensure defaults for all parameters not set explicitly. */
4051
4052 memset(tmpbuf, 0, sizeof(tmpbuf));
4053 for (v = queue_vars; v; v = v->next) {
4054 /* Convert to dashes `-' from underscores `_' as the latter are more SQL friendly. */
4055 if (strchr(v->name, '_')) {
4056 ast_copy_string(tmpbuf, v->name, sizeof(tmpbuf));
4057 tmp_name = tmpbuf;
4058 tmp = tmpbuf;
4059 while ((tmp = strchr(tmp, '_'))) {
4060 *tmp++ = '-';
4061 }
4062 } else {
4063 tmp_name = v->name;
4064 }
4065
4066 /* NULL values don't get returned from realtime; blank values should
4067 * still get set. If someone doesn't want a value to be set, they
4068 * should set the realtime column to NULL, not blank. */
4069 queue_set_param(q, tmp_name, v->value, -1, 0);
4070 }
4071
4072 /* Temporarily set realtime members dead so we can detect deleted ones. */
4073 mem_iter = ao2_iterator_init(q->members, 0);
4074 while ((m = ao2_iterator_next(&mem_iter))) {
4075 if (m->realtime) {
4076 m->dead = 1;
4077 }
4078 ao2_ref(m, -1);
4079 }
4080 ao2_iterator_destroy(&mem_iter);
4081
4082 while ((category = ast_category_browse(member_config, category))) {
4083 rt_handle_member_record(q, category, member_config);
4084 }
4085
4086 /* Delete all realtime members that have been deleted in DB. */
4087 mem_iter = ao2_iterator_init(q->members, 0);
4088 while ((m = ao2_iterator_next(&mem_iter))) {
4089 if (m->dead) {
4090 if (ast_strlen_zero(m->membername) || !log_membername_as_agent) {
4091 ast_queue_log(q->name, "REALTIME", m->interface, "REMOVEMEMBER", "%s", "");
4092 } else {
4093 ast_queue_log(q->name, "REALTIME", m->membername, "REMOVEMEMBER", "%s", "");
4094 }
4095 member_remove_from_queue(q, m);
4096 }
4097 ao2_ref(m, -1);
4098 }
4099 ao2_iterator_destroy(&mem_iter);
4100
4101 ao2_unlock(q);
4102
4103 return q;
4104 }
4105
4106 /*!
4107 * note */
4108
4109 /*!
4110 * \internal
4111 * \brief Returns reference to the named queue. If the queue is realtime, it will load the queue as well.
4112 * \param queuename - name of the desired queue
4113 *
4114 * \retval the queue
4115 * \retval NULL if it doesn't exist
4116 */
4117 static struct call_queue *find_load_queue_rt_friendly(const char *queuename)
4118 {
4119 struct ast_variable *queue_vars;
4120 struct ast_config *member_config = NULL;
4121 struct call_queue *q = NULL, tmpq = {
4122 .name = queuename,
4123 };
4124 int prev_weight = 0;
4125
4126 /* Find the queue in the in-core list first. */
4127 q = ao2_t_find(queues, &tmpq, OBJ_POINTER, "Look for queue in memory first");
4128
4129 if (!q || q->realtime) {
4130 /*! \note Load from realtime before taking the "queues" container lock, to avoid blocking all
4131 queue operations while waiting for the DB.
4132
4133 This will be two separate database transactions, so we might
4134 see queue parameters as they were before another process
4135 changed the queue and member list as it was after the change.
4136 Thus we might see an empty member list when a queue is
4137 deleted. In practise, this is unlikely to cause a problem. */
4138
4139 queue_vars = ast_load_realtime("queues", "name", queuename, SENTINEL);
4140 if (queue_vars) {
4141 member_config = ast_load_realtime_multientry("queue_members", "interface LIKE", "%", "queue_name", queuename, SENTINEL);
4142 if (!member_config) {
4143 ast_debug(1, "No queue_members defined in config extconfig.conf\n");
4144 member_config = ast_config_new();
4145 }
4146 }
4147 if (q) {
4148 prev_weight = q->weight ? 1 : 0;
4149 queue_t_unref(q, "Need to find realtime queue");
4150 }
4151
4152 q = find_queue_by_name_rt(queuename, queue_vars, member_config);
4153 ast_config_destroy(member_config);
4154 ast_variables_destroy(queue_vars);
4155
4156 /* update the use_weight value if the queue's has gained or lost a weight */
4157 if (q) {
4158 if (!q->weight && prev_weight) {
4159 ast_atomic_fetchadd_int(&use_weight, -1);
4160 }
4161 if (q->weight && !prev_weight) {
4162 ast_atomic_fetchadd_int(&use_weight, +1);
4163 }
4164 }
4165 /* Other cases will end up with the proper value for use_weight */
4166 } else {
4167 update_realtime_members(q);
4168 }
4169 return q;
4170 }
4171
4172 /*!
4173 * \internal
4174 * \brief Load queues and members from realtime.
4175 *
4176 * \param queuename - name of the desired queue to load or empty if need to load all queues
4177 */
4178 static void load_realtime_queues(const char *queuename)
4179 {
4180 struct ast_config *cfg = NULL;
4181 char *category = NULL;
4182 const char *name = NULL;
4183 struct call_queue *q = NULL;
4184
4185 if (!ast_check_realtime("queues")) {
4186 return;
4187 }
4188
4189 if (ast_strlen_zero(queuename)) {
4190 if ((cfg = ast_load_realtime_multientry("queues", "name LIKE", "%", SENTINEL))) {
4191 while ((category = ast_category_browse(cfg, category))) {
4192 name = ast_variable_retrieve(cfg, category, "name");
4193 if (!ast_strlen_zero(name) && (q = find_load_queue_rt_friendly(name))) {
4194 queue_unref(q);
4195 }
4196 }
4197 ast_config_destroy(cfg);
4198 }
4199 } else {
4200 if ((q = find_load_queue_rt_friendly(queuename))) {
4201 queue_unref(q);
4202 }
4203 }
4204 }
4205
4206 static int update_realtime_member_field(struct member *mem, const char *queue_name, const char *field, const char *value)
4207 {
4208 int ret = -1;
4209
4210 if (ast_strlen_zero(mem->rt_uniqueid)) {
4211 return ret;
4212 }
4213
4214 if ((ast_update_realtime("queue_members", "uniqueid", mem->rt_uniqueid, field, value, SENTINEL)) >= 0) {
4215 ret = 0;
4216 }
4217
4218 return ret;
4219 }
4220
4221
4222 static void update_realtime_members(struct call_queue *q)
4223 {
4224 struct ast_config *member_config = NULL;
4225 struct member *m;
4226 char *category = NULL;
4227 struct ao2_iterator mem_iter;
4228
4229 if (!(member_config = ast_load_realtime_multientry("queue_members", "interface LIKE", "%", "queue_name", q->name , SENTINEL))) {
4230 /* This queue doesn't have realtime members. If the queue still has any realtime
4231 * members in memory, they need to be removed.
4232 */
4233 ao2_lock(q);
4234 mem_iter = ao2_iterator_init(q->members, 0);
4235 while ((m = ao2_iterator_next(&mem_iter))) {
4236 if (m->realtime) {
4237 member_remove_from_queue(q, m);
4238 }
4239 ao2_ref(m, -1);
4240 }
4241 ao2_iterator_destroy(&mem_iter);
4242 ast_debug(3, "Queue %s has no realtime members defined. No need for update\n", q->name);
4243 ao2_unlock(q);
4244 return;
4245 }
4246
4247 ao2_lock(q);
4248
4249 /* Temporarily set realtime members dead so we can detect deleted ones.*/
4250 mem_iter = ao2_iterator_init(q->members, 0);
4251 while ((m = ao2_iterator_next(&mem_iter))) {
4252 if (m->realtime) {
4253 m->dead = 1;
4254 }
4255 ao2_ref(m, -1);
4256 }
4257 ao2_iterator_destroy(&mem_iter);
4258
4259 while ((category = ast_category_browse(member_config, category))) {
4260 rt_handle_member_record(q, category, member_config);
4261 }
4262
4263 /* Delete all realtime members that have been deleted in DB. */
4264 mem_iter = ao2_iterator_init(q->members, 0);
4265 while ((m = ao2_iterator_next(&mem_iter))) {
4266 if (m->dead) {
4267 if (ast_strlen_zero(m->membername) || !log_membername_as_agent) {
4268 ast_queue_log(q->name, "REALTIME", m->interface, "REMOVEMEMBER", "%s", "");
4269 } else {
4270 ast_queue_log(q->name, "REALTIME", m->membername, "REMOVEMEMBER", "%s", "");
4271 }
4272 member_remove_from_queue(q, m);
4273 }
4274 ao2_ref(m, -1);
4275 }
4276 ao2_iterator_destroy(&mem_iter);
4277 ao2_unlock(q);
4278 ast_config_destroy(member_config);
4279 }
4280
4281 static int join_queue(char *queuename, struct queue_ent *qe, enum queue_result *reason, int position)
4282 {
4283 struct call_queue *q;
4284 struct queue_ent *cur, *prev = NULL;
4285 int res = -1;
4286 int pos = 0;
4287 int inserted = 0;
4288
4289 if (!(q = find_load_queue_rt_friendly(queuename))) {
4290 return res;
4291 }
4292 ao2_lock(q);
4293
4294 /* This is our one */
4295 if (q->joinempty) {
4296 int status = 0;
4297 if ((status = get_member_status(q, qe->max_penalty, qe->min_penalty, qe->raise_penalty, q->joinempty, 0, qe->raise_respect_min))) {
4298 *reason = QUEUE_JOINEMPTY;
4299 ao2_unlock(q);
4300 queue_t_unref(q, "Done with realtime queue");
4301 return res;
4302 }
4303 }
4304 if (*reason == QUEUE_UNKNOWN && q->maxlen && (q->count >= q->maxlen)) {
4305 *reason = QUEUE_FULL;
4306 } else if (*reason == QUEUE_UNKNOWN) {
4307 RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
4308
4309 /* There's space for us, put us at the right position inside
4310 * the queue.
4311 * Take into account the priority of the calling user */
4312 inserted = 0;
4313 prev = NULL;
4314 cur = q->head;
4315 while (cur) {
4316 /* We have higher priority than the current user, enter
4317 * before him, after all the other users with priority
4318 * higher or equal to our priority. */
4319 if ((!inserted) && (qe->prio > cur->prio)) {
4320 insert_entry(q, prev, qe, &pos);
4321 inserted = 1;
4322 }
4323 /* <= is necessary for the position comparison because it may not be possible to enter
4324 * at our desired position since higher-priority callers may have taken the position we want
4325 */
4326 if (!inserted && (qe->prio >= cur->prio) && position && (position <= pos + 1)) {
4327 insert_entry(q, prev, qe, &pos);
4328 inserted = 1;
4329 /*pos is incremented inside insert_entry, so don't need to add 1 here*/
4330 if (position < pos) {
4331 ast_log(LOG_NOTICE, "Asked to be inserted at position %d but forced into position %d due to higher priority callers\n", position, pos);
4332 }
4333 }
4334 cur->pos = ++pos;
4335 prev = cur;
4336 cur = cur->next;
4337 }
4338 /* No luck, join at the end of the queue */
4339 if (!inserted) {
4340 insert_entry(q, prev, qe, &pos);
4341 }
4342 ast_copy_string(qe->moh, q->moh, sizeof(qe->moh));
4343 ast_copy_string(qe->announce, q->announce, sizeof(qe->announce));
4344 ast_copy_string(qe->context, q->context, sizeof(qe->context));
4345 q->count++;
4346 if (q->count == 1) {
4347 ast_devstate_changed(AST_DEVICE_RINGING, AST_DEVSTATE_CACHABLE, "Queue:%s", q->name);
4348 }
4349
4350 res = 0;
4351
4352 blob = ast_json_pack("{s: s, s: i, s: i}",
4353 "Queue", q->name,
4354 "Position", qe->pos,
4355 "Count", q->count);
4356 ast_channel_publish_cached_blob(qe->chan, queue_caller_join_type(), blob);
4357 ast_debug(1, "Queue '%s' Join, Channel '%s', Position '%d'\n", q->name, ast_channel_name(qe->chan), qe->pos );
4358 }
4359 ao2_unlock(q);
4360 queue_t_unref(q, "Done with realtime queue");
4361
4362 return res;
4363 }
4364
4365 static int play_file(struct ast_channel *chan, const char *filename)
4366 {
4367 int res;
4368
4369 if (ast_strlen_zero(filename)) {
4370 return 0;
4371 }
4372
4373 if (!ast_fileexists(filename, NULL, ast_channel_language(chan))) {
4374 return 0;
4375 }
4376
4377 ast_stopstream(chan);
4378
4379 res = ast_streamfile(chan, filename, ast_channel_language(chan));
4380 if (!res) {
4381 res = ast_waitstream(chan, AST_DIGIT_ANY);
4382 }
4383
4384 ast_stopstream(chan);
4385
4386 return res;
4387 }
4388
4389 /*!
4390 * \brief Check for valid exit from queue via goto
4391 * \retval 0 if failure
4392 * \retval 1 if successful
4393 */
4394 static int valid_exit(struct queue_ent *qe, char digit)
4395 {
4396 int digitlen = strlen(qe->digits);
4397
4398 /* Prevent possible buffer overflow */
4399 if (digitlen < sizeof(qe->digits) - 2) {
4400 qe->digits[digitlen] = digit;
4401 qe->digits[digitlen + 1] = '\0';
4402 } else {
4403 qe->digits[0] = '\0';
4404 return 0;
4405 }
4406
4407 /* If there's no context to goto, short-circuit */
4408 if (ast_strlen_zero(qe->context)) {
4409 return 0;
4410 }
4411
4412 /* If the extension is bad, then reset the digits to blank */
4413 if (!ast_canmatch_extension(qe->chan, qe->context, qe->digits, 1,
4414 S_COR(ast_channel_caller(qe->chan)->id.number.valid, ast_channel_caller(qe->chan)->id.number.str, NULL))) {
4415 qe->digits[0] = '\0';
4416 return 0;
4417 }
4418
4419 /* We have an exact match */
4420 if (!ast_goto_if_exists(qe->chan, qe->context, qe->digits, 1)) {
4421 qe->valid_digits = 1;
4422 /* Return 1 on a successful goto */
4423 return 1;
4424 }
4425
4426 return 0;
4427 }
4428
4429 static int say_position(struct queue_ent *qe, int ringing)
4430 {
4431 int res = 0, say_thanks = 0;
4432 long avgholdmins, avgholdsecs;
4433 time_t now;
4434
4435 /* Let minannouncefrequency seconds pass between the start of each position announcement */
4436 time(&now);
4437 if ((now - qe->last_pos) < qe->parent->minannouncefrequency) {
4438 return 0;
4439 }
4440
4441 /* If either our position has changed, or we are over the freq timer, say position */
4442 if ((qe->last_pos_said == qe->pos) && ((now - qe->last_pos) < qe->parent->announcefrequency)) {
4443 return 0;
4444 }
4445
4446 /* Only announce if the caller's queue position has improved since last time */
4447 if (qe->parent->announceposition_only_up && qe->last_pos_said > 0 && qe->last_pos_said <= qe->pos) {
4448 return 0;
4449 }
4450
4451 if (ringing) {
4452 ast_indicate(qe->chan,-1);
4453 } else {
4454 ast_moh_stop(qe->chan);
4455 }
4456
4457 if (qe->parent->announceposition == ANNOUNCEPOSITION_YES ||
4458 qe->parent->announceposition == ANNOUNCEPOSITION_MORE_THAN ||
4459 (qe->parent->announceposition == ANNOUNCEPOSITION_LIMIT &&
4460 qe->pos <= qe->parent->announcepositionlimit)) {
4461 say_thanks = 1;
4462 /* Say we're next, if we are */
4463 if (qe->pos == 1) {
4464 res = play_file(qe->chan, qe->parent->sound_next);
4465 if (!res) {
4466 goto posout;
4467 }
4468 /* Say there are more than N callers */
4469 } else if (qe->parent->announceposition == ANNOUNCEPOSITION_MORE_THAN && qe->pos > qe->parent->announcepositionlimit) {
4470 res = (
4471 play_file(qe->chan, qe->parent->queue_quantity1) ||
4472 ast_say_number(qe->chan, qe->parent->announcepositionlimit, AST_DIGIT_ANY,
4473 ast_channel_language(qe->chan), NULL) || /* Needs gender */
4474 play_file(qe->chan, qe->parent->queue_quantity2));
4475 /* Say there are currently N callers waiting */
4476 } else {
4477 res = (
4478 play_file(qe->chan, qe->parent->sound_thereare) ||
4479 ast_say_number(qe->chan, qe->pos, AST_DIGIT_ANY,
4480 ast_channel_language(qe->chan), "n") || /* Needs gender */
4481 play_file(qe->chan, qe->parent->sound_calls));
4482 }
4483 if (res) {
4484 goto playout;
4485 }
4486 }
4487 /* Round hold time to nearest minute */
4488 avgholdmins = labs(((qe->parent->holdtime + 30) - (now - qe->start)) / 60);
4489
4490 /* If they have specified a rounding then round the seconds as well */
4491 if (qe->parent->roundingseconds) {
4492 avgholdsecs = (labs(((qe->parent->holdtime + 30) - (now - qe->start))) - 60 * avgholdmins) / qe->parent->roundingseconds;
4493 avgholdsecs *= qe->parent->roundingseconds;
4494 } else {
4495 avgholdsecs = 0;
4496 }
4497
4498 ast_verb(3, "Hold time for %s is %ld minute(s) %ld seconds\n", qe->parent->name, avgholdmins, avgholdsecs);
4499
4500 /* If the hold time is >1 min, if it's enabled, and if it's not
4501 supposed to be only once and we have already said it, say it */
4502 if ((avgholdmins+avgholdsecs) > 0 && qe->parent->announceholdtime &&
4503 ((qe->parent->announceholdtime == ANNOUNCEHOLDTIME_ONCE && !qe->last_pos) ||
4504 !(qe->parent->announceholdtime == ANNOUNCEHOLDTIME_ONCE))) {
4505 say_thanks = 1;
4506 res = play_file(qe->chan, qe->parent->sound_holdtime);
4507 if (res) {
4508 goto playout;
4509 }
4510
4511 if (avgholdmins >= 1) {
4512 res = ast_say_number(qe->chan, avgholdmins, AST_DIGIT_ANY, ast_channel_language(qe->chan), "n");
4513 if (res) {
4514 goto playout;
4515 }
4516
4517 if (avgholdmins == 1) {
4518 res = play_file(qe->chan, qe->parent->sound_minute);
4519 if (res) {
4520 goto playout;
4521 }
4522 } else {
4523 res = play_file(qe->chan, qe->parent->sound_minutes);
4524 if (res) {
4525 goto playout;
4526 }
4527 }
4528 }
4529 if (avgholdsecs >= 1) {
4530 res = ast_say_number(qe->chan, avgholdsecs, AST_DIGIT_ANY, ast_channel_language(qe->chan), "n");
4531 if (res) {
4532 goto playout;
4533 }
4534
4535 res = play_file(qe->chan, qe->parent->sound_seconds);
4536 if (res) {
4537 goto playout;
4538 }
4539 }
4540 }
4541
4542 posout:
4543 if (qe->parent->announceposition) {
4544 ast_verb(3, "Told %s in %s their queue position (which was %d)\n",
4545 ast_channel_name(qe->chan), qe->parent->name, qe->pos);
4546 }
4547 if (say_thanks) {
4548 res = play_file(qe->chan, qe->parent->sound_thanks);
4549 }
4550 playout:
4551
4552 if ((res > 0 && !valid_exit(qe, res))) {
4553 res = 0;
4554 }
4555
4556 /* Set our last_pos indicators */
4557 qe->last_pos = now;
4558 qe->last_pos_said = qe->pos;
4559
4560 /* Don't restart music on hold if we're about to exit the caller from the queue */
4561 if (!res) {
4562 if (ringing) {
4563 ast_indicate(qe->chan, AST_CONTROL_RINGING);
4564 } else {
4565 ast_moh_start(qe->chan, qe->moh, NULL);
4566 }
4567 }
4568 return res;
4569 }
4570
4571 static void recalc_holdtime(struct queue_ent *qe, int newholdtime)
4572 {
4573 int oldvalue;
4574
4575 /* Calculate holdtime using an exponential average */
4576 /* Thanks to SRT for this contribution */
4577 /* 2^2 (4) is the filter coefficient; a higher exponent would give old entries more weight */
4578
4579 ao2_lock(qe->parent);
4580 if ((qe->parent->callscompleted + qe->parent->callsabandoned) == 0) {
4581 qe->parent->holdtime = newholdtime;
4582 } else {
4583 oldvalue = qe->parent->holdtime;
4584 qe->parent->holdtime = (((oldvalue << 2) - oldvalue) + newholdtime) >> 2;
4585 }
4586 ao2_unlock(qe->parent);
4587 }
4588
4589 /*! \brief Caller leaving queue.
4590 *
4591 * Search the queue to find the leaving client, if found remove from queue
4592 * create manager event, move others up the queue.
4593 */
4594 static void leave_queue(struct queue_ent *qe)
4595 {
4596 struct call_queue *q;
4597 struct queue_ent *current, *prev = NULL;
4598 struct penalty_rule *pr_iter;
4599 int pos = 0;
4600
4601 if (!(q = qe->parent)) {
4602 return;
4603 }
4604 queue_t_ref(q, "Copy queue pointer from queue entry");
4605 ao2_lock(q);
4606
4607 prev = NULL;
4608 for (current = q->head; current; current = current->next) {
4609 if (current == qe) {
4610 RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
4611 char posstr[20];
4612 q->count--;
4613 if (!q->count) {
4614 ast_devstate_changed(AST_DEVICE_NOT_INUSE, AST_DEVSTATE_CACHABLE, "Queue:%s", q->name);
4615 }
4616
4617 blob = ast_json_pack("{s: s, s: i, s: i}",
4618 "Queue", q->name,
4619 "Position", qe->pos,
4620 "Count", q->count);
4621 ast_channel_publish_cached_blob(qe->chan, queue_caller_leave_type(), blob);
4622 ast_debug(1, "Queue '%s' Leave, Channel '%s'\n", q->name, ast_channel_name(qe->chan));
4623 /* Take us out of the queue */
4624 if (prev) {
4625 prev->next = current->next;
4626 } else {
4627 q->head = current->next;
4628 }
4629 /* Free penalty rules */
4630 while ((pr_iter = AST_LIST_REMOVE_HEAD(&qe->qe_rules, list))) {
4631 ast_free(pr_iter);
4632 }
4633 qe->pr = NULL;
4634 snprintf(posstr, sizeof(posstr), "%d", qe->pos);
4635 pbx_builtin_setvar_helper(qe->chan, "QUEUEPOSITION", posstr);
4636 } else {
4637 /* Renumber the people after us in the queue based on a new count */
4638 current->pos = ++pos;
4639 prev = current;
4640 }
4641 }
4642 ao2_unlock(q);
4643
4644 /*If the queue is a realtime queue, check to see if it's still defined in real time*/
4645 if (q->realtime) {
4646 struct ast_variable *var;
4647 if (!(var = ast_load_realtime("queues", "name", q->name, SENTINEL))) {
4648 q->dead = 1;
4649 } else {
4650 ast_variables_destroy(var);
4651 }
4652 }
4653
4654 if (q->dead) {
4655 /* It's dead and nobody is in it, so kill it */
4656 queues_t_unlink(queues, q, "Queue is now dead; remove it from the container");
4657 }
4658 /* unref the explicit ref earlier in the function */
4659 queue_t_unref(q, "Expire copied reference");
4660 }
4661
4662 /*!
4663 * \internal
4664 * \brief Destroy the given callattempt structure and free it.
4665 * \since 1.8
4666 *
4667 * \param doomed callattempt structure to destroy.
4668 */
4669 static void callattempt_free(struct callattempt *doomed)
4670 {
4671 if (doomed->member) {
4672 ao2_ref(doomed->member, -1);
4673 }
4674 ast_party_connected_line_free(&doomed->connected);
4675 ast_free(doomed->orig_chan_name);
4676 ast_free(doomed);
4677 }
4678
4679 static void publish_dial_end_event(struct ast_channel *in, struct callattempt *outgoing, struct ast_channel *exception, const char *status)
4680 {
4681 struct callattempt *cur;
4682
4683 for (cur = outgoing; cur; cur = cur->q_next) {
4684 if (cur->chan && cur->chan != exception) {
4685 ast_channel_publish_dial(in, cur->chan, NULL, status);
4686 }
4687 }
4688 }
4689
4690 /*! \brief Hang up a list of outgoing calls */
4691 static void hangupcalls(struct queue_ent *qe, struct callattempt *outgoing, struct ast_channel *exception, int cancel_answered_elsewhere)
4692 {
4693 struct callattempt *oo;
4694
4695 while (outgoing) {
4696 /* If someone else answered the call we should indicate this in the CANCEL */
4697 /* Hangup any existing lines we have open */
4698 if (outgoing->chan && (outgoing->chan != exception)) {
4699 if (exception || cancel_answered_elsewhere) {
4700 ast_channel_hangupcause_set(outgoing->chan, AST_CAUSE_ANSWERED_ELSEWHERE);
4701 }
4702 ast_channel_publish_dial(qe->chan, outgoing->chan, outgoing->interface, "CANCEL");
4703
4704 /* When dialing channels it is possible that they may not ever
4705 * leave the not in use state (Local channels in particular) by
4706 * the time we cancel them. If this occurs but we know they were
4707 * dialed we explicitly remove them from the pending members
4708 * container so that subsequent call attempts occur.
4709 */
4710 if (outgoing->member->status == AST_DEVICE_NOT_INUSE) {
4711 pending_members_remove(outgoing->member);
4712 }
4713
4714 ast_hangup(outgoing->chan);
4715 }
4716 oo = outgoing;
4717 outgoing = outgoing->q_next;
4718 ast_aoc_destroy_decoded(oo->aoc_s_rate_list);
4719 callattempt_free(oo);
4720 }
4721 }
4722
4723 /*!
4724 * \brief Get the number of members available to accept a call.
4725 *
4726 * \note The queue passed in should be locked prior to this function call
4727 *
4728 * \param[in] q The queue for which we are counting the number of available members
4729 * \return Return the number of available members in queue q
4730 */
4731 static int num_available_members(struct call_queue *q)
4732 {
4733 struct member *mem;
4734 int avl = 0;
4735 struct ao2_iterator mem_iter;
4736
4737 mem_iter = ao2_iterator_init(q->members, 0);
4738 while ((mem = ao2_iterator_next(&mem_iter))) {
4739
4740 avl += is_member_available(q, mem);
4741 ao2_ref(mem, -1);
4742
4743 /* If autofill is not enabled or if the queue's strategy is ringall, then
4744 * we really don't care about the number of available members so much as we
4745 * do that there is at least one available.
4746 *
4747 * In fact, we purposely will return from this function stating that only
4748 * one member is available if either of those conditions hold. That way,
4749 * functions which determine what action to take based on the number of available
4750 * members will operate properly. The reasoning is that even if multiple
4751 * members are available, only the head caller can actually be serviced.
4752 */
4753 if ((!q->autofill || q->strategy == QUEUE_STRATEGY_RINGALL) && avl) {
4754 break;
4755 }
4756 }
4757 ao2_iterator_destroy(&mem_iter);
4758
4759 return avl;
4760 }
4761
4762 /* traverse all defined queues which have calls waiting and contain this member
4763 return 0 if no other queue has precedence (higher weight) or 1 if found */
4764 static int compare_weight(struct call_queue *rq, struct member *member)
4765 {
4766 struct call_queue *q;
4767 struct member *mem;
4768 int found = 0;
4769 struct ao2_iterator queue_iter;
4770
4771 queue_iter = ao2_iterator_init(queues, 0);
4772 while ((q = ao2_t_iterator_next(&queue_iter, "Iterate through queues"))) {
4773 if (q == rq) { /* don't check myself, could deadlock */
4774 queue_t_unref(q, "Done with iterator");
4775 continue;
4776 }
4777 ao2_lock(q);
4778 if (q->count && q->members) {
4779 if ((mem = ao2_find(q->members, member, OBJ_POINTER))) {
4780 ast_debug(1, "Found matching member %s in queue '%s'\n", mem->interface, q->name);
4781 if (q->weight > rq->weight && q->count >= num_available_members(q)) {
4782 ast_debug(1, "Queue '%s' (weight %d, calls %d) is preferred over '%s' (weight %d, calls %d)\n", q->name, q->weight, q->count, rq->name, rq->weight, rq->count);
4783 found = 1;
4784 }
4785 ao2_ref(mem, -1);
4786 }
4787 }
4788 ao2_unlock(q);
4789 queue_t_unref(q, "Done with iterator");
4790 if (found) {
4791 break;
4792 }
4793 }
4794 ao2_iterator_destroy(&queue_iter);
4795 return found;
4796 }
4797
4798 static int is_longest_waiting_caller(struct queue_ent *caller, struct member *member)
4799 {
4800 struct call_queue *q;
4801 struct member *mem;
4802 int is_longest_waiting = 1;
4803 struct ao2_iterator queue_iter;
4804 struct queue_ent *ch;
4805
4806 queue_iter = ao2_iterator_init(queues, 0);
4807 while ((q = ao2_t_iterator_next(&queue_iter, "Iterate through queues"))) {
4808 if (q == caller->parent) { /* don't check myself, could deadlock */
4809 queue_t_unref(q, "Done with iterator");
4810 continue;
4811 }
4812 ao2_lock(q);
4813 /*
4814 * If the other queue has equal weight, see if we should let that handle
4815 * their call first. If weights are not equal, compare_weights will step in.
4816 */
4817 if (q->weight == caller->parent->weight && q->count && q->members) {
4818 if ((mem = ao2_find(q->members, member, OBJ_POINTER))) {
4819 ast_debug(2, "Found matching member %s in queue '%s'\n", mem->interface, q->name);
4820
4821 /* Does this queue have a caller that's been waiting longer? */
4822 ch = q->head;
4823 while (ch) {
4824 /* If ch->pending, the other call (which may be waiting for a longer period of time),
4825 * is already ringing at another agent. Ignore such callers; otherwise, all agents
4826 * will be unused until the first caller is picked up.
4827 */
4828 if (!ch->pending) {
4829 if (ch->prio != caller->prio && force_longest_waiting_caller == FORCELONGESTWAITINGCALLER_PRIO) {
4830 if (ch->prio > caller->prio) { /* This queue has a caller with higher priority. */
4831 ast_debug(1, "Queue %s has a call at position %i that's higher priority (%d vs %d)\n",
4832 q->name, ch->pos, ch->prio, caller->prio);
4833 is_longest_waiting = 0;
4834 }
4835 } else if (ch->start < caller->start) {
4836 ast_debug(1, "Queue %s has a call at position %i that's been waiting longer (%li vs %li)\n",
4837 q->name, ch->pos, ch->start, caller->start);
4838 is_longest_waiting = 0;
4839 }
4840 break;
4841 }
4842 ch = ch->next;
4843 }
4844
4845 ao2_ref(mem, -1);
4846 }
4847 }
4848 ao2_unlock(q);
4849 queue_t_unref(q, "Done with iterator");
4850 if (!is_longest_waiting) {
4851 break;
4852 }
4853 }
4854 ao2_iterator_destroy(&queue_iter);
4855 return is_longest_waiting;
4856 }
4857
4858 /*! \brief common hangup actions */
4859 static void do_hang(struct callattempt *o)
4860 {
4861 o->stillgoing = 0;
4862 ast_hangup(o->chan);
4863 pending_members_remove(o->member);
4864 o->chan = NULL;
4865 }
4866
4867 /*!
4868 * \internal
4869 * \brief Check if the member status is available.
4870 *
4871 * \param status Member status to check if available.
4872 *
4873 * \retval non-zero if the member status is available.
4874 */
4875 static int member_status_available(int status)
4876 {
4877 return status == AST_DEVICE_NOT_INUSE || status == AST_DEVICE_UNKNOWN;
4878 }
4879
4880 /*!
4881 * \internal
4882 * \brief Determine if can ring a queue entry.
4883 *
4884 * \param qe Queue entry to check.
4885 * \param call Member call attempt.
4886 *
4887 * \retval non-zero if an entry can be called.
4888 */
4889 static int can_ring_entry(struct queue_ent *qe, struct callattempt *call)
4890 {
4891 struct member *memberp = call->member;
4892 int wrapuptime;
4893
4894 if (memberp->paused) {
4895 ast_debug(1, "%s paused, can't receive call\n", call->interface);
4896 return 0;
4897 }
4898
4899 if (!memberp->ringinuse && !member_status_available(memberp->status)) {
4900 ast_debug(1, "%s not available, can't receive call\n", call->interface);
4901 return 0;
4902 }
4903
4904 if (memberp->lastqueue) {
4905 wrapuptime = get_wrapuptime(memberp->lastqueue, memberp);
4906 } else {
4907 wrapuptime = get_wrapuptime(qe->parent, memberp);
4908 }
4909 if (wrapuptime && (time(NULL) - memberp->lastcall) < wrapuptime) {
4910 ast_debug(1, "Wrapuptime not yet expired on queue %s for %s\n",
4911 (memberp->lastqueue ? memberp->lastqueue->name : qe->parent->name),
4912 call->interface);
4913 return 0;
4914 }
4915
4916 if (use_weight && compare_weight(qe->parent, memberp)) {
4917 ast_debug(1, "Priority queue delaying call to %s:%s\n",
4918 qe->parent->name, call->interface);
4919 return 0;
4920 }
4921
4922 if (force_longest_waiting_caller && !is_longest_waiting_caller(qe, memberp)) {
4923 ast_debug(1, "Another caller was waiting longer; delaying call to %s:%s\n",
4924 qe->parent->name, call->interface);
4925 return 0;
4926 }
4927
4928 if (!memberp->ringinuse) {
4929 struct member *mem;
4930
4931 ao2_lock(pending_members);
4932
4933 mem = ao2_find(pending_members, memberp,
4934 OBJ_SEARCH_OBJECT | OBJ_NOLOCK);
4935 if (mem) {
4936 /*
4937 * If found that means this member is currently being attempted
4938 * from another calling thread, so stop trying from this thread
4939 */
4940 ast_debug(1, "%s has another call trying, can't receive call\n",
4941 call->interface);
4942 ao2_ref(mem, -1);
4943 ao2_unlock(pending_members);
4944 return 0;
4945 }
4946
4947 /*
4948 * If not found add it to the container so another queue
4949 * won't attempt to call this member at the same time.
4950 */
4951 ast_debug(3, "Add %s to pending_members\n", memberp->membername);
4952 ao2_link(pending_members, memberp);
4953 ao2_unlock(pending_members);
4954
4955 /*
4956 * The queue member is available. Get current status to be sure
4957 * because the device state and extension state callbacks may
4958 * not have updated the status yet.
4959 */
4960 if (!member_status_available(get_queue_member_status(memberp))) {
4961 ast_debug(1, "%s actually not available, can't receive call\n",
4962 call->interface);
4963 pending_members_remove(memberp);
4964 return 0;
4965 }
4966 }
4967
4968 return 1;
4969 }
4970
4971 /*!
4972 * \brief Part 2 of ring_one
4973 *
4974 * Does error checking before attempting to request a channel and call a member.
4975 * This function is only called from ring_one().
4976 * Failure can occur if:
4977 * - Agent on call
4978 * - Agent is paused
4979 * - Wrapup time not expired
4980 * - Priority by another queue
4981 *
4982 * \retval 1 on success to reach a free agent
4983 * \retval 0 on failure to get agent.
4984 */
4985 static int ring_entry(struct queue_ent *qe, struct callattempt *tmp, int *busies)
4986 {
4987 int res;
4988 int status;
4989 char tech[256];
4990 char *location;
4991 struct ast_format_cap *nativeformats;
4992 RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
4993
4994 /* on entry here, we know that tmp->chan == NULL */
4995 if (!can_ring_entry(qe, tmp)) {
4996 tmp->stillgoing = 0;
4997 ++*busies;
4998 return 0;
4999 }
5000
5001 ast_copy_string(tech, tmp->interface, sizeof(tech));
5002 if ((location = strchr(tech, '/'))) {
5003 *location++ = '\0';
5004 } else {
5005 location = "";
5006 }
5007
5008 ast_channel_lock(qe->chan);
5009 nativeformats = ao2_bump(ast_channel_nativeformats(qe->chan));
5010 ast_channel_unlock(qe->chan);
5011
5012 /* Request the peer */
5013 tmp->chan = ast_request(tech, nativeformats, NULL, qe->chan, location, &status);
5014 ao2_cleanup(nativeformats);
5015 if (!tmp->chan) { /* If we can't, just go on to the next call */
5016 ao2_lock(qe->parent);
5017 qe->parent->rrpos++;
5018 qe->linpos++;
5019 ao2_unlock(qe->parent);
5020
5021 pending_members_remove(tmp->member);
5022
5023 publish_dial_end_event(qe->chan, tmp, NULL, "BUSY");
5024 tmp->stillgoing = 0;
5025 ++*busies;
5026 return 0;
5027 }
5028
5029 ast_channel_lock_both(tmp->chan, qe->chan);
5030
5031 ast_channel_req_accountcodes_precious(tmp->chan, qe->chan,
5032 AST_CHANNEL_REQUESTOR_BRIDGE_PEER);
5033 if (qe->cancel_answered_elsewhere) {
5034 ast_channel_hangupcause_set(tmp->chan, AST_CAUSE_ANSWERED_ELSEWHERE);
5035 }
5036 ast_channel_appl_set(tmp->chan, "AppQueue");
5037 ast_channel_data_set(tmp->chan, "(Outgoing Line)");
5038 memset(ast_channel_whentohangup(tmp->chan), 0, sizeof(*ast_channel_whentohangup(tmp->chan)));
5039
5040 /* If the new channel has no callerid, try to guess what it should be */
5041 if (!ast_channel_caller(tmp->chan)->id.number.valid) {
5042 if (ast_channel_connected(qe->chan)->id.number.valid) {
5043 struct ast_party_caller caller;
5044
5045 ast_party_caller_set_init(&caller, ast_channel_caller(tmp->chan));
5046 caller.id = ast_channel_connected(qe->chan)->id;
5047 caller.ani = ast_channel_connected(qe->chan)->ani;
5048 ast_channel_set_caller_event(tmp->chan, &caller, NULL);
5049 } else if (!ast_strlen_zero(ast_channel_dialed(qe->chan)->number.str)) {
5050 ast_set_callerid(tmp->chan, ast_channel_dialed(qe->chan)->number.str, NULL, NULL);
5051 } else if (!ast_strlen_zero(ast_channel_exten(qe->chan))) {
5052 ast_set_callerid(tmp->chan, ast_channel_exten(qe->chan), NULL, NULL);
5053 }
5054 tmp->dial_callerid_absent = 1;
5055 }
5056
5057 ast_party_redirecting_copy(ast_channel_redirecting(tmp->chan), ast_channel_redirecting(qe->chan));
5058
5059 ast_channel_dialed(tmp->chan)->transit_network_select = ast_channel_dialed(qe->chan)->transit_network_select;
5060
5061 ast_connected_line_copy_from_caller(ast_channel_connected(tmp->chan), ast_channel_caller(qe->chan));
5062
5063 /* Inherit specially named variables from parent channel */
5064 ast_channel_inherit_variables(qe->chan, tmp->chan);
5065 ast_channel_datastore_inherit(qe->chan, tmp->chan);
5066 ast_max_forwards_decrement(tmp->chan);
5067
5068 /* Presense of ADSI CPE on outgoing channel follows ours */
5069 ast_channel_adsicpe_set(tmp->chan, ast_channel_adsicpe(qe->chan));
5070
5071 /* Inherit context and extension */
5072 ast_channel_dialcontext_set(tmp->chan, ast_channel_context(qe->chan));
5073 ast_channel_exten_set(tmp->chan, ast_channel_exten(qe->chan));
5074
5075 /* Save the original channel name to detect call pickup masquerading in. */
5076 tmp->orig_chan_name = ast_strdup(ast_channel_name(tmp->chan));
5077
5078 ast_channel_unlock(tmp->chan);
5079 ast_channel_unlock(qe->chan);
5080
5081 /* location is tmp->interface where tech/ has been stripped, so it follow the same syntax as DIALEDPEERNUMBER in app_dial.c */
5082 pbx_builtin_setvar_helper(tmp->chan, "DIALEDPEERNUMBER", strlen(location) ? location : tmp->interface);
5083
5084 /* PREDIAL: Run gosub on the callee's channel */
5085 if (qe->predial_callee) {
5086 ast_pre_call(tmp->chan, qe->predial_callee);
5087 }
5088
5089 /* Place the call, but don't wait on the answer */
5090 if ((res = ast_call(tmp->chan, location, 0))) {
5091 /* Again, keep going even if there's an error */
5092 ast_verb(3, "Couldn't call %s\n", tmp->interface);
5093 do_hang(tmp);
5094 ++*busies;
5095 return 0;
5096 }
5097
5098 ast_channel_lock_both(tmp->chan, qe->chan);
5099
5100 blob = ast_json_pack("{s: s, s: s, s: s}",
5101 "Queue", qe->parent->name,
5102 "Interface", tmp->interface,
5103 "MemberName", tmp->member->membername);
5104 queue_publish_multi_channel_blob(qe->chan, tmp->chan, queue_agent_called_type(), blob);
5105
5106 ast_channel_publish_dial(qe->chan, tmp->chan, tmp->interface, NULL);
5107
5108 ast_channel_unlock(tmp->chan);
5109 ast_channel_unlock(qe->chan);
5110
5111 ast_verb(3, "Called %s\n", tmp->interface);
5112
5113 return 1;
5114 }
5115
5116 /*! \brief find the entry with the best metric, or NULL */
5117 static struct callattempt *find_best(struct callattempt *outgoing)
5118 {
5119 struct callattempt *best = NULL, *cur;
5120
5121 for (cur = outgoing; cur; cur = cur->q_next) {
5122 if (cur->stillgoing && /* Not already done */
5123 !cur->chan && /* Isn't already going */
5124 (!best || cur->metric < best->metric)) { /* We haven't found one yet, or it's better */
5125 best = cur;
5126 }
5127 }
5128
5129 return best;
5130 }
5131
5132 /*!
5133 * \brief Place a call to a queue member.
5134 *
5135 * Once metrics have been calculated for each member, this function is used
5136 * to place a call to the appropriate member (or members). The low-level
5137 * channel-handling and error detection is handled in ring_entry
5138 *
5139 * \retval 1 if a member was called successfully
5140 * \retval 0 otherwise
5141 */
5142 static int ring_one(struct queue_ent *qe, struct callattempt *outgoing, int *busies)
5143 {
5144 int ret = 0;
5145 struct callattempt *cur;
5146
5147 if (qe->predial_callee) {
5148 ast_autoservice_start(qe->chan);
5149 for (cur = outgoing; cur; cur = cur->q_next) {
5150 if (cur->stillgoing && cur->chan) {
5151 ast_autoservice_start(cur->chan);
5152 }
5153 }
5154 }
5155
5156 while (ret == 0) {
5157 struct callattempt *best = find_best(outgoing);
5158 if (!best) {
5159 ast_debug(1, "Nobody left to try ringing in queue\n");
5160 break;
5161 }
5162 if (qe->parent->strategy == QUEUE_STRATEGY_RINGALL) {
5163 /* Ring everyone who shares this best metric (for ringall) */
5164 for (cur = outgoing; cur; cur = cur->q_next) {
5165 if (cur->stillgoing && !cur->chan && cur->metric <= best->metric) {
5166 ast_debug(1, "(Parallel) Trying '%s' with metric %d\n", cur->interface, cur->metric);
5167 ret |= ring_entry(qe, cur, busies);
5168 if (qe->predial_callee && cur->chan) {
5169 ast_autoservice_start(cur->chan);
5170 }
5171 }
5172 }
5173 } else {
5174 /* Ring just the best channel */
5175 ast_debug(1, "Trying '%s' with metric %d\n", best->interface, best->metric);
5176 ret = ring_entry(qe, best, busies);
5177 if (qe->predial_callee && best->chan) {
5178 ast_autoservice_start(best->chan);
5179 }
5180 }
5181
5182 /* If we have timed out, break out */
5183 if (qe->expire && (time(NULL) >= qe->expire)) {
5184 ast_debug(1, "Queue timed out while ringing members.\n");
5185 ret = 0;
5186 break;
5187 }
5188 }
5189 if (qe->predial_callee) {
5190 for (cur = outgoing; cur; cur = cur->q_next) {
5191 if (cur->stillgoing && cur->chan) {
5192 ast_autoservice_stop(cur->chan);
5193 }
5194 }
5195 ast_autoservice_stop(qe->chan);
5196 }
5197
5198 return ret;
5199 }
5200
5201 /*! \brief Search for best metric and add to Round Robbin queue */
5202 static int store_next_rr(struct queue_ent *qe, struct callattempt *outgoing)
5203 {
5204 struct callattempt *best = find_best(outgoing);
5205
5206 if (best) {
5207 /* Ring just the best channel */
5208 ast_debug(1, "Next is '%s' with metric %d\n", best->interface, best->metric);
5209 qe->parent->rrpos = best->metric % 1000;
5210 } else {
5211 /* Just increment rrpos */
5212 if (qe->parent->wrapped) {
5213 /* No more channels, start over */
5214 qe->parent->rrpos = 0;
5215 } else {
5216 /* Prioritize next entry */
5217 qe->parent->rrpos++;
5218 }
5219 }
5220 qe->parent->wrapped = 0;
5221
5222 return 0;
5223 }
5224
5225 /*! \brief Search for best metric and add to Linear queue */
5226 static int store_next_lin(struct queue_ent *qe, struct callattempt *outgoing)
5227 {
5228 struct callattempt *best = find_best(outgoing);
5229
5230 if (best) {
5231 /* Ring just the best channel */
5232 ast_debug(1, "Next is '%s' with metric %d\n", best->interface, best->metric);
5233 qe->linpos = best->metric % 1000;
5234 } else {
5235 /* Just increment rrpos */
5236 if (qe->linwrapped) {
5237 /* No more channels, start over */
5238 qe->linpos = 0;
5239 } else {
5240 /* Prioritize next entry */
5241 qe->linpos++;
5242 }
5243 }
5244 qe->linwrapped = 0;
5245
5246 return 0;
5247 }
5248
5249 /*! \brief Playback announcement to queued members if period has elapsed */
5250 static int say_periodic_announcement(struct queue_ent *qe, int ringing)
5251 {
5252 int res = 0;
5253 time_t now;
5254
5255 /* Get the current time */
5256 time(&now);
5257
5258 /* Check to see if it is time to announce */
5259 if ((now - qe->last_periodic_announce_time) < qe->parent->periodicannouncefrequency) {
5260 return 0;
5261 }
5262
5263 /* Stop the music on hold so we can play our own file */
5264 if (ringing) {
5265 ast_indicate(qe->chan,-1);
5266 } else {
5267 ast_moh_stop(qe->chan);
5268 }
5269
5270 ast_verb(3, "Playing periodic announcement\n");
5271
5272 if (qe->parent->randomperiodicannounce && qe->parent->numperiodicannounce) {
5273 qe->last_periodic_announce_sound = ((unsigned long) ast_random()) % qe->parent->numperiodicannounce;
5274 } else if (qe->last_periodic_announce_sound >= qe->parent->numperiodicannounce ||
5275 ast_str_strlen(qe->parent->sound_periodicannounce[qe->last_periodic_announce_sound]) == 0) {
5276 qe->last_periodic_announce_sound = 0;
5277 }
5278
5279 /* play the announcement */
5280 res = play_file(qe->chan, ast_str_buffer(qe->parent->sound_periodicannounce[qe->last_periodic_announce_sound]));
5281
5282 if (res > 0 && !valid_exit(qe, res)) {
5283 res = 0;
5284 }
5285
5286 /* Resume Music on Hold if the caller is going to stay in the queue */
5287 if (!res) {
5288 if (ringing) {
5289 ast_indicate(qe->chan, AST_CONTROL_RINGING);
5290 } else {
5291 ast_moh_start(qe->chan, qe->moh, NULL);
5292 }
5293 }
5294
5295 /* update last_periodic_announce_time */
5296 if (qe->parent->relativeperiodicannounce) {
5297 time(&qe->last_periodic_announce_time);
5298 } else {
5299 qe->last_periodic_announce_time = now;
5300 }
5301
5302 /* Update the current periodic announcement to the next announcement */
5303 if (!qe->parent->randomperiodicannounce) {
5304 qe->last_periodic_announce_sound++;
5305 }
5306
5307 return res;
5308 }
5309
5310 /*! \brief Record that a caller gave up on waiting in queue */
5311 static void record_abandoned(struct queue_ent *qe)
5312 {
5313 int callabandonedinsl = 0;
5314 time_t now;
5315
5316 RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
5317
5318 pbx_builtin_setvar_helper(qe->chan, "ABANDONED", "TRUE");
5319
5320 set_queue_variables(qe->parent, qe->chan);
5321 ao2_lock(qe->parent);
5322 blob = ast_json_pack("{s: s, s: i, s: i, s: i}",
5323 "Queue", qe->parent->name,
5324 "Position", qe->pos,
5325 "OriginalPosition", qe->opos,
5326 "HoldTime", (int)(time(NULL) - qe->start));
5327
5328
5329 time(&now);
5330 callabandonedinsl = ((now - qe->start) <= qe->parent->servicelevel);
5331 if (callabandonedinsl) {
5332 qe->parent->callsabandonedinsl++;
5333 }
5334
5335 qe->parent->callsabandoned++;
5336 ao2_unlock(qe->parent);
5337
5338 ast_channel_publish_cached_blob(qe->chan, queue_caller_abandon_type(), blob);
5339 }
5340
5341 /*! \brief RNA == Ring No Answer. Common code that is executed when we try a queue member and they don't answer. */
5342 static void rna(int rnatime, struct queue_ent *qe, struct ast_channel *peer, char *interface, char *membername, int autopause)
5343 {
5344 RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
5345
5346 ast_verb(3, "Nobody picked up in %d ms\n", rnatime);
5347
5348 /* Stop ringing, and resume MOH if specified */
5349 if (qe->ring_when_ringing) {
5350 ast_indicate(qe->chan, -1);
5351 ast_moh_start(qe->chan, qe->moh, NULL);
5352 }
5353
5354 blob = ast_json_pack("{s: s, s: s, s: s, s: i}",
5355 "Queue", qe->parent->name,
5356 "Interface", interface,
5357 "MemberName", membername,
5358 "RingTime", rnatime);
5359 queue_publish_multi_channel_blob(qe->chan, peer, queue_agent_ringnoanswer_type(), blob);
5360
5361 ast_queue_log(qe->parent->name, ast_channel_uniqueid(qe->chan), membername, "RINGNOANSWER", "%d", rnatime);
5362 if (qe->parent->autopause != QUEUE_AUTOPAUSE_OFF && autopause) {
5363 if (qe->parent->autopausedelay > 0) {
5364 struct member *mem;
5365 ao2_lock(qe->parent);
5366 if ((mem = interface_exists(qe->parent, interface))) {
5367 time_t idletime = time(&idletime)-mem->lastcall;
5368 if ((mem->lastcall != 0) && (qe->parent->autopausedelay > idletime)) {
5369 ao2_unlock(qe->parent);
5370 ao2_ref(mem, -1);
5371 return;
5372 }
5373 ao2_ref(mem, -1);
5374 }
5375 ao2_unlock(qe->parent);
5376 }
5377 if (qe->parent->autopause == QUEUE_AUTOPAUSE_ON) {
5378 if (!set_member_paused(qe->parent->name, interface, "Auto-Pause", 1)) {
5379 ast_verb(3, "Auto-Pausing Queue Member %s in queue %s since they failed to answer.\n",
5380 interface, qe->parent->name);
5381 } else {
5382 ast_verb(3, "Failed to pause Queue Member %s in queue %s!\n", interface, qe->parent->name);
5383 }
5384 } else {
5385 /* If queue autopause is mode all, just don't send any queue to stop.
5386 * the function will stop in all queues */
5387 if (!set_member_paused("", interface, "Auto-Pause", 1)) {
5388 ast_verb(3, "Auto-Pausing Queue Member %s in all queues since they failed to answer on queue %s.\n",
5389 interface, qe->parent->name);
5390 } else {
5391 ast_verb(3, "Failed to pause Queue Member %s in all queues!\n", interface);
5392 }
5393 }
5394 }
5395 return;
5396 }
5397
5398 /*!
5399 * \internal
5400 * \brief Update connected line on chan from peer.
5401 * \since 13.6.0
5402 *
5403 * \param chan Channel to get connected line updated.
5404 * \param peer Channel providing connected line information.
5405 * \param is_caller Non-zero if chan is the calling channel.
5406 */
5407 static void update_connected_line_from_peer(struct ast_channel *chan, struct ast_channel *peer, int is_caller)
5408 {
5409 struct ast_party_connected_line connected_caller;
5410
5411 ast_party_connected_line_init(&connected_caller);
5412
5413 ast_channel_lock(peer);
5414 ast_connected_line_copy_from_caller(&connected_caller, ast_channel_caller(peer));
5415 ast_channel_unlock(peer);
5416 connected_caller.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
5417 if (ast_channel_connected_line_sub(peer, chan, &connected_caller, 0)) {
5418 ast_channel_update_connected_line(chan, &connected_caller, NULL);
5419 }
5420 ast_party_connected_line_free(&connected_caller);
5421 }
5422
5423 #define AST_MAX_WATCHERS 256
5424 /*!
5425 * \brief Wait for a member to answer the call
5426 *
5427 * \param[in] qe the queue_ent corresponding to the caller in the queue
5428 * \param[in] outgoing the list of callattempts. Relevant ones will have their chan and stillgoing parameters non-zero
5429 * \param[in] to the amount of time (in milliseconds) to wait for a response
5430 * \param[out] digit if a user presses a digit to exit the queue, this is the digit the caller pressed
5431 * \param[in] prebusies number of busy members calculated prior to calling wait_for_answer
5432 * \param[in] caller_disconnect if the 'H' option is used when calling Queue(), this is used to detect if the caller pressed * to disconnect the call
5433 * \param[in] forwardsallowed used to detect if we should allow call forwarding, based on the 'i' option to Queue()
5434 *
5435 * \todo eventually all call forward logic should be integrated into and replaced by ast_call_forward()
5436 */
5437 static struct callattempt *wait_for_answer(struct queue_ent *qe, struct callattempt *outgoing, int *to, char *digit, int prebusies, int caller_disconnect, int forwardsallowed)
5438 {
5439 const char *queue = qe->parent->name;
5440 struct callattempt *o, *start = NULL, *prev = NULL;
5441 int status;
5442 int numbusies = prebusies;
5443 int numnochan = 0;
5444 int stillgoing = 0;
5445 int orig = *to;
5446 struct ast_frame *f;
5447 struct callattempt *peer = NULL;
5448 struct ast_channel *winner;
5449 struct ast_channel *in = qe->chan;
5450 char on[80] = "";
5451 char membername[80] = "";
5452 long starttime = 0;
5453 long endtime = 0;
5454 char *inchan_name;
5455 struct timeval start_time_tv = ast_tvnow();
5456 int canceled_by_caller = 0; /* 1 when caller hangs up or press digit or press * */
5457
5458 ast_channel_lock(qe->chan);
5459 inchan_name = ast_strdupa(ast_channel_name(qe->chan));
5460 ast_channel_unlock(qe->chan);
5461
5462 starttime = (long) time(NULL);
5463
5464 while ((*to = ast_remaining_ms(start_time_tv, orig)) && !peer) {
5465 int numlines, retry, pos = 1;
5466 struct ast_channel *watchers[AST_MAX_WATCHERS];
5467 watchers[0] = in;
5468 start = NULL;
5469
5470 for (retry = 0; retry < 2; retry++) {
5471 numlines = 0;
5472 for (o = outgoing; o; o = o->q_next) { /* Keep track of important channels */
5473 if (o->stillgoing) { /* Keep track of important channels */
5474 stillgoing = 1;
5475 if (o->chan) {
5476 if (pos < AST_MAX_WATCHERS) {
5477 watchers[pos++] = o->chan;
5478 }
5479 if (!start) {
5480 start = o;
5481 } else {
5482 prev->call_next = o;
5483 }
5484 prev = o;
5485 }
5486 } else if (prev) {
5487 prev->call_next = NULL;
5488 }
5489 numlines++;
5490 }
5491 if (pos > 1 /* found */ || !stillgoing /* nobody listening */ ||
5492 (qe->parent->strategy != QUEUE_STRATEGY_RINGALL) /* ring would not be delivered */) {
5493 break;
5494 }
5495 /* On "ringall" strategy we only move to the next penalty level
5496 when *all* ringing phones are done in the current penalty level */
5497 ring_one(qe, outgoing, &numbusies);
5498 /* and retry... */
5499 }
5500 if (pos == 1 /* not found */) {
5501 if (numlines == (numbusies + numnochan)) {
5502 ast_debug(1, "Everyone is busy at this time\n");
5503 } else {
5504 ast_debug(3, "No one is answering queue '%s' (%d numlines / %d busies / %d failed channels)\n", queue, numlines, numbusies, numnochan);
5505 }
5506 *to = 0;
5507 return NULL;
5508 }
5509
5510 /* Poll for events from both the incoming channel as well as any outgoing channels */
5511 winner = ast_waitfor_n(watchers, pos, to);
5512
5513 /* Service all of the outgoing channels */
5514 for (o = start; o; o = o->call_next) {
5515 /* We go with a fixed buffer here instead of using ast_strdupa. Using
5516 * ast_strdupa in a loop like this one can cause a stack overflow
5517 */
5518 char ochan_name[AST_CHANNEL_NAME];
5519
5520 if (o->chan) {
5521 ast_channel_lock(o->chan);
5522 ast_copy_string(ochan_name, ast_channel_name(o->chan), sizeof(ochan_name));
5523 ast_channel_unlock(o->chan);
5524 }
5525 if (o->stillgoing && (o->chan) && (ast_channel_state(o->chan) == AST_STATE_UP)) {
5526 if (!peer) {
5527 ast_verb(3, "%s answered %s\n", ochan_name, inchan_name);
5528 if (o->orig_chan_name
5529 && strcmp(o->orig_chan_name, ochan_name)) {
5530 /*
5531 * The channel name changed so we must generate COLP update.
5532 * Likely because a call pickup channel masqueraded in.
5533 */
5534 update_connected_line_from_peer(in, o->chan, 1);
5535 } else if (!o->block_connected_update) {
5536 if (o->pending_connected_update) {
5537 if (ast_channel_connected_line_sub(o->chan, in, &o->connected, 0)) {
5538 ast_channel_update_connected_line(in, &o->connected, NULL);
5539 }
5540 } else if (!o->dial_callerid_absent) {
5541 update_connected_line_from_peer(in, o->chan, 1);
5542 }
5543 }
5544 if (o->aoc_s_rate_list) {
5545 size_t encoded_size;
5546 struct ast_aoc_encoded *encoded;
5547 if ((encoded = ast_aoc_encode(o->aoc_s_rate_list, &encoded_size, o->chan))) {
5548 ast_indicate_data(in, AST_CONTROL_AOC, encoded, encoded_size);
5549 ast_aoc_destroy_encoded(encoded);
5550 }
5551 }
5552 peer = o;
5553 }
5554 } else if (o->chan && (o->chan == winner)) {
5555
5556 ast_copy_string(on, o->member->interface, sizeof(on));
5557 ast_copy_string(membername, o->member->membername, sizeof(membername));
5558
5559 /* Before processing channel, go ahead and check for forwarding */
5560 if (!ast_strlen_zero(ast_channel_call_forward(o->chan)) && !forwardsallowed) {
5561 ast_verb(3, "Forwarding %s to '%s' prevented.\n", inchan_name, ast_channel_call_forward(o->chan));
5562 ast_channel_publish_dial_forward(qe->chan, o->chan, NULL, NULL,
5563 "CANCEL", ast_channel_call_forward(o->chan));
5564 numnochan++;
5565 do_hang(o);
5566 winner = NULL;
5567 continue;
5568 } else if (!ast_strlen_zero(ast_channel_call_forward(o->chan))) {
5569 struct ast_channel *original = o->chan;
5570 char forwarder[AST_CHANNEL_NAME];
5571 char tmpchan[256];
5572 char *stuff;
5573 char *tech;
5574 int failed = 0;
5575
5576 ast_copy_string(tmpchan, ast_channel_call_forward(o->chan), sizeof(tmpchan));
5577 ast_copy_string(forwarder, ast_channel_name(o->chan), sizeof(forwarder));
5578 if ((stuff = strchr(tmpchan, '/'))) {
5579 *stuff++ = '\0';
5580 tech = tmpchan;
5581 } else {
5582 const char *forward_context;
5583 ast_channel_lock(o->chan);
5584 forward_context = pbx_builtin_getvar_helper(o->chan, "FORWARD_CONTEXT");
5585 snprintf(tmpchan, sizeof(tmpchan), "%s@%s", ast_channel_call_forward(o->chan), forward_context ? forward_context : ast_channel_context(o->chan));
5586 ast_channel_unlock(o->chan);
5587 stuff = tmpchan;
5588 tech = "Local";
5589 }
5590 if (!strcasecmp(tech, "Local")) {
5591 /*
5592 * Drop the connected line update block for local channels since
5593 * this is going to run dialplan and the user can change his
5594 * mind about what connected line information he wants to send.
5595 */
5596 o->block_connected_update = 0;
5597 }
5598
5599 ast_verb(3, "Now forwarding %s to '%s/%s' (thanks to %s)\n", inchan_name, tech, stuff, ochan_name);
5600 /* Setup parameters */
5601 o->chan = ast_request(tech, ast_channel_nativeformats(in), NULL, in, stuff, &status);
5602 if (!o->chan) {
5603 ast_log(LOG_NOTICE,
5604 "Forwarding failed to create channel to dial '%s/%s'\n",
5605 tech, stuff);
5606 o->stillgoing = 0;
5607 numnochan++;
5608 } else {
5609 ast_channel_lock_both(o->chan, original);
5610 ast_party_redirecting_copy(ast_channel_redirecting(o->chan),
5611 ast_channel_redirecting(original));
5612 ast_channel_unlock(o->chan);
5613 ast_channel_unlock(original);
5614
5615 ast_channel_lock_both(o->chan, in);
5616 ast_channel_inherit_variables(in, o->chan);
5617 ast_channel_datastore_inherit(in, o->chan);
5618 pbx_builtin_setvar_helper(o->chan, "FORWARDERNAME", forwarder);
5619 ast_max_forwards_decrement(o->chan);
5620
5621 if (o->pending_connected_update) {
5622 /*
5623 * Re-seed the callattempt's connected line information with
5624 * previously acquired connected line info from the queued
5625 * channel. The previously acquired connected line info could
5626 * have been set through the CONNECTED_LINE dialplan function.
5627 */
5628 o->pending_connected_update = 0;
5629 ast_party_connected_line_copy(&o->connected, ast_channel_connected(in));
5630 }
5631
5632 ast_free(o->orig_chan_name);
5633 o->orig_chan_name = ast_strdup(ast_channel_name(o->chan));
5634
5635 ast_channel_req_accountcodes(o->chan, in, AST_CHANNEL_REQUESTOR_BRIDGE_PEER);
5636
5637 if (!ast_channel_redirecting(o->chan)->from.number.valid
5638 || ast_strlen_zero(ast_channel_redirecting(o->chan)->from.number.str)) {
5639 /*
5640 * The call was not previously redirected so it is
5641 * now redirected from this number.
5642 */
5643 ast_party_number_free(&ast_channel_redirecting(o->chan)->from.number);
5644 ast_party_number_init(&ast_channel_redirecting(o->chan)->from.number);
5645 ast_channel_redirecting(o->chan)->from.number.valid = 1;
5646 ast_channel_redirecting(o->chan)->from.number.str =
5647 ast_strdup(ast_channel_exten(in));
5648 }
5649
5650 ast_channel_dialed(o->chan)->transit_network_select = ast_channel_dialed(in)->transit_network_select;
5651
5652 o->dial_callerid_absent = !ast_channel_caller(o->chan)->id.number.valid
5653 || ast_strlen_zero(ast_channel_caller(o->chan)->id.number.str);
5654 ast_connected_line_copy_from_caller(ast_channel_connected(o->chan),
5655 ast_channel_caller(in));
5656
5657 ast_channel_unlock(in);
5658 if (qe->parent->strategy != QUEUE_STRATEGY_RINGALL
5659 && !o->block_connected_update) {
5660 struct ast_party_redirecting redirecting;
5661
5662 /*
5663 * Redirecting updates to the caller make sense only on single
5664 * call at a time strategies.
5665 *
5666 * Need to re-evaluate if calling unlock is still required as we no longer
5667 * use macro.
5668 */
5669 ast_party_redirecting_init(&redirecting);
5670 ast_party_redirecting_copy(&redirecting, ast_channel_redirecting(o->chan));
5671 ast_channel_unlock(o->chan);
5672 if (ast_channel_redirecting_sub(o->chan, in, &redirecting, 0)) {
5673 ast_channel_update_redirecting(in, &redirecting, NULL);
5674 }
5675 ast_party_redirecting_free(&redirecting);
5676 } else {
5677 ast_channel_unlock(o->chan);
5678 }
5679
5680 if (ast_call(o->chan, stuff, 0)) {
5681 ast_log(LOG_NOTICE, "Forwarding failed to dial '%s/%s'\n",
5682 tech, stuff);
5683 failed = 1;
5684 }
5685 }
5686
5687 ast_channel_publish_dial_forward(qe->chan, original, o->chan, NULL,
5688 "CANCEL", ast_channel_call_forward(original));
5689 if (o->chan) {
5690 ast_channel_publish_dial(qe->chan, o->chan, stuff, NULL);
5691 }
5692
5693 if (failed) {
5694 do_hang(o);
5695 numnochan++;
5696 }
5697
5698 /* Hangup the original channel now, in case we needed it */
5699 ast_hangup(winner);
5700 continue;
5701 }
5702 f = ast_read(winner);
5703 if (f) {
5704 if (f->frametype == AST_FRAME_CONTROL) {
5705 switch (f->subclass.integer) {
5706 case AST_CONTROL_ANSWER:
5707 /* This is our guy if someone answered. */
5708 if (!peer) {
5709 ast_verb(3, "%s answered %s\n", ochan_name, inchan_name);
5710 ast_channel_publish_dial(qe->chan, o->chan, on, "ANSWER");
5711 publish_dial_end_event(qe->chan, outgoing, o->chan, "CANCEL");
5712 if (o->orig_chan_name
5713 && strcmp(o->orig_chan_name, ochan_name)) {
5714 /*
5715 * The channel name changed so we must generate COLP update.
5716 * Likely because a call pickup channel masqueraded in.
5717 */
5718 update_connected_line_from_peer(in, o->chan, 1);
5719 } else if (!o->block_connected_update) {
5720 if (o->pending_connected_update) {
5721 if (ast_channel_connected_line_sub(o->chan, in, &o->connected, 0)) {
5722 ast_channel_update_connected_line(in, &o->connected, NULL);
5723 }
5724 } else if (!o->dial_callerid_absent) {
5725 update_connected_line_from_peer(in, o->chan, 1);
5726 }
5727 }
5728 if (o->aoc_s_rate_list) {
5729 size_t encoded_size;
5730 struct ast_aoc_encoded *encoded;
5731 if ((encoded = ast_aoc_encode(o->aoc_s_rate_list, &encoded_size, o->chan))) {
5732 ast_indicate_data(in, AST_CONTROL_AOC, encoded, encoded_size);
5733 ast_aoc_destroy_encoded(encoded);
5734 }
5735 }
5736 peer = o;
5737 }
5738 break;
5739 case AST_CONTROL_BUSY:
5740 ast_verb(3, "%s is busy\n", ochan_name);
5741 ast_channel_publish_dial(qe->chan, o->chan, on, "BUSY");
5742 endtime = (long) time(NULL);
5743 endtime -= starttime;
5744 rna(endtime * 1000, qe, o->chan, on, membername, qe->parent->autopausebusy);
5745 do_hang(o);
5746 if (qe->parent->strategy != QUEUE_STRATEGY_RINGALL) {
5747 if (qe->parent->timeoutrestart) {
5748 start_time_tv = ast_tvnow();
5749 }
5750 /* Have enough time for a queue member to answer? */
5751 if (ast_remaining_ms(start_time_tv, orig) > 500) {
5752 ring_one(qe, outgoing, &numbusies);
5753 starttime = (long) time(NULL);
5754 }
5755 }
5756 numbusies++;
5757 break;
5758 case AST_CONTROL_CONGESTION:
5759 ast_verb(3, "%s is circuit-busy\n", ochan_name);
5760 ast_channel_publish_dial(qe->chan, o->chan, on, "CONGESTION");
5761 endtime = (long) time(NULL);
5762 endtime -= starttime;
5763 rna(endtime * 1000, qe, o->chan, on, membername, qe->parent->autopauseunavail);
5764 do_hang(o);
5765 if (qe->parent->strategy != QUEUE_STRATEGY_RINGALL) {
5766 if (qe->parent->timeoutrestart) {
5767 start_time_tv = ast_tvnow();
5768 }
5769 if (ast_remaining_ms(start_time_tv, orig) > 500) {
5770 ring_one(qe, outgoing, &numbusies);
5771 starttime = (long) time(NULL);
5772 }
5773 }
5774 numbusies++;
5775 break;
5776 case AST_CONTROL_RINGING:
5777 ast_verb(3, "%s is ringing\n", ochan_name);
5778
5779 ast_channel_publish_dial(qe->chan, o->chan, on, "RINGING");
5780
5781 /* Start ring indication when the channel is ringing, if specified */
5782 if (qe->ring_when_ringing) {
5783 ast_moh_stop(qe->chan);
5784 ast_indicate(qe->chan, AST_CONTROL_RINGING);
5785 }
5786 break;
5787 case AST_CONTROL_OFFHOOK:
5788 /* Ignore going off hook */
5789 break;
5790 case AST_CONTROL_CONNECTED_LINE:
5791 if (o->block_connected_update) {
5792 ast_verb(3, "Connected line update to %s prevented.\n", inchan_name);
5793 break;
5794 }
5795 if (qe->parent->strategy == QUEUE_STRATEGY_RINGALL) {
5796 struct ast_party_connected_line connected;
5797
5798 ast_verb(3, "%s connected line has changed. Saving it until answer for %s\n", ochan_name, inchan_name);
5799 ast_party_connected_line_set_init(&connected, &o->connected);
5800 ast_connected_line_parse_data(f->data.ptr, f->datalen, &connected);
5801 ast_party_connected_line_set(&o->connected, &connected, NULL);
5802 ast_party_connected_line_free(&connected);
5803 o->pending_connected_update = 1;
5804 break;
5805 }
5806
5807 /*
5808 * Prevent using the CallerID from the outgoing channel since we
5809 * got a connected line update from it.
5810 */
5811 o->dial_callerid_absent = 1;
5812
5813 if (ast_channel_connected_line_sub(o->chan, in, f, 1)) {
5814 ast_indicate_data(in, AST_CONTROL_CONNECTED_LINE, f->data.ptr, f->datalen);
5815 }
5816 break;
5817 case AST_CONTROL_AOC:
5818 {
5819 struct ast_aoc_decoded *decoded = ast_aoc_decode(f->data.ptr, f->datalen, o->chan);
5820 if (decoded && (ast_aoc_get_msg_type(decoded) == AST_AOC_S)) {
5821 ast_aoc_destroy_decoded(o->aoc_s_rate_list);
5822 o->aoc_s_rate_list = decoded;
5823 } else {
5824 ast_aoc_destroy_decoded(decoded);
5825 }
5826 }
5827 break;
5828 case AST_CONTROL_REDIRECTING:
5829 if (qe->parent->strategy == QUEUE_STRATEGY_RINGALL) {
5830 /*
5831 * Redirecting updates to the caller make sense only on single
5832 * call at a time strategies.
5833 */
5834 break;
5835 }
5836 if (o->block_connected_update) {
5837 ast_verb(3, "Redirecting update to %s prevented\n",
5838 inchan_name);
5839 break;
5840 }
5841 ast_verb(3, "%s redirecting info has changed, passing it to %s\n",
5842 ochan_name, inchan_name);
5843 if (ast_channel_redirecting_sub(o->chan, in, f, 1)) {
5844 ast_indicate_data(in, AST_CONTROL_REDIRECTING, f->data.ptr, f->datalen);
5845 }
5846 break;
5847 case AST_CONTROL_PVT_CAUSE_CODE:
5848 ast_indicate_data(in, AST_CONTROL_PVT_CAUSE_CODE, f->data.ptr, f->datalen);
5849 break;
5850 default:
5851 ast_debug(1, "Dunno what to do with control type %d\n", f->subclass.integer);
5852 break;
5853 }
5854 }
5855 ast_frfree(f);
5856 } else { /* ast_read() returned NULL */
5857 endtime = (long) time(NULL) - starttime;
5858 ast_channel_publish_dial(qe->chan, o->chan, on, "NOANSWER");
5859 rna(endtime * 1000, qe, o->chan, on, membername, 1);
5860 do_hang(o);
5861 if (qe->parent->strategy != QUEUE_STRATEGY_RINGALL) {
5862 if (qe->parent->timeoutrestart) {
5863 start_time_tv = ast_tvnow();
5864 }
5865 if (ast_remaining_ms(start_time_tv, orig) > 500) {
5866 ring_one(qe, outgoing, &numbusies);
5867 starttime = (long) time(NULL);
5868 }
5869 }
5870 }
5871 }
5872 }
5873
5874 /* If we received an event from the caller, deal with it. */
5875 if (winner == in) {
5876 f = ast_read(in);
5877 if (!f || ((f->frametype == AST_FRAME_CONTROL) && (f->subclass.integer == AST_CONTROL_HANGUP))) {
5878 /* Got hung up */
5879 *to = -1;
5880 if (f) {
5881 if (f->data.uint32) {
5882 ast_channel_hangupcause_set(in, f->data.uint32);
5883 }
5884 ast_frfree(f);
5885 }
5886 canceled_by_caller = 1;
5887 } else if ((f->frametype == AST_FRAME_DTMF) && caller_disconnect && (f->subclass.integer == '*')) {
5888 ast_verb(3, "User hit %c to disconnect call.\n", f->subclass.integer);
5889 *to = 0;
5890 ast_frfree(f);
5891 canceled_by_caller = 1;
5892 } else if ((f->frametype == AST_FRAME_DTMF) && valid_exit(qe, f->subclass.integer)) {
5893 ast_verb(3, "User pressed digit: %c\n", f->subclass.integer);
5894 *to = 0;
5895 *digit = f->subclass.integer;
5896 ast_frfree(f);
5897 canceled_by_caller = 1;
5898 }
5899 /* When caller hung up or pressed * or digit. */
5900 if (canceled_by_caller) {
5901 publish_dial_end_event(in, outgoing, NULL, "CANCEL");
5902 for (o = start; o; o = o->call_next) {
5903 if (o->chan) {
5904 ast_queue_log(qe->parent->name, ast_channel_uniqueid(qe->chan), o->member->membername, "RINGCANCELED", "%d", (int) ast_tvdiff_ms(ast_tvnow(), start_time_tv));
5905 }
5906 }
5907 return NULL;
5908 }
5909
5910 /* Send the frame from the in channel to all outgoing channels. */
5911 for (o = start; o; o = o->call_next) {
5912 if (!o->stillgoing || !o->chan) {
5913 /* This outgoing channel has died so don't send the frame to it. */
5914 continue;
5915 }
5916 switch (f->frametype) {
5917 case AST_FRAME_CONTROL:
5918 switch (f->subclass.integer) {
5919 case AST_CONTROL_CONNECTED_LINE:
5920 if (o->block_connected_update) {
5921 ast_verb(3, "Connected line update to %s prevented.\n", ast_channel_name(o->chan));
5922 break;
5923 }
5924 if (ast_channel_connected_line_sub(in, o->chan, f, 1)) {
5925 ast_indicate_data(o->chan, f->subclass.integer, f->data.ptr, f->datalen);
5926 }
5927 break;
5928 case AST_CONTROL_REDIRECTING:
5929 if (o->block_connected_update) {
5930 ast_verb(3, "Redirecting update to %s prevented.\n", ast_channel_name(o->chan));
5931 break;
5932 }
5933 if (ast_channel_redirecting_sub(in, o->chan, f, 1)) {
5934 ast_indicate_data(o->chan, f->subclass.integer, f->data.ptr, f->datalen);
5935 }
5936 break;
5937 default:
5938 /* We are not going to do anything with this frame. */
5939 goto skip_frame;
5940 }
5941 break;
5942 default:
5943 /* We are not going to do anything with this frame. */
5944 goto skip_frame;
5945 }
5946 }
5947 skip_frame:;
5948
5949 ast_frfree(f);
5950 }
5951 }
5952
5953 if (!*to) {
5954 for (o = start; o; o = o->call_next) {
5955 if (o->chan) {
5956 rna(orig, qe, o->chan, o->interface, o->member->membername, 1);
5957 }
5958 }
5959
5960 publish_dial_end_event(qe->chan, outgoing, NULL, "NOANSWER");
5961 }
5962
5963 return peer;
5964 }
5965
5966 /*!
5967 * \brief Check if we should start attempting to call queue members.
5968 *
5969 * A simple process, really. Count the number of members who are available
5970 * to take our call and then see if we are in a position in the queue at
5971 * which a member could accept our call.
5972 *
5973 * \param[in] qe The caller who wants to know if it is his turn
5974 * \retval 0 It is not our turn
5975 * \retval 1 It is our turn
5976 */
5977 static int is_our_turn(struct queue_ent *qe)
5978 {
5979 struct queue_ent *ch;
5980 int res;
5981 int avl;
5982 int idx = 0;
5983 /* This needs a lock. How many members are available to be served? */
5984 ao2_lock(qe->parent);
5985
5986 avl = num_available_members(qe->parent);
5987
5988 ch = qe->parent->head;
5989
5990 ast_debug(1, "There %s %d available %s.\n", avl != 1 ? "are" : "is", avl, avl != 1 ? "members" : "member");
5991
5992 while ((idx < avl) && (ch) && (ch != qe)) {
5993 if (!ch->pending) {
5994 idx++;
5995 }
5996 ch = ch->next;
5997 }
5998
5999 ao2_unlock(qe->parent);
6000 /* If the queue entry is within avl [the number of available members] calls from the top ...
6001 * Autofill and position check added to support autofill=no (as only calls
6002 * from the front of the queue are valid when autofill is disabled)
6003 */
6004 if (ch && idx < avl && (qe->parent->autofill || qe->pos == 1)) {
6005 ast_debug(1, "It's our turn (%s).\n", ast_channel_name(qe->chan));
6006 res = 1;
6007 } else {
6008 ast_debug(1, "It's not our turn (%s).\n", ast_channel_name(qe->chan));
6009 res = 0;
6010 }
6011
6012 /* Update realtime members if this is the first call and number of avalable members is 0 */
6013 if (avl == 0 && qe->pos == 1) {
6014 update_realtime_members(qe->parent);
6015 }
6016
6017 return res;
6018 }
6019
6020 /*!
6021 * \brief update rules for queues
6022 *
6023 * Calculate min/max penalties making sure if relative they stay within bounds.
6024 * Update queues penalty and set dialplan vars, goto next list entry.
6025 */
6026 static void update_qe_rule(struct queue_ent *qe)
6027 {
6028 int max_penalty = INT_MAX;
6029
6030 if (qe->max_penalty != INT_MAX) {
6031 char max_penalty_str[20];
6032
6033 if (qe->pr->max_relative) {
6034 max_penalty = qe->max_penalty + qe->pr->max_value;
6035 } else {
6036 max_penalty = qe->pr->max_value;
6037 }
6038
6039 /* a relative change to the penalty could put it below 0 */
6040 if (max_penalty < 0) {
6041 max_penalty = 0;
6042 }
6043
6044 snprintf(max_penalty_str, sizeof(max_penalty_str), "%d", max_penalty);
6045 pbx_builtin_setvar_helper(qe->chan, "QUEUE_MAX_PENALTY", max_penalty_str);
6046 qe->max_penalty = max_penalty;
6047 ast_debug(3, "Setting max penalty to %d for caller %s since %d seconds have elapsed\n",
6048 qe->max_penalty, ast_channel_name(qe->chan), qe->pr->time);
6049 }
6050
6051 if (qe->min_penalty != INT_MAX) {
6052 char min_penalty_str[20];
6053 int min_penalty;
6054
6055 if (qe->pr->min_relative) {
6056 min_penalty = qe->min_penalty + qe->pr->min_value;
6057 } else {
6058 min_penalty = qe->pr->min_value;
6059 }
6060
6061 /* a relative change to the penalty could put it below 0 */
6062 if (min_penalty < 0) {
6063 min_penalty = 0;
6064 }
6065
6066 if (max_penalty != INT_MAX && min_penalty > max_penalty) {
6067 min_penalty = max_penalty;
6068 }
6069
6070 snprintf(min_penalty_str, sizeof(min_penalty_str), "%d", min_penalty);
6071 pbx_builtin_setvar_helper(qe->chan, "QUEUE_MIN_PENALTY", min_penalty_str);
6072 qe->min_penalty = min_penalty;
6073 ast_debug(3, "Setting min penalty to %d for caller %s since %d seconds have elapsed\n",
6074 qe->min_penalty, ast_channel_name(qe->chan), qe->pr->time);
6075 }
6076
6077 if (qe->raise_penalty != INT_MAX) {
6078 char raise_penalty_str[20];
6079 int raise_penalty;
6080
6081 if (qe->pr->raise_relative) {
6082 raise_penalty = qe->raise_penalty + qe->pr->raise_value;
6083 } else {
6084 raise_penalty = qe->pr->raise_value;
6085 }
6086
6087 /* a relative change to the penalty could put it below 0 */
6088 if (raise_penalty < 0) {
6089 raise_penalty = 0;
6090 }
6091
6092 if (max_penalty != INT_MAX && raise_penalty > max_penalty) {
6093 raise_penalty = max_penalty;
6094 }
6095
6096 qe->raise_respect_min = qe->pr->raise_respect_min;
6097 if (qe->raise_respect_min) {
6098 snprintf(raise_penalty_str, sizeof(raise_penalty_str), "r%d", raise_penalty);
6099 } else {
6100 snprintf(raise_penalty_str, sizeof(raise_penalty_str), "%d", raise_penalty);
6101 }
6102 pbx_builtin_setvar_helper(qe->chan, "QUEUE_RAISE_PENALTY", raise_penalty_str);
6103 qe->raise_penalty = raise_penalty;
6104 ast_debug(3, "Setting raised penalty to %d for caller %s since %d seconds have elapsed\n",
6105 qe->raise_penalty, ast_channel_name(qe->chan), qe->pr->time);
6106 }
6107
6108 qe->pr = AST_LIST_NEXT(qe->pr, list);
6109 }
6110
6111 /*! \brief The waiting areas for callers who are not actively calling members
6112 *
6113 * This function is one large loop. This function will return if a caller
6114 * either exits the queue or it becomes that caller's turn to attempt calling
6115 * queue members. Inside the loop, we service the caller with periodic announcements,
6116 * holdtime announcements, etc. as configured in queues.conf
6117 *
6118 * \retval 0 if the caller's turn has arrived
6119 * \retval -1 if the caller should exit the queue.
6120 */
6121 static int wait_our_turn(struct queue_ent *qe, int ringing, enum queue_result *reason)
6122 {
6123 int res = 0;
6124
6125 /* This is the holding pen for callers 2 through maxlen */
6126 for (;;) {
6127
6128 /* A request to withdraw this call from the queue arrived */
6129 if (qe->withdraw) {
6130 *reason = QUEUE_WITHDRAW;
6131 res = 1;
6132 break;
6133 }
6134
6135 if (is_our_turn(qe)) {
6136 break;
6137 }
6138
6139 /* If we have timed out, break out */
6140 if (qe->expire && (time(NULL) >= qe->expire)) {
6141 *reason = QUEUE_TIMEOUT;
6142 break;
6143 }
6144
6145 if (qe->parent->leavewhenempty) {
6146 int status = 0;
6147
6148 if ((status = get_member_status(qe->parent, qe->max_penalty, qe->min_penalty, qe->raise_penalty, qe->parent->leavewhenempty, 0, qe->raise_respect_min))) {
6149 record_abandoned(qe);
6150 *reason = QUEUE_LEAVEEMPTY;
6151 ast_queue_log(qe->parent->name, ast_channel_uniqueid(qe->chan), "NONE", "EXITEMPTY", "%d|%d|%ld", qe->pos, qe->opos, (long) (time(NULL) - qe->start));
6152 res = -1;
6153 qe->handled = -1;
6154 break;
6155 }
6156 }
6157
6158 /* Make a position announcement, if enabled */
6159 if (qe->parent->announcefrequency &&
6160 (res = say_position(qe,ringing))) {
6161 break;
6162 }
6163
6164 /* If we have timed out, break out */
6165 if (qe->expire && (time(NULL) >= qe->expire)) {
6166 *reason = QUEUE_TIMEOUT;
6167 break;
6168 }
6169
6170 /* Make a periodic announcement, if enabled */
6171 if (qe->parent->periodicannouncefrequency &&
6172 (res = say_periodic_announcement(qe,ringing)))
6173 break;
6174
6175 /* see if we need to move to the next penalty level for this queue */
6176 while (qe->pr && ((time(NULL) - qe->start) >= qe->pr->time)) {
6177 update_qe_rule(qe);
6178 }
6179
6180 /* If we have timed out, break out */
6181 if (qe->expire && (time(NULL) >= qe->expire)) {
6182 *reason = QUEUE_TIMEOUT;
6183 break;
6184 }
6185
6186 /* Wait a second before checking again */
6187 if ((res = ast_waitfordigit(qe->chan, RECHECK * 1000))) {
6188 if (res > 0 && !valid_exit(qe, res)) {
6189 res = 0;
6190 } else {
6191 break;
6192 }
6193 }
6194
6195 /* If we have timed out, break out */
6196 if (qe->expire && (time(NULL) >= qe->expire)) {
6197 *reason = QUEUE_TIMEOUT;
6198 break;
6199 }
6200 }
6201
6202 return res;
6203 }
6204
6205 /*!
6206 * \brief update the queue status
6207 * \retval 0 always
6208 */
6209 static int update_queue(struct call_queue *q, struct member *member,
6210 int callcompletedinsl, time_t starttime)
6211 {
6212 int oldtalktime;
6213 int newtalktime;
6214 struct member *mem;
6215 struct call_queue *qtmp;
6216 struct ao2_iterator queue_iter;
6217 int did_increment_any = 0;
6218
6219 if (!starttime) {
6220 return 0;
6221 }
6222
6223 newtalktime = (int)(time(NULL) - starttime);
6224
6225 /* It is possible for us to be called when a call has already been considered terminated
6226 * and data updated, so to ensure we only act on the call that the agent is currently in
6227 * we check when the call was bridged.
6228 */
6229 ao2_lock(q);
6230 if (member->starttime != starttime) {
6231 ao2_unlock(q);
6232 return 0;
6233 }
6234 member->starttime = 0;
6235 ao2_unlock(q);
6236
6237 if (shared_lastcall) {
6238 queue_iter = ao2_iterator_init(queues, 0);
6239 while ((qtmp = ao2_t_iterator_next(&queue_iter, "Iterate queues"))) {
6240 ao2_lock(qtmp);
6241 if ((mem = ao2_find(qtmp->members, member, OBJ_POINTER))) {
6242 time(&mem->lastcall);
6243 mem->calls++;
6244 mem->callcompletedinsl = 0;
6245 mem->lastqueue = q;
6246 did_increment_any = 1;
6247 ao2_ref(mem, -1);
6248 }
6249 ao2_unlock(qtmp);
6250 queue_t_unref(qtmp, "queue iteration done");
6251 }
6252 ao2_iterator_destroy(&queue_iter);
6253 } else {
6254 ao2_lock(q);
6255 time(&member->lastcall);
6256 member->callcompletedinsl = 0;
6257 member->calls++;
6258 member->lastqueue = q;
6259 did_increment_any = 1;
6260 ao2_unlock(q);
6261 }
6262 /* Member might never experience any direct status change (local
6263 * channel with forwarding in particular). If that's the case,
6264 * this is the last chance to remove it from pending or subsequent
6265 * calls will not occur.
6266 */
6267 pending_members_remove(member);
6268
6269 if (did_increment_any) {
6270 ao2_lock(q);
6271 q->callscompleted++;
6272 if (callcompletedinsl) {
6273 q->callscompletedinsl++;
6274 }
6275 if (q->callscompleted == 1) {
6276 q->talktime = newtalktime;
6277 } else {
6278 /* Calculate talktime using the same exponential average as holdtime code */
6279 oldtalktime = q->talktime;
6280 q->talktime = (((oldtalktime << 2) - oldtalktime) + newtalktime) >> 2;
6281 }
6282 ao2_unlock(q);
6283 }
6284
6285 return 0;
6286 }
6287 /*! \brief Calculate the metric of each member in the outgoing callattempts
6288 *
6289 * A numeric metric is given to each member depending on the ring strategy used
6290 * by the queue. Members with lower metrics will be called before members with
6291 * higher metrics
6292 * \retval -1 if penalties are exceeded
6293 * \retval 0 otherwise
6294 */
6295 static int calc_metric(struct call_queue *q, struct member *mem, int pos, struct queue_ent *qe, struct callattempt *tmp)
6296 {
6297 /* disregarding penalty on too few members? */
6298 int membercount = ao2_container_count(q->members);
6299 unsigned char usepenalty = (membercount <= q->penaltymemberslimit) ? 0 : 1;
6300 int penalty = mem->penalty;
6301
6302 if (usepenalty) {
6303 if (qe->raise_penalty != INT_MAX && penalty < qe->raise_penalty && !(qe->raise_respect_min && qe->min_penalty != INT_MAX && penalty < qe->min_penalty)) {
6304 /* Low penalty is raised up to the current minimum */
6305 penalty = qe->raise_penalty;
6306 }
6307 if ((qe->max_penalty != INT_MAX && penalty > qe->max_penalty) ||
6308 (qe->min_penalty != INT_MAX && penalty < qe->min_penalty)) {
6309 return -1;
6310 }
6311 } else {
6312 ast_debug(1, "Disregarding penalty, %d members and %d in penaltymemberslimit.\n",
6313 membercount, q->penaltymemberslimit);
6314 }
6315
6316 switch (q->strategy) {
6317 case QUEUE_STRATEGY_RINGALL:
6318 /* Everyone equal, except for penalty */
6319 tmp->metric = penalty * 1000000 * usepenalty;
6320 break;
6321 case QUEUE_STRATEGY_LINEAR:
6322 if (pos < qe->linpos) {
6323 tmp->metric = 1000 + pos;
6324 } else {
6325 if (pos > qe->linpos) {
6326 /* Indicate there is another priority */
6327 qe->linwrapped = 1;
6328 }
6329 tmp->metric = pos;
6330 }
6331 tmp->metric += penalty * 1000000 * usepenalty;
6332 break;
6333 case QUEUE_STRATEGY_RRORDERED:
6334 case QUEUE_STRATEGY_RRMEMORY:
6335 pos = mem->queuepos;
6336 if (pos < q->rrpos) {
6337 tmp->metric = 1000 + pos;
6338 } else {
6339 if (pos > q->rrpos) {
6340 /* Indicate there is another priority */
6341 q->wrapped = 1;
6342 }
6343 tmp->metric = pos;
6344 }
6345 tmp->metric += penalty * 1000000 * usepenalty;
6346 break;
6347 case QUEUE_STRATEGY_RANDOM:
6348 tmp->metric = ast_random() % 1000;
6349 tmp->metric += penalty * 1000000 * usepenalty;
6350 break;
6351 case QUEUE_STRATEGY_WRANDOM:
6352 tmp->metric = ast_random() % ((1 + penalty) * 1000);
6353 break;
6354 case QUEUE_STRATEGY_FEWESTCALLS:
6355 tmp->metric = mem->calls;
6356 tmp->metric += penalty * 1000000 * usepenalty;
6357 break;
6358 case QUEUE_STRATEGY_LEASTRECENT:
6359 if (!mem->lastcall) {
6360 tmp->metric = 0;
6361 } else {
6362 tmp->metric = 1000000 - (time(NULL) - mem->lastcall);
6363 }
6364 tmp->metric += penalty * 1000000 * usepenalty;
6365 break;
6366 default:
6367 ast_log(LOG_WARNING, "Can't calculate metric for unknown strategy %d\n", q->strategy);
6368 break;
6369 }
6370 return 0;
6371 }
6372
6373 enum agent_complete_reason {
6374 CALLER,
6375 AGENT,
6376 TRANSFER
6377 };
6378
6379 /*! \brief Send out AMI message with member call completion status information */
6380 static void send_agent_complete(const char *queuename, struct ast_channel_snapshot *caller,
6381 struct ast_channel_snapshot *peer, const struct member *member, time_t holdstart,
6382 time_t callstart, enum agent_complete_reason rsn)
6383 {
6384 const char *reason = NULL; /* silence dumb compilers */
6385 RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
6386
6387 switch (rsn) {
6388 case CALLER:
6389 reason = "caller";
6390 break;
6391 case AGENT:
6392 reason = "agent";
6393 break;
6394 case TRANSFER:
6395 reason = "transfer";
6396 break;
6397 }
6398
6399 blob = ast_json_pack("{s: s, s: s, s: s, s: I, s: I, s: s}",
6400 "Queue", queuename,
6401 "Interface", member->interface,
6402 "MemberName", member->membername,
6403 "HoldTime", (ast_json_int_t)(callstart - holdstart),
6404 "TalkTime", (ast_json_int_t)(time(NULL) - callstart),
6405 "Reason", reason ?: "");
6406
6407 queue_publish_multi_channel_snapshot_blob(ast_queue_topic(queuename), caller, peer,
6408 queue_agent_complete_type(), blob);
6409 }
6410
6411 static void queue_agent_cb(void *userdata, struct stasis_subscription *sub,
6412 struct stasis_message *msg)
6413 {
6414 struct ast_channel_blob *agent_blob;
6415
6416 agent_blob = stasis_message_data(msg);
6417
6418 if (ast_channel_agent_login_type() == stasis_message_type(msg)) {
6419 ast_queue_log("NONE", agent_blob->snapshot->base->uniqueid,
6420 ast_json_string_get(ast_json_object_get(agent_blob->blob, "agent")),
6421 "AGENTLOGIN", "%s", agent_blob->snapshot->base->name);
6422 } else if (ast_channel_agent_logoff_type() == stasis_message_type(msg)) {
6423 ast_queue_log("NONE", agent_blob->snapshot->base->uniqueid,
6424 ast_json_string_get(ast_json_object_get(agent_blob->blob, "agent")),
6425 "AGENTLOGOFF", "%s|%ld", agent_blob->snapshot->base->name,
6426 (long) ast_json_integer_get(ast_json_object_get(agent_blob->blob, "logintime")));
6427 }
6428 }
6429
6430 /*!
6431 * \brief Structure representing relevant data during a local channel optimization
6432 *
6433 * The reason we care about local channel optimizations is that we want to be able
6434 * to accurately report when the caller and queue member have stopped talking to
6435 * each other. A local channel optimization can cause it to appear that the conversation
6436 * has stopped immediately after it has begun. By tracking that the relevant channels
6437 * to monitor have changed due to a local channel optimization, we can give accurate
6438 * reports.
6439 *
6440 * Local channel optimizations for queues are restricted from their normal operation.
6441 * Bridges created by queues can only be the destination of local channel optimizations,
6442 * not the source. In addition, move-swap local channel optimizations are the only
6443 * permitted types of local channel optimization.
6444 *
6445 * This data is populated when we are told that a local channel optimization begin
6446 * is occurring. When we get told the optimization has ended successfully, we then
6447 * apply the data here into the queue_stasis_data.
6448 */
6449 struct local_optimization {
6450 /*! The uniqueid of the channel that will be taking the place of the caller or member */
6451 const char *source_chan_uniqueid;
6452 /*! Indication of whether we think there is a local channel optimization in progress */
6453 int in_progress;
6454 /*! The identifier for this local channel optimization */
6455 unsigned int id;
6456 };
6457
6458 /*!
6459 * \brief User data for stasis subscriptions used for queue calls.
6460 *
6461 * app_queue subscribes to channel and bridge events for all bridged calls.
6462 * app_queue cares about the following events:
6463 *
6464 * \li bridge enter: To determine the unique ID of the bridge created for the call.
6465 * \li blind transfer: To send an appropriate agent complete event.
6466 * \li attended transfer: To send an appropriate agent complete event.
6467 * \li local optimization: To update caller and member unique IDs for the call.
6468 * \li hangup: To send an appropriate agent complete event.
6469 *
6470 * The stasis subscriptions last until we determine that the caller and the member
6471 * are no longer bridged with each other.
6472 */
6473 struct queue_stasis_data {
6474 AST_DECLARE_STRING_FIELDS(
6475 /*! The unique ID of the caller's channel. */
6476 AST_STRING_FIELD(caller_uniqueid);
6477 /*! The unique ID of the queue member's channel */
6478 AST_STRING_FIELD(member_uniqueid);
6479 /*! The unique ID of the bridge created by the queue */
6480 AST_STRING_FIELD(bridge_uniqueid);
6481 );
6482 /*! The relevant queue */
6483 struct call_queue *queue;
6484 /*! The queue member that has answered the call */
6485 struct member *member;
6486 /*! The time at which the caller entered the queue. Start of the caller's hold time */
6487 time_t holdstart;
6488 /*! The time at which the member answered the call. */
6489 time_t starttime;
6490 /*! The original position of the caller when he entered the queue */
6491 int caller_pos;
6492 /*! Indication if the call was answered within the configured service level of the queue */
6493 int callcompletedinsl;
6494 /*! Indicates if the stasis subscriptions are shutting down */
6495 int dying;
6496 /*! The stasis message router for bridge events */
6497 struct stasis_message_router *bridge_router;
6498 /*! The stasis message router for channel events */
6499 struct stasis_message_router *channel_router;
6500 /*! Local channel optimization details for the caller */
6501 struct local_optimization caller_optimize;
6502 /*! Local channel optimization details for the member */
6503 struct local_optimization member_optimize;
6504 };
6505
6506 /*!
6507 * \internal
6508 * \brief Free memory for a queue_stasis_data
6509 */
6510 static void queue_stasis_data_destructor(void *obj)
6511 {
6512 struct queue_stasis_data *queue_data = obj;
6513
6514 /* This can only happen if refcounts for this object have got severely messed up */
6515 ast_assert(queue_data->bridge_router == NULL);
6516 ast_assert(queue_data->channel_router == NULL);
6517
6518 ao2_cleanup(queue_data->member);
6519 queue_unref(queue_data->queue);
6520 ast_string_field_free_memory(queue_data);
6521 }
6522
6523 /*!
6524 * \internal
6525 * \brief End all stasis subscriptions on a queue_stasis_data
6526 */
6527 static void remove_stasis_subscriptions(struct queue_stasis_data *queue_data)
6528 {
6529 SCOPED_AO2LOCK(lock, queue_data);
6530
6531 queue_data->dying = 1;
6532 stasis_message_router_unsubscribe(queue_data->bridge_router);
6533 queue_data->bridge_router = NULL;
6534 stasis_message_router_unsubscribe(queue_data->channel_router);
6535 queue_data->channel_router = NULL;
6536 }
6537
6538 /*!
6539 * \internal
6540 * \brief Allocate a queue_stasis_data and initialize its data.
6541 */
6542 static struct queue_stasis_data *queue_stasis_data_alloc(struct queue_ent *qe,
6543 struct ast_channel *peer, struct member *mem, time_t holdstart,
6544 time_t starttime, int callcompletedinsl)
6545 {
6546 struct queue_stasis_data *queue_data;
6547
6548 queue_data = ao2_alloc(sizeof(*queue_data), queue_stasis_data_destructor);
6549 if (!queue_data) {
6550 return NULL;
6551 }
6552
6553 if (ast_string_field_init(queue_data, 64)) {
6554 ao2_cleanup(queue_data);
6555 return NULL;
6556 }
6557
6558 ast_string_field_set(queue_data, caller_uniqueid, ast_channel_uniqueid(qe->chan));
6559 ast_string_field_set(queue_data, member_uniqueid, ast_channel_uniqueid(peer));
6560 queue_data->queue = queue_ref(qe->parent);
6561 queue_data->starttime = starttime;
6562 queue_data->holdstart = holdstart;
6563 queue_data->callcompletedinsl = callcompletedinsl;
6564 queue_data->caller_pos = qe->opos;
6565 ao2_ref(mem, +1);
6566 queue_data->member = mem;
6567
6568 return queue_data;
6569 }
6570
6571 /*!
6572 * \internal
6573 * \brief Log an attended transfer in the queue log.
6574 *
6575 * Attended transfer queue log messages vary based on the method by which the
6576 * attended transfer was completed.
6577 *
6578 * \param queue_data Data pertaining to the particular call in the queue.
6579 * \param atxfer_msg The stasis attended transfer message data.
6580 */
6581 static void log_attended_transfer(struct queue_stasis_data *queue_data,
6582 struct ast_attended_transfer_message *atxfer_msg)
6583 {
6584 RAII_VAR(struct ast_str *, transfer_str, ast_str_create(32), ast_free);
6585
6586 if (!transfer_str) {
6587 ast_log(LOG_WARNING, "Unable to log attended transfer to queue log\n");
6588 return;
6589 }
6590
6591 switch (atxfer_msg->dest_type) {
6592 case AST_ATTENDED_TRANSFER_DEST_BRIDGE_MERGE:
6593 ast_str_set(&transfer_str, 0, "BRIDGE|%s", atxfer_msg->dest.bridge);
6594 break;
6595 case AST_ATTENDED_TRANSFER_DEST_APP:
6596 case AST_ATTENDED_TRANSFER_DEST_LOCAL_APP:
6597 ast_str_set(&transfer_str, 0, "APP|%s", atxfer_msg->dest.app);
6598 break;
6599 case AST_ATTENDED_TRANSFER_DEST_LINK:
6600 ast_str_set(&transfer_str, 0, "LINK|%s|%s", atxfer_msg->dest.links[0]->base->name,
6601 atxfer_msg->dest.links[1]->base->name);
6602 break;
6603 case AST_ATTENDED_TRANSFER_DEST_THREEWAY:
6604 case AST_ATTENDED_TRANSFER_DEST_FAIL:
6605 /* Threeways are headed off and should not be logged here */
6606 ast_assert(0);
6607 return;
6608 }
6609
6610 ast_queue_log(queue_data->queue->name, queue_data->caller_uniqueid, queue_data->member->membername, "ATTENDEDTRANSFER", "%s|%ld|%ld|%d",
6611 ast_str_buffer(transfer_str),
6612 (long) (queue_data->starttime - queue_data->holdstart),
6613 (long) (time(NULL) - queue_data->starttime), queue_data->caller_pos);
6614 }
6615
6616 /*!
6617 * \internal
6618 * \brief Handle a stasis bridge enter event.
6619 *
6620 * We track this particular event in order to learn what bridge
6621 * was created for the queue call.
6622 *
6623 * \param userdata Data pertaining to the particular call in the queue.
6624 * \param sub The stasis subscription on which the message occurred.
6625 * \param msg The stasis message for the bridge enter event
6626 */
6627 static void handle_bridge_enter(void *userdata, struct stasis_subscription *sub,
6628 struct stasis_message *msg)
6629 {
6630 struct queue_stasis_data *queue_data = userdata;
6631 struct ast_bridge_blob *enter_blob = stasis_message_data(msg);
6632 SCOPED_AO2LOCK(lock, queue_data);
6633
6634 if (queue_data->dying) {
6635 return;
6636 }
6637
6638 if (!ast_strlen_zero(queue_data->bridge_uniqueid)) {
6639 return;
6640 }
6641
6642 if (!strcmp(enter_blob->channel->base->uniqueid, queue_data->caller_uniqueid)) {
6643 ast_string_field_set(queue_data, bridge_uniqueid,
6644 enter_blob->bridge->uniqueid);
6645 ast_debug(3, "Detected entry of caller channel %s into bridge %s\n",
6646 enter_blob->channel->base->name, queue_data->bridge_uniqueid);
6647 }
6648 }
6649
6650 /*!
6651 * \brief Handle a blind transfer event
6652 *
6653 * This event is important in order to be able to log the end of the
6654 * call to the queue log and to stasis.
6655 *
6656 * \param userdata Data pertaining to the particular call in the queue.
6657 * \param sub The stasis subscription on which the message occurred.
6658 * \param msg The stasis message for the blind transfer event
6659 */
6660 static void handle_blind_transfer(void *userdata, struct stasis_subscription *sub,
6661 struct stasis_message *msg)
6662 {
6663 struct queue_stasis_data *queue_data = userdata;
6664 struct ast_blind_transfer_message *transfer_msg = stasis_message_data(msg);
6665 const char *exten;
6666 const char *context;
6667 RAII_VAR(struct ast_channel_snapshot *, caller_snapshot, NULL, ao2_cleanup);
6668 RAII_VAR(struct ast_channel_snapshot *, member_snapshot, NULL, ao2_cleanup);
6669
6670 if (transfer_msg->result != AST_BRIDGE_TRANSFER_SUCCESS) {
6671 return;
6672 }
6673
6674 ao2_lock(queue_data);
6675
6676 if (queue_data->dying) {
6677 ao2_unlock(queue_data);
6678 return;
6679 }
6680
6681 if (ast_strlen_zero(queue_data->bridge_uniqueid) ||
6682 strcmp(queue_data->bridge_uniqueid, transfer_msg->bridge->uniqueid)) {
6683 ao2_unlock(queue_data);
6684 return;
6685 }
6686
6687 caller_snapshot = ast_channel_snapshot_get_latest(queue_data->caller_uniqueid);
6688 member_snapshot = ast_channel_snapshot_get_latest(queue_data->member_uniqueid);
6689
6690 ao2_unlock(queue_data);
6691
6692 exten = transfer_msg->exten;
6693 context = transfer_msg->context;
6694
6695 ast_debug(3, "Detected blind transfer in queue %s\n", queue_data->queue->name);
6696 ast_queue_log(queue_data->queue->name, queue_data->caller_uniqueid, queue_data->member->membername,
6697 "BLINDTRANSFER", "%s|%s|%ld|%ld|%d",
6698 exten, context,
6699 (long) (queue_data->starttime - queue_data->holdstart),
6700 (long) (time(NULL) - queue_data->starttime), queue_data->caller_pos);
6701
6702 send_agent_complete(queue_data->queue->name, caller_snapshot, member_snapshot, queue_data->member,
6703 queue_data->holdstart, queue_data->starttime, TRANSFER);
6704 update_queue(queue_data->queue, queue_data->member, queue_data->callcompletedinsl,
6705 queue_data->starttime);
6706 remove_stasis_subscriptions(queue_data);
6707 }
6708
6709 /*!
6710 * \brief Handle an attended transfer event
6711 *
6712 * This event is important in order to be able to log the end of the
6713 * call to the queue log and to stasis.
6714 *
6715 * \param userdata Data pertaining to the particular call in the queue.
6716 * \param sub The stasis subscription on which the message occurred.
6717 * \param msg The stasis message for the attended transfer event.
6718 */
6719 static void handle_attended_transfer(void *userdata, struct stasis_subscription *sub,
6720 struct stasis_message *msg)
6721 {
6722 struct queue_stasis_data *queue_data = userdata;
6723 struct ast_attended_transfer_message *atxfer_msg = stasis_message_data(msg);
6724 RAII_VAR(struct ast_channel_snapshot *, caller_snapshot, NULL, ao2_cleanup);
6725 RAII_VAR(struct ast_channel_snapshot *, member_snapshot, NULL, ao2_cleanup);
6726
6727 if (atxfer_msg->result != AST_BRIDGE_TRANSFER_SUCCESS ||
6728 atxfer_msg->dest_type == AST_ATTENDED_TRANSFER_DEST_THREEWAY) {
6729 return;
6730 }
6731
6732 ao2_lock(queue_data);
6733
6734 if (queue_data->dying) {
6735 ao2_unlock(queue_data);
6736 return;
6737 }
6738
6739 if (ast_strlen_zero(queue_data->bridge_uniqueid)) {
6740 ao2_unlock(queue_data);
6741 return;
6742 }
6743
6744 if ((!atxfer_msg->to_transferee.bridge_snapshot || strcmp(queue_data->bridge_uniqueid,
6745 atxfer_msg->to_transferee.bridge_snapshot->uniqueid)) &&
6746 (!atxfer_msg->to_transfer_target.bridge_snapshot || strcmp(queue_data->bridge_uniqueid,
6747 atxfer_msg->to_transfer_target.bridge_snapshot->uniqueid))) {
6748 ao2_unlock(queue_data);
6749 return;
6750 }
6751
6752 caller_snapshot = ast_channel_snapshot_get_latest(queue_data->caller_uniqueid);
6753 member_snapshot = ast_channel_snapshot_get_latest(queue_data->member_uniqueid);
6754
6755 ao2_unlock(queue_data);
6756
6757 ast_debug(3, "Detected attended transfer in queue %s\n", queue_data->queue->name);
6758 log_attended_transfer(queue_data, atxfer_msg);
6759
6760 send_agent_complete(queue_data->queue->name, caller_snapshot, member_snapshot, queue_data->member,
6761 queue_data->holdstart, queue_data->starttime, TRANSFER);
6762 update_queue(queue_data->queue, queue_data->member, queue_data->callcompletedinsl,
6763 queue_data->starttime);
6764 remove_stasis_subscriptions(queue_data);
6765 }
6766
6767 /*!
6768 * \internal
6769 * \brief Callback for all stasis bridge events
6770 *
6771 * Based on the event and what bridge it is on, the task is farmed out to relevant
6772 * subroutines for further processing.
6773 */
6774 static void queue_bridge_cb(void *userdata, struct stasis_subscription *sub,
6775 struct stasis_message *msg)
6776 {
6777 if (stasis_subscription_final_message(sub, msg)) {
6778 ao2_cleanup(userdata);
6779 }
6780 }
6781
6782 /*!
6783 * \internal
6784 * \brief Handler for the beginning of a local channel optimization
6785 *
6786 * This method gathers data relevant to the local channel optimization and stores
6787 * it to be used once the local optimization completes.
6788 *
6789 * \param userdata Data pertaining to the particular call in the queue.
6790 * \param sub The stasis subscription on which the message occurred.
6791 * \param msg The stasis message for the local optimization begin event
6792 */
6793 static void handle_local_optimization_begin(void *userdata, struct stasis_subscription *sub,
6794 struct stasis_message *msg)
6795 {
6796 struct queue_stasis_data *queue_data = userdata;
6797 struct ast_multi_channel_blob *optimization_blob = stasis_message_data(msg);
6798 struct ast_channel_snapshot *local_one = ast_multi_channel_blob_get_channel(optimization_blob, "1");
6799 struct ast_channel_snapshot *local_two = ast_multi_channel_blob_get_channel(optimization_blob, "2");
6800 struct ast_channel_snapshot *source = ast_multi_channel_blob_get_channel(optimization_blob, "source");
6801 struct local_optimization *optimization;
6802 unsigned int id;
6803 SCOPED_AO2LOCK(lock, queue_data);
6804
6805 if (!local_one || !local_two || !source) {
6806 ast_debug(1, "Local optimization begin missing channel snapshots:%s%s%s\n",
6807 !local_one ? " local_one," : "",
6808 !local_two ? " local_two," : "",
6809 !source ? " source," : "");
6810 return;
6811 }
6812
6813 if (queue_data->dying) {
6814 return;
6815 }
6816
6817 if (!strcmp(local_one->base->uniqueid, queue_data->member_uniqueid)) {
6818 optimization = &queue_data->member_optimize;
6819 } else if (!strcmp(local_two->base->uniqueid, queue_data->caller_uniqueid)) {
6820 optimization = &queue_data->caller_optimize;
6821 } else {
6822 return;
6823 }
6824
6825 /* We only allow move-swap optimizations, so there had BETTER be a source */
6826 ast_assert(source != NULL);
6827
6828 optimization->source_chan_uniqueid = ast_strdup(source->base->uniqueid);
6829 if (!optimization->source_chan_uniqueid) {
6830 ast_log(LOG_ERROR, "Unable to track local channel optimization for channel %s. Expect further errors\n", local_one->base->name);
6831 return;
6832 }
6833 id = ast_json_integer_get(ast_json_object_get(ast_multi_channel_blob_get_json(optimization_blob), "id"));
6834
6835 optimization->id = id;
6836 optimization->in_progress = 1;
6837 }
6838
6839 /*!
6840 * \internal
6841 * \brief Handler for the end of a local channel optimization
6842 *
6843 * This method takes the data gathered during the local channel optimization begin
6844 * event and applies it to the queue stasis data appropriately. This generally involves
6845 * updating the caller or member unique ID with the channel that is taking the place of
6846 * the previous caller or member.
6847 *
6848 * \param userdata Data pertaining to the particular call in the queue.
6849 * \param sub The stasis subscription on which the message occurred.
6850 * \param msg The stasis message for the local optimization end event
6851 */
6852 static void handle_local_optimization_end(void *userdata, struct stasis_subscription *sub,
6853 struct stasis_message *msg)
6854 {
6855 struct queue_stasis_data *queue_data = userdata;
6856 struct ast_multi_channel_blob *optimization_blob = stasis_message_data(msg);
6857 struct ast_channel_snapshot *local_one = ast_multi_channel_blob_get_channel(optimization_blob, "1");
6858 struct ast_channel_snapshot *local_two = ast_multi_channel_blob_get_channel(optimization_blob, "2");
6859 struct local_optimization *optimization;
6860 int is_caller;
6861 unsigned int id;
6862 SCOPED_AO2LOCK(lock, queue_data);
6863
6864 if (queue_data->dying) {
6865 return;
6866 }
6867
6868 if (!strcmp(local_one->base->uniqueid, queue_data->member_uniqueid)) {
6869 optimization = &queue_data->member_optimize;
6870 is_caller = 0;
6871 } else if (!strcmp(local_two->base->uniqueid, queue_data->caller_uniqueid)) {
6872 optimization = &queue_data->caller_optimize;
6873 is_caller = 1;
6874 } else {
6875 return;
6876 }
6877
6878 id = ast_json_integer_get(ast_json_object_get(ast_multi_channel_blob_get_json(optimization_blob), "id"));
6879
6880 if (!optimization->in_progress) {
6881 ast_log(LOG_WARNING, "Told of a local optimization end when we had no previous begin\n");
6882 return;
6883 }
6884
6885 if (id != optimization->id) {
6886 ast_log(LOG_WARNING, "Local optimization end event ID does not match begin (%u != %u)\n",
6887 id, optimization->id);
6888 return;
6889 }
6890
6891 if (is_caller) {
6892 ast_debug(3, "Local optimization: Changing queue caller uniqueid from %s to %s\n",
6893 queue_data->caller_uniqueid, optimization->source_chan_uniqueid);
6894 ast_string_field_set(queue_data, caller_uniqueid, optimization->source_chan_uniqueid);
6895 } else {
6896 ast_debug(3, "Local optimization: Changing queue member uniqueid from %s to %s\n",
6897 queue_data->member_uniqueid, optimization->source_chan_uniqueid);
6898 ast_string_field_set(queue_data, member_uniqueid, optimization->source_chan_uniqueid);
6899 }
6900
6901 optimization->in_progress = 0;
6902 }
6903
6904 /*!
6905 * \internal
6906 * \brief Handler for hangup stasis event
6907 *
6908 * This is how we determine that the caller or member has hung up and the call
6909 * has ended. An appropriate queue log and stasis message are raised in this
6910 * callback.
6911 *
6912 * \param userdata Data pertaining to the particular call in the queue.
6913 * \param sub The stasis subscription on which the message occurred.
6914 * \param msg The stasis message for the hangup event.
6915 */
6916 static void handle_hangup(void *userdata, struct stasis_subscription *sub,
6917 struct stasis_message *msg)
6918 {
6919 struct queue_stasis_data *queue_data = userdata;
6920 struct ast_channel_blob *channel_blob = stasis_message_data(msg);
6921 RAII_VAR(struct ast_channel_snapshot *, caller_snapshot, NULL, ao2_cleanup);
6922 RAII_VAR(struct ast_channel_snapshot *, member_snapshot, NULL, ao2_cleanup);
6923 RAII_VAR(struct ast_channel *, chan, NULL, ao2_cleanup);
6924 enum agent_complete_reason reason;
6925
6926 ao2_lock(queue_data);
6927
6928 if (queue_data->dying) {
6929 ao2_unlock(queue_data);
6930 return;
6931 }
6932
6933 if (!strcmp(channel_blob->snapshot->base->uniqueid, queue_data->caller_uniqueid)) {
6934 reason = CALLER;
6935 } else if (!strcmp(channel_blob->snapshot->base->uniqueid, queue_data->member_uniqueid)) {
6936 reason = AGENT;
6937 } else {
6938 ao2_unlock(queue_data);
6939 return;
6940 }
6941
6942 chan = ast_channel_get_by_name(channel_blob->snapshot->base->name);
6943 if (chan && (ast_channel_has_role(chan, AST_TRANSFERER_ROLE_NAME) ||
6944 !ast_strlen_zero(pbx_builtin_getvar_helper(chan, "ATTENDEDTRANSFER")) ||
6945 !ast_strlen_zero(pbx_builtin_getvar_helper(chan, "BLINDTRANSFER")))) {
6946 /* Channel that is hanging up is doing it as part of a transfer.
6947 * We'll get a transfer event later
6948 */
6949 ao2_unlock(queue_data);
6950 return;
6951 }
6952
6953 caller_snapshot = ast_channel_snapshot_get_latest(queue_data->caller_uniqueid);
6954 member_snapshot = ast_channel_snapshot_get_latest(queue_data->member_uniqueid);
6955
6956 ao2_unlock(queue_data);
6957
6958 ast_debug(3, "Detected hangup of queue %s channel %s\n", reason == CALLER ? "caller" : "member",
6959 channel_blob->snapshot->base->name);
6960
6961 ast_queue_log(queue_data->queue->name, queue_data->caller_uniqueid, queue_data->member->membername,
6962 reason == CALLER ? "COMPLETECALLER" : "COMPLETEAGENT", "%ld|%ld|%d",
6963 (long) (queue_data->starttime - queue_data->holdstart),
6964 (long) (time(NULL) - queue_data->starttime), queue_data->caller_pos);
6965
6966 send_agent_complete(queue_data->queue->name, caller_snapshot, member_snapshot, queue_data->member,
6967 queue_data->holdstart, queue_data->starttime, reason);
6968 update_queue(queue_data->queue, queue_data->member, queue_data->callcompletedinsl,
6969 queue_data->starttime);
6970 remove_stasis_subscriptions(queue_data);
6971 }
6972
6973 static void handle_masquerade(void *userdata, struct stasis_subscription *sub,
6974 struct stasis_message *msg)
6975 {
6976 struct queue_stasis_data *queue_data = userdata;
6977 struct ast_channel_blob *channel_blob = stasis_message_data(msg);
6978 const char *new_channel_id;
6979
6980 new_channel_id = ast_json_string_get(ast_json_object_get(channel_blob->blob, "newchanneluniqueid"));
6981
6982 ao2_lock(queue_data);
6983
6984 if (queue_data->dying) {
6985 ao2_unlock(queue_data);
6986 return;
6987 }
6988
6989 if (!strcmp(channel_blob->snapshot->base->uniqueid, queue_data->caller_uniqueid)) {
6990 ast_debug(1, "Replacing caller channel %s with %s due to masquerade\n", queue_data->caller_uniqueid, new_channel_id);
6991 ast_string_field_set(queue_data, caller_uniqueid, new_channel_id);
6992 } else if (!strcmp(channel_blob->snapshot->base->uniqueid, queue_data->member_uniqueid)) {
6993 ast_debug(1, "Replacing member channel %s with %s due to masquerade\n", queue_data->member_uniqueid, new_channel_id);
6994 ast_string_field_set(queue_data, member_uniqueid, new_channel_id);
6995 }
6996
6997 ao2_unlock(queue_data);
6998 }
6999
7000 /*!
7001 * \internal
7002 * \brief Callback for all stasis channel events
7003 *
7004 * Based on the event and the channels involved, the work is farmed out into
7005 * subroutines for further processing.
7006 */
7007 static void queue_channel_cb(void *userdata, struct stasis_subscription *sub,
7008 struct stasis_message *msg)
7009 {
7010 if (stasis_subscription_final_message(sub, msg)) {
7011 ao2_cleanup(userdata);
7012 }
7013 }
7014
7015 /*!
7016 * \internal
7017 * \brief Create stasis subscriptions for a particular call in the queue.
7018 *
7019 * These subscriptions are created once the call has been answered. The subscriptions
7020 * are put in place so that call progress may be tracked. Once the call can be determined
7021 * to have ended, then messages are logged to the queue log and stasis events are emitted.
7022 *
7023 * \param qe The queue entry representing the caller
7024 * \param peer The channel that has answered the call
7025 * \param mem The queue member that answered the call
7026 * \param holdstart The time at which the caller entered the queue
7027 * \param starttime The time at which the call was answered
7028 * \param callcompletedinsl Indicates if the call was answered within the configured service level of the queue.
7029 * \retval 0 Success
7030 * \retval non-zero Failure
7031 */
7032 static int setup_stasis_subs(struct queue_ent *qe, struct ast_channel *peer, struct member *mem,
7033 time_t holdstart, time_t starttime, int callcompletedinsl)
7034 {
7035 struct queue_stasis_data *queue_data = queue_stasis_data_alloc(qe, peer, mem, holdstart, starttime, callcompletedinsl);
7036
7037 if (!queue_data) {
7038 return -1;
7039 }
7040
7041 queue_data->bridge_router = stasis_message_router_create_pool(ast_bridge_topic_all());
7042 if (!queue_data->bridge_router) {
7043 ao2_ref(queue_data, -1);
7044 return -1;
7045 }
7046
7047 stasis_message_router_add(queue_data->bridge_router, ast_channel_entered_bridge_type(),
7048 handle_bridge_enter, queue_data);
7049 stasis_message_router_add(queue_data->bridge_router, ast_blind_transfer_type(),
7050 handle_blind_transfer, queue_data);
7051 stasis_message_router_add(queue_data->bridge_router, ast_attended_transfer_type(),
7052 handle_attended_transfer, queue_data);
7053 stasis_message_router_add(queue_data->bridge_router, stasis_subscription_change_type(),
7054 queue_bridge_cb, queue_data);
7055
7056 queue_data->channel_router = stasis_message_router_create_pool(ast_channel_topic_all());
7057 if (!queue_data->channel_router) {
7058 /* Unsubscribing from the bridge router will remove the only ref of queue_data,
7059 * thus beginning the destruction process
7060 */
7061 stasis_message_router_unsubscribe(queue_data->bridge_router);
7062 queue_data->bridge_router = NULL;
7063 return -1;
7064 }
7065
7066 ao2_ref(queue_data, +1);
7067 stasis_message_router_add(queue_data->channel_router, ast_local_optimization_begin_type(),
7068 handle_local_optimization_begin, queue_data);
7069 stasis_message_router_add(queue_data->channel_router, ast_local_optimization_end_type(),
7070 handle_local_optimization_end, queue_data);
7071 stasis_message_router_add(queue_data->channel_router, ast_channel_hangup_request_type(),
7072 handle_hangup, queue_data);
7073 stasis_message_router_add(queue_data->channel_router, ast_channel_masquerade_type(),
7074 handle_masquerade, queue_data);
7075 stasis_message_router_add(queue_data->channel_router, stasis_subscription_change_type(),
7076 queue_channel_cb, queue_data);
7077
7078 return 0;
7079 }
7080
7081 struct queue_end_bridge {
7082 struct call_queue *q;
7083 struct ast_channel *chan;
7084 struct timeval start_time;
7085 };
7086
7087 /*!
7088 * \internal
7089 * \brief Helper to set the standard Dial duration variables
7090 */
7091 static void set_duration_var(struct ast_channel *chan, const char *var_base, int64_t duration)
7092 {
7093 char buf[32];
7094 char full_var_name[128];
7095
7096 snprintf(buf, sizeof(buf), "%" PRId64, duration / 1000);
7097 pbx_builtin_setvar_helper(chan, var_base, buf);
7098
7099 snprintf(full_var_name, sizeof(full_var_name), "%s_MS", var_base);
7100 snprintf(buf, sizeof(buf), "%" PRId64, duration);
7101 pbx_builtin_setvar_helper(chan, full_var_name, buf);
7102 }
7103
7104 static void end_bridge_callback_data_fixup(struct ast_bridge_config *bconfig, struct ast_channel *originator, struct ast_channel *terminator)
7105 {
7106 struct queue_end_bridge *qeb = bconfig->end_bridge_callback_data;
7107 ao2_ref(qeb, +1);
7108 qeb->chan = originator;
7109 }
7110
7111 static void end_bridge_callback(void *data)
7112 {
7113 struct queue_end_bridge *qeb = data;
7114 struct call_queue *q = qeb->q;
7115 struct ast_channel *chan = qeb->chan;
7116 int64_t answered_time_ms;
7117
7118 if (ao2_ref(qeb, -1) == 1) {
7119 set_queue_variables(q, chan);
7120
7121 /* Match Dial() timing variables */
7122 ast_channel_lock(chan);
7123 ast_channel_stage_snapshot(chan);
7124 answered_time_ms = ast_tvdiff_ms(ast_tvnow(), qeb->start_time);
7125 set_duration_var(chan, "ANSWEREDTIME", answered_time_ms);
7126 set_duration_var(chan, "DIALEDTIME", ast_channel_get_duration_ms(chan));
7127 ast_channel_stage_snapshot_done(chan);
7128 ast_channel_unlock(chan);
7129
7130 /* This unrefs the reference we made in try_calling when we allocated qeb */
7131 queue_t_unref(q, "Expire bridge_config reference");
7132 }
7133 }
7134
7135 /*!
7136 * \internal
7137 * \brief Setup the after bridge goto location on the peer.
7138 * \since 12.0.0
7139 *
7140 * \param chan Calling channel for bridge.
7141 * \param peer Peer channel for bridge.
7142 * \param opts Dialing option flags.
7143 * \param opt_args Dialing option argument strings.
7144 */
7145 static void setup_peer_after_bridge_goto(struct ast_channel *chan, struct ast_channel *peer, struct ast_flags *opts, char *opt_args[])
7146 {
7147 const char *context;
7148 const char *extension;
7149 int priority;
7150
7151 if (ast_test_flag(opts, OPT_CALLEE_GO_ON)) {
7152 ast_channel_lock(chan);
7153 context = ast_strdupa(ast_channel_context(chan));
7154 extension = ast_strdupa(ast_channel_exten(chan));
7155 priority = ast_channel_priority(chan);
7156 ast_channel_unlock(chan);
7157 ast_bridge_set_after_go_on(peer, context, extension, priority,
7158 opt_args[OPT_ARG_CALLEE_GO_ON]);
7159 }
7160 }
7161
7162 static void escape_and_substitute(struct ast_channel *chan, const char *input,
7163 char *output, size_t size)
7164 {
7165 const char *m = input;
7166 char escaped[size];
7167 char *p;
7168
7169 for (p = escaped; p < escaped + size - 1; p++, m++) {
7170 switch (*m) {
7171 case '^':
7172 if (*(m + 1) == '{') {
7173 *p = '$';
7174 }
7175 break;
7176 case ',':
7177 *p++ = '\\';
7178 /* Fall through */
7179 default:
7180 *p = *m;
7181 }
7182 if (*m == '\0')
7183 break;
7184 }
7185
7186 if (p == escaped + size) {
7187 escaped[size - 1] = '\0';
7188 }
7189
7190 pbx_substitute_variables_helper(chan, escaped, output, size - 1);
7191 }
7192
7193 static void setup_mixmonitor(struct queue_ent *qe, const char *filename)
7194 {
7195 char escaped_filename[256];
7196 char file_with_ext[sizeof(escaped_filename) + sizeof(qe->parent->monfmt)];
7197 char mixmonargs[1512];
7198 char escaped_monitor_exec[1024];
7199 const char *monitor_options;
7200 const char *monitor_exec;
7201
7202 escaped_monitor_exec[0] = '\0';
7203
7204 if (filename) {
7205 escape_and_substitute(qe->chan, filename, escaped_filename, sizeof(escaped_filename));
7206 } else {
7207 ast_copy_string(escaped_filename, ast_channel_uniqueid(qe->chan), sizeof(escaped_filename));
7208 }
7209
7210 ast_channel_lock(qe->chan);
7211 if ((monitor_exec = pbx_builtin_getvar_helper(qe->chan, "MONITOR_EXEC"))) {
7212 monitor_exec = ast_strdupa(monitor_exec);
7213 }
7214 if ((monitor_options = pbx_builtin_getvar_helper(qe->chan, "MONITOR_OPTIONS"))) {
7215 monitor_options = ast_strdupa(monitor_options);
7216 } else {
7217 monitor_options = "";
7218 }
7219 ast_channel_unlock(qe->chan);
7220
7221 if (monitor_exec) {
7222 escape_and_substitute(qe->chan, monitor_exec, escaped_monitor_exec, sizeof(escaped_monitor_exec));
7223 }
7224
7225 snprintf(file_with_ext, sizeof(file_with_ext), "%s.%s", escaped_filename, qe->parent->monfmt);
7226
7227 if (!ast_strlen_zero(escaped_monitor_exec)) {
7228 snprintf(mixmonargs, sizeof(mixmonargs), "b%s,%s", monitor_options, escaped_monitor_exec);
7229 } else {
7230 snprintf(mixmonargs, sizeof(mixmonargs), "b%s", monitor_options);
7231 }
7232
7233 ast_debug(1, "Arguments being passed to MixMonitor: %s,%s\n", file_with_ext, mixmonargs);
7234
7235 if (ast_start_mixmonitor(qe->chan, file_with_ext, mixmonargs)) {
7236 ast_log(LOG_WARNING, "Unable to start mixmonitor. Is the MixMonitor app loaded?\n");
7237 }
7238 }
7239
7240 /*!
7241 * \internal
7242 * \brief A large function which calls members, updates statistics, and bridges the caller and a member
7243 *
7244 * Here is the process of this function
7245 * 1. Process any options passed to the Queue() application. Options here mean the third argument to Queue()
7246 * 2. Iterate trough the members of the queue, creating a callattempt corresponding to each member.
7247 * 3. Call ring_one to place a call to the appropriate member(s)
7248 * 4. Call wait_for_answer to wait for an answer. If no one answers, return.
7249 * 5. Take care of any holdtime announcements, member delays, or other options which occur after a call has been answered.
7250 * 6. Start the monitor or mixmonitor if the option is set
7251 * 7. Remove the caller from the queue to allow other callers to advance
7252 * 8. Bridge the call.
7253 * 9. Do any post processing after the call has disconnected.
7254 *
7255 * \param[in] qe the queue_ent structure which corresponds to the caller attempting to reach members
7256 * \param[in] opts the options passed as the third parameter to the Queue() application
7257 * \param[in] opt_args the options passed as the third parameter to the Queue() application
7258 * \param[in] announceoverride filename to play to user when waiting
7259 * \param[in] url the url passed as the fourth parameter to the Queue() application
7260 * \param[in,out] tries the number of times we have tried calling queue members
7261 * \param[out] noption set if the call to Queue() has the 'n' option set.
7262 * \param[in] agi the agi passed as the fifth parameter to the Queue() application
7263 * \param[in] gosub the gosub passed as the sixth parameter to the Queue() application
7264 * \param[in] ringing 1 if the 'r' option is set, otherwise 0
7265 */
7266 static int try_calling(struct queue_ent *qe, struct ast_flags opts, char **opt_args, char *announceoverride, const char *url, int *tries, int *noption, const char *agi, const char *gosub, int ringing)
7267 {
7268 struct member *cur;
7269 struct callattempt *outgoing = NULL; /* the list of calls we are building */
7270 int to, orig;
7271 char oldexten[AST_MAX_EXTENSION]="";
7272 char oldcontext[AST_MAX_CONTEXT]="";
7273 char queuename[256]="";
7274 struct ast_channel *peer;
7275 struct callattempt *lpeer;
7276 struct member *member;
7277 struct ast_app *application;
7278 int res = 0, bridge = 0;
7279 int numbusies = 0;
7280 int x=0;
7281 char *announce = NULL;
7282 char digit = 0;
7283 time_t now = time(NULL);
7284 struct ast_bridge_config bridge_config;
7285 char nondataquality = 1;
7286 char *agiexec = NULL;
7287 char *gosubexec = NULL;
7288 const char *monitorfilename;
7289 int forwardsallowed = 1;
7290 int block_connected_line = 0;
7291 struct ao2_iterator memi;
7292 struct queue_end_bridge *queue_end_bridge = NULL;
7293 int callcompletedinsl;
7294 time_t starttime;
7295
7296 memset(&bridge_config, 0, sizeof(bridge_config));
7297 time(&now);
7298
7299 /* If we've already exceeded our timeout, then just stop
7300 * This should be extremely rare. queue_exec will take care
7301 * of removing the caller and reporting the timeout as the reason.
7302 */
7303 if (qe->expire && now >= qe->expire) {
7304 res = 0;
7305 goto out;
7306 }
7307
7308 if (ast_test_flag(&opts, OPT_CALLEE_TRANSFER)) {
7309 ast_set_flag(&(bridge_config.features_callee), AST_FEATURE_REDIRECT);
7310 }
7311 if (ast_test_flag(&opts, OPT_CALLER_TRANSFER)) {
7312 ast_set_flag(&(bridge_config.features_caller), AST_FEATURE_REDIRECT);
7313 }
7314 if (ast_test_flag(&opts, OPT_CALLEE_AUTOMON)) {
7315 ast_set_flag(&(bridge_config.features_callee), AST_FEATURE_AUTOMON);
7316 }
7317 if (ast_test_flag(&opts, OPT_CALLER_AUTOMON)) {
7318 ast_set_flag(&(bridge_config.features_caller), AST_FEATURE_AUTOMON);
7319 }
7320 if (ast_test_flag(&opts, OPT_DATA_QUALITY)) {
7321 nondataquality = 0;
7322 }
7323 if (ast_test_flag(&opts, OPT_CALLEE_HANGUP)) {
7324 ast_set_flag(&(bridge_config.features_callee), AST_FEATURE_DISCONNECT);
7325 }
7326 if (ast_test_flag(&opts, OPT_CALLER_HANGUP)) {
7327 ast_set_flag(&(bridge_config.features_caller), AST_FEATURE_DISCONNECT);
7328 }
7329 if (ast_test_flag(&opts, OPT_CALLEE_PARK)) {
7330 ast_set_flag(&(bridge_config.features_callee), AST_FEATURE_PARKCALL);
7331 }
7332 if (ast_test_flag(&opts, OPT_CALLER_PARK)) {
7333 ast_set_flag(&(bridge_config.features_caller), AST_FEATURE_PARKCALL);
7334 }
7335 if (ast_test_flag(&opts, OPT_NO_RETRY)) {
7336 if (qe->parent->strategy == QUEUE_STRATEGY_RRMEMORY || qe->parent->strategy == QUEUE_STRATEGY_LINEAR
7337 || qe->parent->strategy == QUEUE_STRATEGY_RRORDERED) {
7338 (*tries)++;
7339 } else {
7340 *tries = ao2_container_count(qe->parent->members);
7341 }
7342 *noption = 1;
7343 }
7344 if (ast_test_flag(&opts, OPT_IGNORE_CALL_FW)) {
7345 forwardsallowed = 0;
7346 }
7347 if (ast_test_flag(&opts, OPT_IGNORE_CONNECTEDLINE)) {
7348 block_connected_line = 1;
7349 }
7350 if (ast_test_flag(&opts, OPT_CALLEE_AUTOMIXMON)) {
7351 ast_set_flag(&(bridge_config.features_callee), AST_FEATURE_AUTOMIXMON);
7352 }
7353 if (ast_test_flag(&opts, OPT_CALLER_AUTOMIXMON)) {
7354 ast_set_flag(&(bridge_config.features_caller), AST_FEATURE_AUTOMIXMON);
7355 }
7356 if (ast_test_flag(&opts, OPT_MARK_AS_ANSWERED)) {
7357 qe->cancel_answered_elsewhere = 1;
7358 }
7359
7360 /* if the calling channel has AST_CAUSE_ANSWERED_ELSEWHERE set, make sure this is inherited.
7361 (this is mainly to support unreal/local channels)
7362 */
7363 if (ast_channel_hangupcause(qe->chan) == AST_CAUSE_ANSWERED_ELSEWHERE) {
7364 qe->cancel_answered_elsewhere = 1;
7365 }
7366
7367 ao2_lock(qe->parent);
7368 ast_debug(1, "%s is trying to call a queue member.\n",
7369 ast_channel_name(qe->chan));
7370 ast_copy_string(queuename, qe->parent->name, sizeof(queuename));
7371 if (!ast_strlen_zero(qe->announce)) {
7372 announce = qe->announce;
7373 }
7374 if (!ast_strlen_zero(announceoverride)) {
7375 announce = announceoverride;
7376 }
7377
7378 memi = ao2_iterator_init(qe->parent->members, 0);
7379 while ((cur = ao2_iterator_next(&memi))) {
7380 struct callattempt *tmp = ast_calloc(1, sizeof(*tmp));
7381 if (!tmp) {
7382 ao2_ref(cur, -1);
7383 ao2_iterator_destroy(&memi);
7384 ao2_unlock(qe->parent);
7385 goto out;
7386 }
7387
7388 /*
7389 * Seed the callattempt's connected line information with previously
7390 * acquired connected line info from the queued channel. The
7391 * previously acquired connected line info could have been set
7392 * through the CONNECTED_LINE dialplan function.
7393 */
7394 ast_channel_lock(qe->chan);
7395 ast_party_connected_line_copy(&tmp->connected, ast_channel_connected(qe->chan));
7396 ast_channel_unlock(qe->chan);
7397
7398 tmp->block_connected_update = block_connected_line;
7399 tmp->stillgoing = 1;
7400 tmp->member = cur; /* Place the reference for cur into callattempt. */
7401 ast_copy_string(tmp->interface, cur->interface, sizeof(tmp->interface));
7402 /* Calculate the metric for the appropriate strategy. */
7403 if (!calc_metric(qe->parent, cur, x++, qe, tmp)) {
7404 /* Put them in the list of outgoing thingies... We're ready now.
7405 XXX If we're forcibly removed, these outgoing calls won't get
7406 hung up XXX */
7407 tmp->q_next = outgoing;
7408 outgoing = tmp;
7409 } else {
7410 callattempt_free(tmp);
7411 }
7412 }
7413 ao2_iterator_destroy(&memi);
7414
7415 if (qe->parent->timeoutpriority == TIMEOUT_PRIORITY_APP) {
7416 /* Application arguments have higher timeout priority (behaviour for <=1.6) */
7417 if (qe->expire && (!qe->parent->timeout || (qe->expire - now) <= qe->parent->timeout)) {
7418 to = (qe->expire - now) * 1000;
7419 } else {
7420 to = (qe->parent->timeout) ? qe->parent->timeout * 1000 : -1;
7421 }
7422 } else {
7423 /* Config timeout is higher priority thatn application timeout */
7424 if (qe->expire && qe->expire<=now) {
7425 to = 0;
7426 } else if (qe->parent->timeout) {
7427 to = qe->parent->timeout * 1000;
7428 } else {
7429 to = -1;
7430 }
7431 }
7432 orig = to;
7433 ++qe->pending;
7434 ao2_unlock(qe->parent);
7435 /* Call the queue members with the best metric now. */
7436 ring_one(qe, outgoing, &numbusies);
7437 lpeer = wait_for_answer(qe, outgoing, &to, &digit, numbusies,
7438 ast_test_flag(&(bridge_config.features_caller), AST_FEATURE_DISCONNECT),
7439 forwardsallowed);
7440
7441 ao2_lock(qe->parent);
7442 if (qe->parent->strategy == QUEUE_STRATEGY_RRMEMORY || qe->parent->strategy == QUEUE_STRATEGY_RRORDERED) {
7443 store_next_rr(qe, outgoing);
7444
7445 }
7446 if (qe->parent->strategy == QUEUE_STRATEGY_LINEAR) {
7447 store_next_lin(qe, outgoing);
7448 }
7449 ao2_unlock(qe->parent);
7450 peer = lpeer ? lpeer->chan : NULL;
7451 if (!peer) {
7452 qe->pending = 0;
7453 if (to) {
7454 /* Must gotten hung up */
7455 res = -1;
7456 } else {
7457 /* User exited by pressing a digit */
7458 res = digit;
7459 }
7460 if (res == -1) {
7461 ast_debug(1, "%s: Nobody answered.\n", ast_channel_name(qe->chan));
7462 }
7463 } else { /* peer is valid */
7464 RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
7465 RAII_VAR(struct ast_str *, interfacevar, ast_str_create(325), ast_free);
7466 /* Ah ha! Someone answered within the desired timeframe. Of course after this
7467 we will always return with -1 so that it is hung up properly after the
7468 conversation. */
7469 if (!strcmp(ast_channel_tech(qe->chan)->type, "DAHDI")) {
7470 ast_channel_setoption(qe->chan, AST_OPTION_TONE_VERIFY, &nondataquality, sizeof(nondataquality), 0);
7471 }
7472 if (!strcmp(ast_channel_tech(peer)->type, "DAHDI")) {
7473 ast_channel_setoption(peer, AST_OPTION_TONE_VERIFY, &nondataquality, sizeof(nondataquality), 0);
7474 }
7475 /* Update parameters for the queue */
7476 time(&now);
7477 recalc_holdtime(qe, (now - qe->start));
7478 member = lpeer->member;
7479 ao2_lock(qe->parent);
7480 callcompletedinsl = member->callcompletedinsl = ((now - qe->start) <= qe->parent->servicelevel);
7481 ao2_unlock(qe->parent);
7482 /* Increment the refcount for this member, since we're going to be using it for awhile in here. */
7483 ao2_ref(member, 1);
7484 hangupcalls(qe, outgoing, peer, qe->cancel_answered_elsewhere);
7485 outgoing = NULL;
7486 if (announce || qe->parent->reportholdtime || qe->parent->memberdelay) {
7487 int res2;
7488
7489 res2 = ast_autoservice_start(qe->chan);
7490 if (!res2) {
7491 if (qe->parent->memberdelay) {
7492 ast_log(LOG_NOTICE, "Delaying member connect for %d seconds\n", qe->parent->memberdelay);
7493 res2 = ast_safe_sleep(peer, qe->parent->memberdelay * 1000);
7494 }
7495 if (!res2 && announce) {
7496 char *front;
7497 char *announcefiles = ast_strdupa(announce);
7498 while ((front = ast_strsep(&announcefiles, '&', AST_STRSEP_STRIP | AST_STRSEP_TRIM))) {
7499 if (play_file(peer, front) < 0) {
7500 ast_log(LOG_ERROR, "play_file failed for '%s' on %s\n", front, ast_channel_name(peer));
7501 }
7502 }
7503 }
7504 if (!res2 && qe->parent->reportholdtime) {
7505 if (!play_file(peer, qe->parent->sound_reporthold)) {
7506 long holdtime, holdtimesecs;
7507
7508 time(&now);
7509 holdtime = labs((now - qe->start) / 60);
7510 holdtimesecs = labs((now - qe->start) % 60);
7511 if (holdtime > 0) {
7512 ast_say_number(peer, holdtime, AST_DIGIT_ANY, ast_channel_language(peer), "n");
7513 if (play_file(peer, qe->parent->sound_minutes) < 0) {
7514 ast_log(LOG_ERROR, "play_file failed for '%s' on %s\n", qe->parent->sound_minutes, ast_channel_name(peer));
7515 }
7516 }
7517 if (holdtimesecs > 1) {
7518 ast_say_number(peer, holdtimesecs, AST_DIGIT_ANY, ast_channel_language(peer), "n");
7519 if (play_file(peer, qe->parent->sound_seconds) < 0) {
7520 ast_log(LOG_ERROR, "play_file failed for '%s' on %s\n", qe->parent->sound_seconds, ast_channel_name(peer));
7521 }
7522 }
7523 }
7524 }
7525 ast_autoservice_stop(qe->chan);
7526 }
7527 if (ast_check_hangup(peer)) {
7528 /* Agent must have hung up */
7529 ast_log(LOG_WARNING, "Agent on %s hungup on the customer.\n", ast_channel_name(peer));
7530 ast_queue_log(queuename, ast_channel_uniqueid(qe->chan), member->membername, "AGENTDUMP", "%s", "");
7531
7532 blob = ast_json_pack("{s: s, s: s, s: s}",
7533 "Queue", queuename,
7534 "Interface", member->interface,
7535 "MemberName", member->membername);
7536 queue_publish_multi_channel_blob(qe->chan, peer, queue_agent_dump_type(), blob);
7537
7538 ast_channel_publish_dial(qe->chan, peer, member->interface, ast_hangup_cause_to_dial_status(ast_channel_hangupcause(peer)));
7539 ast_autoservice_chan_hangup_peer(qe->chan, peer);
7540 pending_members_remove(member);
7541 ao2_ref(member, -1);
7542 goto out;
7543 } else if (ast_check_hangup(qe->chan)) {
7544 /* Caller must have hung up just before being connected */
7545 ast_log(LOG_NOTICE, "Caller was about to talk to agent on %s but the caller hungup.\n", ast_channel_name(peer));
7546 ast_queue_log(queuename, ast_channel_uniqueid(qe->chan), member->membername, "ABANDON", "%d|%d|%ld", qe->pos, qe->opos, (long) (time(NULL) - qe->start));
7547 record_abandoned(qe);
7548 qe->handled = -1;
7549 ast_channel_publish_dial(qe->chan, peer, member->interface, ast_hangup_cause_to_dial_status(ast_channel_hangupcause(peer)));
7550 ast_autoservice_chan_hangup_peer(qe->chan, peer);
7551 pending_members_remove(member);
7552 ao2_ref(member, -1);
7553 return -1;
7554 }
7555 }
7556 /* Stop music on hold */
7557 if (ringing) {
7558 ast_indicate(qe->chan,-1);
7559 } else {
7560 ast_moh_stop(qe->chan);
7561 }
7562
7563 /* Make sure channels are compatible */
7564 res = ast_channel_make_compatible(qe->chan, peer);
7565 if (res < 0) {
7566 ast_queue_log(queuename, ast_channel_uniqueid(qe->chan), member->membername, "SYSCOMPAT", "%s", "");
7567 ast_log(LOG_WARNING, "Had to drop call because I couldn't make %s compatible with %s\n", ast_channel_name(qe->chan), ast_channel_name(peer));
7568 record_abandoned(qe);
7569 ast_channel_publish_dial(qe->chan, peer, member->interface, ast_hangup_cause_to_dial_status(ast_channel_hangupcause(peer)));
7570 ast_autoservice_chan_hangup_peer(qe->chan, peer);
7571 pending_members_remove(member);
7572 ao2_ref(member, -1);
7573 return -1;
7574 }
7575
7576 /* Play announcement to the caller telling it's his turn if defined */
7577 if (!ast_strlen_zero(qe->parent->sound_callerannounce)) {
7578 if (play_file(qe->chan, qe->parent->sound_callerannounce)) {
7579 ast_log(LOG_WARNING, "Announcement file '%s' is unavailable, continuing anyway...\n", qe->parent->sound_callerannounce);
7580 }
7581 }
7582
7583 ao2_lock(qe->parent);
7584 /* if setinterfacevar is defined, make member variables available to the channel */
7585 /* use pbx_builtin_setvar to set a load of variables with one call */
7586 if (qe->parent->setinterfacevar && interfacevar) {
7587 ast_str_set(&interfacevar, 0, "MEMBERINTERFACE=%s,MEMBERNAME=%s,MEMBERCALLS=%d,MEMBERLASTCALL=%ld,MEMBERPENALTY=%d,MEMBERDYNAMIC=%d,MEMBERREALTIME=%d",
7588 member->interface, member->membername, member->calls, (long)member->lastcall, member->penalty, member->dynamic, member->realtime);
7589 pbx_builtin_setvar_multiple(qe->chan, ast_str_buffer(interfacevar));
7590 pbx_builtin_setvar_multiple(peer, ast_str_buffer(interfacevar));
7591 }
7592
7593 /* if setqueueentryvar is defined, make queue entry (i.e. the caller) variables available to the channel */
7594 /* use pbx_builtin_setvar to set a load of variables with one call */
7595 if (qe->parent->setqueueentryvar && interfacevar) {
7596 ast_str_set(&interfacevar, 0, "QEHOLDTIME=%ld,QEORIGINALPOS=%d",
7597 (long) (time(NULL) - qe->start), qe->opos);
7598 pbx_builtin_setvar_multiple(qe->chan, ast_str_buffer(interfacevar));
7599 pbx_builtin_setvar_multiple(peer, ast_str_buffer(interfacevar));
7600 }
7601
7602 ao2_unlock(qe->parent);
7603
7604 /* try to set queue variables if configured to do so*/
7605 set_queue_variables(qe->parent, qe->chan);
7606 set_queue_variables(qe->parent, peer);
7607
7608 setup_peer_after_bridge_goto(qe->chan, peer, &opts, opt_args);
7609 ast_channel_lock(qe->chan);
7610 if ((monitorfilename = pbx_builtin_getvar_helper(qe->chan, "MONITOR_FILENAME"))) {
7611 monitorfilename = ast_strdupa(monitorfilename);
7612 }
7613 ast_channel_unlock(qe->chan);
7614
7615 /* Begin Monitoring */
7616 if (*qe->parent->monfmt) {
7617 setup_mixmonitor(qe, monitorfilename);
7618 }
7619 /* Drop out of the queue at this point, to prepare for next caller */
7620 leave_queue(qe);
7621 if (!ast_strlen_zero(url) && ast_channel_supports_html(peer)) {
7622 ast_debug(1, "app_queue: sendurl=%s.\n", url);
7623 ast_channel_sendurl(peer, url);
7624 }
7625
7626 /* run a gosub for this connection if defined. The gosub simply returns, no action is taken on the result */
7627 /* use gosub from dialplan if passed as a option, otherwise use the default queue gosub */
7628 if (!ast_strlen_zero(gosub)) {
7629 gosubexec = ast_strdupa(gosub);
7630 } else {
7631 if (qe->parent->membergosub) {
7632 gosubexec = ast_strdupa(qe->parent->membergosub);
7633 }
7634 }
7635
7636 if (!ast_strlen_zero(gosubexec)) {
7637 char *gosub_args = NULL;
7638 char *gosub_argstart;
7639
7640 ast_debug(1, "app_queue: gosub=%s.\n", gosubexec);
7641
7642 gosub_argstart = strchr(gosubexec, ',');
7643 if (gosub_argstart) {
7644 const char *what_is_s = "s";
7645 *gosub_argstart = 0;
7646 if (!ast_exists_extension(peer, gosubexec, "s", 1, S_COR(ast_channel_caller(peer)->id.number.valid, ast_channel_caller(peer)->id.number.str, NULL)) &&
7647 ast_exists_extension(peer, gosubexec, "~~s~~", 1, S_COR(ast_channel_caller(peer)->id.number.valid, ast_channel_caller(peer)->id.number.str, NULL))) {
7648 what_is_s = "~~s~~";
7649 }
7650 if (ast_asprintf(&gosub_args, "%s,%s,1(%s)", gosubexec, what_is_s, gosub_argstart + 1) < 0) {
7651 gosub_args = NULL;
7652 }
7653 *gosub_argstart = ',';
7654 } else {
7655 const char *what_is_s = "s";
7656 if (!ast_exists_extension(peer, gosubexec, "s", 1, S_COR(ast_channel_caller(peer)->id.number.valid, ast_channel_caller(peer)->id.number.str, NULL)) &&
7657 ast_exists_extension(peer, gosubexec, "~~s~~", 1, S_COR(ast_channel_caller(peer)->id.number.valid, ast_channel_caller(peer)->id.number.str, NULL))) {
7658 what_is_s = "~~s~~";
7659 }
7660 if (ast_asprintf(&gosub_args, "%s,%s,1", gosubexec, what_is_s) < 0) {
7661 gosub_args = NULL;
7662 }
7663 }
7664 if (gosub_args) {
7665 ast_app_exec_sub(qe->chan, peer, gosub_args, 0);
7666 ast_free(gosub_args);
7667 } else {
7668 ast_log(LOG_ERROR, "Could not Allocate string for Gosub arguments -- Gosub Call Aborted!\n");
7669 }
7670 }
7671
7672 if (!ast_strlen_zero(agi)) {
7673 ast_debug(1, "app_queue: agi=%s.\n", agi);
7674 application = pbx_findapp("agi");
7675 if (application) {
7676 agiexec = ast_strdupa(agi);
7677 pbx_exec(qe->chan, application, agiexec);
7678 } else {
7679 ast_log(LOG_WARNING, "Asked to execute an AGI on this channel, but could not find application (agi)!\n");
7680 }
7681 }
7682 qe->handled++;
7683
7684 ast_queue_log(queuename, ast_channel_uniqueid(qe->chan), member->membername, "CONNECT", "%ld|%s|%ld", (long) (time(NULL) - qe->start), ast_channel_uniqueid(peer),
7685 (long)(orig - to > 0 ? (orig - to) / 1000 : 0));
7686 /* Queue hold time until agent answered */
7687 set_duration_var(qe->chan, "QUEUEWAIT", (int64_t)(time(NULL) - qe->start) * 1000);
7688
7689 blob = ast_json_pack("{s: s, s: s, s: s, s: I, s: I}",
7690 "Queue", queuename,
7691 "Interface", member->interface,
7692 "MemberName", member->membername,
7693 "HoldTime", (ast_json_int_t)(time(NULL) - qe->start),
7694 "RingTime", (ast_json_int_t)(orig - to > 0 ? (orig - to) / 1000 : 0));
7695 queue_publish_multi_channel_blob(qe->chan, peer, queue_agent_connect_type(), blob);
7696
7697 ast_copy_string(oldcontext, ast_channel_context(qe->chan), sizeof(oldcontext));
7698 ast_copy_string(oldexten, ast_channel_exten(qe->chan), sizeof(oldexten));
7699
7700 if ((queue_end_bridge = ao2_alloc(sizeof(*queue_end_bridge), NULL))) {
7701 queue_end_bridge->q = qe->parent;
7702 queue_end_bridge->chan = qe->chan;
7703 queue_end_bridge->start_time = ast_tvnow();
7704 bridge_config.end_bridge_callback = end_bridge_callback;
7705 bridge_config.end_bridge_callback_data = queue_end_bridge;
7706 bridge_config.end_bridge_callback_data_fixup = end_bridge_callback_data_fixup;
7707 /* Since queue_end_bridge can survive beyond the life of this call to Queue, we need
7708 * to make sure to increase the refcount of this queue so it cannot be freed until we
7709 * are done with it. We remove this reference in end_bridge_callback.
7710 */
7711 queue_t_ref(qe->parent, "For bridge_config reference");
7712 }
7713
7714 ao2_lock(qe->parent);
7715 time(&member->starttime);
7716 starttime = member->starttime;
7717 ao2_unlock(qe->parent);
7718 /* As a queue member may end up in multiple calls at once if a transfer occurs with
7719 * a Local channel in the mix we pass the current call information (starttime) to the
7720 * Stasis subscriptions so when they update the queue member data it becomes a noop
7721 * if this call is no longer between the caller and the queue member.
7722 */
7723 setup_stasis_subs(qe, peer, member, qe->start, starttime, callcompletedinsl);
7724 bridge = ast_bridge_call_with_flags(qe->chan, peer, &bridge_config,
7725 AST_BRIDGE_FLAG_MERGE_INHIBIT_FROM | AST_BRIDGE_FLAG_MERGE_INHIBIT_TO | AST_BRIDGE_FLAG_SWAP_INHIBIT_FROM);
7726
7727 res = bridge ? bridge : 1;
7728 ao2_ref(member, -1);
7729 }
7730 out:
7731 hangupcalls(qe, outgoing, NULL, qe->cancel_answered_elsewhere);
7732
7733 return res;
7734 }
7735
7736 static int wait_a_bit(struct queue_ent *qe)
7737 {
7738 /* Don't need to hold the lock while we setup the outgoing calls */
7739 int retrywait = qe->parent->retry * 1000;
7740
7741 int res = ast_waitfordigit(qe->chan, retrywait);
7742 if (res > 0 && !valid_exit(qe, res)) {
7743 res = 0;
7744 }
7745
7746 return res;
7747 }
7748
7749 static struct member *interface_exists(struct call_queue *q, const char *interface)
7750 {
7751 struct member *mem;
7752 struct ao2_iterator mem_iter;
7753
7754 if (!q) {
7755 return NULL;
7756 }
7757 mem_iter = ao2_iterator_init(q->members, 0);
7758 while ((mem = ao2_iterator_next(&mem_iter))) {
7759 if (!strcasecmp(interface, mem->interface)) {
7760 ao2_iterator_destroy(&mem_iter);
7761 return mem;
7762 }
7763 ao2_ref(mem, -1);
7764 }
7765 ao2_iterator_destroy(&mem_iter);
7766
7767 return NULL;
7768 }
7769
7770
7771 /*! \brief Dump all members in a specific queue to the database
7772 * \code
7773 * <pm_family>/<queuename> = <interface>;<penalty>;<paused>;<state_interface>[|...]
7774 * \endcode
7775 */
7776 static void dump_queue_members(struct call_queue *pm_queue)
7777 {
7778 struct member *cur_member;
7779 struct ast_str *value;
7780 struct ao2_iterator mem_iter;
7781
7782 if (!pm_queue) {
7783 return;
7784 }
7785
7786 /* 4K is a reasonable default for most applications, but we grow to
7787 * accommodate more if necessary. */
7788 if (!(value = ast_str_create(4096))) {
7789 return;
7790 }
7791
7792 mem_iter = ao2_iterator_init(pm_queue->members, 0);
7793 while ((cur_member = ao2_iterator_next(&mem_iter))) {
7794 if (!cur_member->dynamic) {
7795 ao2_ref(cur_member, -1);
7796 continue;
7797 }
7798
7799 ast_str_append(&value, 0, "%s%s;%d;%d;%s;%s;%s;%d",
7800 ast_str_strlen(value) ? "|" : "",
7801 cur_member->interface,
7802 cur_member->penalty,
7803 cur_member->paused,
7804 cur_member->membername,
7805 cur_member->state_interface,
7806 cur_member->reason_paused,
7807 cur_member->wrapuptime);
7808
7809 ao2_ref(cur_member, -1);
7810 }
7811 ao2_iterator_destroy(&mem_iter);
7812
7813 if (ast_str_strlen(value) && !cur_member) {
7814 if (ast_db_put(pm_family, pm_queue->name, ast_str_buffer(value))) {
7815 ast_log(LOG_WARNING, "failed to create persistent dynamic entry!\n");
7816 }
7817 } else {
7818 /* Delete the entry if the queue is empty or there is an error */
7819 ast_db_del(pm_family, pm_queue->name);
7820 }
7821
7822 ast_free(value);
7823 }
7824
7825 /*! \brief Remove member from queue
7826 * \retval RES_NOT_DYNAMIC when they aren't a RT member
7827 * \retval RES_NOSUCHQUEUE queue does not exist
7828 * \retval RES_OKAY removed member from queue
7829 * \retval RES_EXISTS queue exists but no members
7830 */
7831 static int remove_from_queue(const char *queuename, const char *interface)
7832 {
7833 struct call_queue *q, tmpq = {
7834 .name = queuename,
7835 };
7836 struct member *mem, tmpmem;
7837 int res = RES_NOSUCHQUEUE;
7838
7839 ast_copy_string(tmpmem.interface, interface, sizeof(tmpmem.interface));
7840 if ((q = ao2_t_find(queues, &tmpq, OBJ_POINTER, "Temporary reference for interface removal"))) {
7841 ao2_lock(q);
7842 if ((mem = ao2_find(q->members, &tmpmem, OBJ_POINTER))) {
7843 /* XXX future changes should beware of this assumption!! */
7844 /*Change Penalty on realtime users*/
7845 if (mem->realtime && !ast_strlen_zero(mem->rt_uniqueid) && negative_penalty_invalid) {
7846 update_realtime_member_field(mem, q->name, "penalty", "-1");
7847 } else if (!mem->dynamic) {
7848 ao2_ref(mem, -1);
7849 ao2_unlock(q);
7850 queue_t_unref(q, "Interface wasn't dynamic, expiring temporary reference");
7851 return RES_NOT_DYNAMIC;
7852 }
7853 queue_publish_member_blob(queue_member_removed_type(), queue_member_blob_create(q, mem));
7854
7855 member_remove_from_queue(q, mem);
7856 ao2_ref(mem, -1);
7857
7858 if (queue_persistent_members) {
7859 dump_queue_members(q);
7860 }
7861
7862 if (!num_available_members(q)) {
7863 ast_devstate_changed(AST_DEVICE_INUSE, AST_DEVSTATE_CACHABLE, "Queue:%s_avail", q->name);
7864 }
7865
7866 res = RES_OKAY;
7867 } else {
7868 res = RES_EXISTS;
7869 }
7870 ao2_unlock(q);
7871 queue_t_unref(q, "Expiring temporary reference");
7872 }
7873
7874 return res;
7875 }
7876
7877 /*! \brief Add member to queue
7878 * \retval RES_NOT_DYNAMIC when they aren't a RT member
7879 * \retval RES_NOSUCHQUEUE queue does not exist
7880 * \retval RES_OKAY added member from queue
7881 * \retval RES_EXISTS queue exists but no members
7882 * \retval RES_OUT_OF_MEMORY queue exists but not enough memory to create member
7883 */
7884 static int add_to_queue(const char *queuename, const char *interface, const char *membername, int penalty, int paused, int dump, const char *state_interface, const char *reason_paused, int wrapuptime)
7885 {
7886 struct call_queue *q;
7887 struct member *new_member, *old_member;
7888 int res = RES_NOSUCHQUEUE;
7889
7890 /*! \note Ensure the appropriate realtime queue is loaded. Note that this
7891 * short-circuits if the queue is already in memory. */
7892 if (!(q = find_load_queue_rt_friendly(queuename))) {
7893 return res;
7894 }
7895
7896 ao2_lock(q);
7897 if ((old_member = interface_exists(q, interface)) == NULL) {
7898 if ((new_member = create_queue_member(interface, membername, penalty, paused, state_interface, q->ringinuse, wrapuptime))) {
7899 new_member->dynamic = 1;
7900 if (reason_paused) {
7901 ast_copy_string(new_member->reason_paused, reason_paused, sizeof(new_member->reason_paused));
7902 }
7903 member_add_to_queue(q, new_member);
7904 queue_publish_member_blob(queue_member_added_type(), queue_member_blob_create(q, new_member));
7905
7906 if (is_member_available(q, new_member)) {
7907 ast_devstate_changed(AST_DEVICE_NOT_INUSE, AST_DEVSTATE_CACHABLE, "Queue:%s_avail", q->name);
7908 }
7909
7910 ao2_ref(new_member, -1);
7911 new_member = NULL;
7912
7913 if (dump) {
7914 dump_queue_members(q);
7915 }
7916
7917 res = RES_OKAY;
7918 } else {
7919 res = RES_OUTOFMEMORY;
7920 }
7921 } else {
7922 ao2_ref(old_member, -1);
7923 res = RES_EXISTS;
7924 }
7925 ao2_unlock(q);
7926 queue_t_unref(q, "Expiring temporary reference");
7927
7928 return res;
7929 }
7930
7931
7932 /*! \brief Change priority caller into a queue
7933 * \retval RES_NOSUCHQUEUE queue does not exist
7934 * \retval RES_OKAY change priority
7935 * \retval RES_NOT_CALLER queue exists but no caller
7936 */
7937 static int change_priority_caller_on_queue(const char *queuename, const char *caller, int priority, int immediate)
7938 {
7939 struct call_queue *q;
7940 struct queue_ent *current, *prev = NULL, *caller_qe = NULL;
7941 int res = RES_NOSUCHQUEUE;
7942
7943 /*! \note Ensure the appropriate realtime queue is loaded. Note that this
7944 * short-circuits if the queue is already in memory. */
7945 if (!(q = find_load_queue_rt_friendly(queuename))) {
7946 return res;
7947 }
7948
7949 ao2_lock(q);
7950 res = RES_NOT_CALLER;
7951 for (current = q->head; current; current = current->next) {
7952 if (strcmp(ast_channel_name(current->chan), caller) == 0) {
7953 ast_debug(1, "%s Caller new priority %d in queue %s\n",
7954 caller, priority, queuename);
7955 current->prio = priority;
7956 if (immediate) {
7957 /* This caller is being immediately moved in the queue so remove them */
7958 if (prev) {
7959 prev->next = current->next;
7960 } else {
7961 q->head = current->next;
7962 }
7963 caller_qe = current;
7964 /* The position for all callers is not recalculated in here as it will
7965 * be updated when the moved caller is inserted back into the queue
7966 */
7967 }
7968 res = RES_OKAY;
7969 break;
7970 } else if (immediate) {
7971 prev = current;
7972 }
7973 }
7974
7975 if (caller_qe) {
7976 int inserted = 0, pos = 0;
7977
7978 /* If a caller queue entry exists, we are applying their priority immediately
7979 * and have to reinsert them at the correct position.
7980 */
7981 prev = NULL;
7982 current = q->head;
7983 while (current) {
7984 if (!inserted && (caller_qe->prio > current->prio)) {
7985 insert_entry(q, prev, caller_qe, &pos);
7986 inserted = 1;
7987 }
7988
7989 /* We always update the position as it may have changed */
7990 current->pos = ++pos;
7991
7992 /* Move to the next caller in the queue */
7993 prev = current;
7994 current = current->next;
7995 }
7996
7997 if (!inserted) {
7998 insert_entry(q, prev, caller_qe, &pos);
7999 }
8000 }
8001
8002 ao2_unlock(q);
8003 return res;
8004 }
8005
8006
8007 /*! \brief Request to withdraw a caller from a queue
8008 * \retval RES_NOSUCHQUEUE queue does not exist
8009 * \retval RES_OKAY withdraw request sent
8010 * \retval RES_NOT_CALLER queue exists but no caller
8011 * \retval RES_EXISTS a withdraw request was already sent for this caller (channel) and queue
8012 */
8013 static int request_withdraw_caller_from_queue(const char *queuename, const char *caller, const char *withdraw_info)
8014 {
8015 struct call_queue *q;
8016 struct queue_ent *qe;
8017 int res = RES_NOSUCHQUEUE;
8018
8019 /*! \note Ensure the appropriate realtime queue is loaded. Note that this
8020 * short-circuits if the queue is already in memory. */
8021 if (!(q = find_load_queue_rt_friendly(queuename))) {
8022 return res;
8023 }
8024
8025 ao2_lock(q);
8026 res = RES_NOT_CALLER;
8027 for (qe = q->head; qe; qe = qe->next) {
8028 if (!strcmp(ast_channel_name(qe->chan), caller)) {
8029 if (qe->withdraw) {
8030 ast_debug(1, "Ignoring duplicate withdraw request of caller %s from queue %s\n", caller, queuename);
8031 res = RES_EXISTS;
8032 } else {
8033 ast_debug(1, "Requested withdraw of caller %s from queue %s\n", caller, queuename);
8034 /* It is not possible to change the withdraw info by further withdraw requests for this caller (channel)
8035 in this queue, so we do not need to worry about a memory leak here. */
8036 if (withdraw_info) {
8037 qe->withdraw_info = ast_strdup(withdraw_info);
8038 }
8039 qe->withdraw = 1;
8040 res = RES_OKAY;
8041 }
8042 break;
8043 }
8044 }
8045 ao2_unlock(q);
8046 queue_unref(q);
8047
8048 return res;
8049 }
8050
8051
8052 static int publish_queue_member_pause(struct call_queue *q, struct member *member)
8053 {
8054 struct ast_json *json_blob = queue_member_blob_create(q, member);
8055
8056 if (!json_blob) {
8057 return -1;
8058 }
8059
8060 queue_publish_member_blob(queue_member_pause_type(), json_blob);
8061
8062 return 0;
8063 }
8064
8065 /*!
8066 * \internal
8067 * \brief Set the pause status of the specific queue member.
8068 *
8069 * \param q Which queue the member belongs.
8070 * \param mem Queue member being paused/unpaused.
8071 * \param reason Why is this happening (Can be NULL/empty for no reason given.)
8072 * \param paused Set to 1 if the member is being paused or 0 to unpause.
8073 *
8074 * \pre The q is locked on entry.
8075 */
8076 static void set_queue_member_pause(struct call_queue *q, struct member *mem, const char *reason, int paused)
8077 {
8078 if (mem->paused == paused) {
8079 ast_debug(1, "%spausing already-%spaused queue member %s:%s\n",
8080 (paused ? "" : "un"), (paused ? "" : "un"), q->name, mem->interface);
8081 if (log_unpause_on_reason_change && paused) {
8082 if (!ast_strings_equal(mem->reason_paused, reason)) {
8083 ast_queue_log(q->name, "NONE", mem->membername, "UNPAUSE", "%s", "Auto-Unpause");
8084 }
8085 }
8086 }
8087
8088 if (mem->realtime && !ast_strlen_zero(mem->rt_uniqueid)) {
8089 if (realtime_reason_paused) {
8090 if (ast_update_realtime("queue_members", "uniqueid", mem->rt_uniqueid, "reason_paused", S_OR(reason, ""), "paused", paused ? "1" : "0", SENTINEL) < 0) {
8091 ast_log(LOG_WARNING, "Failed update of realtime queue member %s:%s %spause and reason '%s'\n",
8092 q->name, mem->interface, (paused ? "" : "un"), S_OR(reason, ""));
8093 }
8094 } else {
8095 if (ast_update_realtime("queue_members", "uniqueid", mem->rt_uniqueid, "paused", paused ? "1" : "0", SENTINEL) < 0) {
8096 ast_log(LOG_WARNING, "Failed %spause update of realtime queue member %s:%s\n",
8097 (paused ? "" : "un"), q->name, mem->interface);
8098 }
8099 }
8100 }
8101
8102 mem->paused = paused;
8103 if (paused) {
8104 time(&mem->lastpause); /* update last pause field */
8105 }
8106 if (paused && !ast_strlen_zero(reason)) {
8107 ast_copy_string(mem->reason_paused, reason, sizeof(mem->reason_paused));
8108 } else {
8109 /* We end up filling this in again later (temporarily) but we need it
8110 * empty for now so that the intervening code - specifically
8111 * dump_queue_members() - has the correct view of things. */
8112 mem->reason_paused[0] = '\0';
8113 }
8114
8115 ast_devstate_changed(mem->paused ? QUEUE_PAUSED_DEVSTATE : QUEUE_UNPAUSED_DEVSTATE,
8116 AST_DEVSTATE_CACHABLE, "Queue:%s_pause_%s", q->name, mem->interface);
8117
8118 if (queue_persistent_members) {
8119 dump_queue_members(q);
8120 }
8121
8122 if (is_member_available(q, mem)) {
8123 ast_devstate_changed(AST_DEVICE_NOT_INUSE, AST_DEVSTATE_CACHABLE,
8124 "Queue:%s_avail", q->name);
8125 } else if (!num_available_members(q)) {
8126 ast_devstate_changed(AST_DEVICE_INUSE, AST_DEVSTATE_CACHABLE,
8127 "Queue:%s_avail", q->name);
8128 }
8129
8130 if (!paused && !ast_strlen_zero(reason)) {
8131 /* Because we've been unpaused with a 'reason' we need to ensure that
8132 * that reason is emitted when the subsequent PauseQueueMember event
8133 * is raised. So temporarily set it on the member and clear it out
8134 * again right after. */
8135 ast_copy_string(mem->reason_paused, reason, sizeof(mem->reason_paused));
8136 }
8137
8138 ast_queue_log(q->name, "NONE", mem->membername, paused ? "PAUSE" : "UNPAUSE",
8139 "%s", mem->reason_paused);
8140
8141 publish_queue_member_pause(q, mem);
8142
8143 if (!paused) {
8144 mem->reason_paused[0] = '\0';
8145 }
8146 }
8147
8148 static int set_member_paused(const char *queuename, const char *interface, const char *reason, int paused)
8149 {
8150 int found = 0;
8151 struct call_queue *q;
8152 struct ao2_iterator queue_iter;
8153
8154 if (ast_check_realtime("queues")) {
8155 load_realtime_queues(queuename);
8156 }
8157
8158 queue_iter = ao2_iterator_init(queues, 0);
8159 while ((q = ao2_t_iterator_next(&queue_iter, "Iterate over queues"))) {
8160 ao2_lock(q);
8161 if (ast_strlen_zero(queuename) || !strcasecmp(q->name, queuename)) {
8162 struct member *mem;
8163
8164 if ((mem = interface_exists(q, interface))) {
8165 /*
8166 * Before we do the PAUSE/UNPAUSE, log if this was a
8167 * PAUSEALL/UNPAUSEALL but only on the first found entry.
8168 */
8169 ++found;
8170 if (found == 1
8171 && ast_strlen_zero(queuename)) {
8172 /*
8173 * XXX In all other cases, we use the queue name,
8174 * but since this affects all queues, we cannot.
8175 */
8176 ast_queue_log("NONE", "NONE", mem->membername,
8177 (paused ? "PAUSEALL" : "UNPAUSEALL"), "%s", S_OR(reason, ""));
8178 }
8179
8180 set_queue_member_pause(q, mem, reason, paused);
8181 ao2_ref(mem, -1);
8182 }
8183
8184 if (!ast_strlen_zero(queuename)) {
8185 ao2_unlock(q);
8186 queue_t_unref(q, "Done with iterator");
8187 break;
8188 }
8189 }
8190
8191 ao2_unlock(q);
8192 queue_t_unref(q, "Done with iterator");
8193 }
8194 ao2_iterator_destroy(&queue_iter);
8195
8196 return found ? RESULT_SUCCESS : RESULT_FAILURE;
8197 }
8198
8199 /*!
8200 * \internal
8201 * \brief helper function for set_member_penalty - given a queue, sets all member penalties with the interface
8202 * \param[in] q queue which is having its member's penalty changed - must be unlocked prior to calling
8203 * \param[in] interface String of interface used to search for queue members being changed
8204 * \param[in] penalty Value penalty is being changed to for the member.
8205 * \retval 0 if the there is no member with interface belonging to q and no change is made
8206 * \retval 1 if the there is a member with interface belonging to q and changes are made
8207 */
8208 static int set_member_penalty_help_members(struct call_queue *q, const char *interface, int penalty)
8209 {
8210 struct member *mem;
8211 int foundinterface = 0;
8212
8213 ao2_lock(q);
8214 if ((mem = interface_exists(q, interface))) {
8215 foundinterface++;
8216 if (mem->realtime) {
8217 char rtpenalty[80];
8218
8219 sprintf(rtpenalty, "%i", penalty);
8220 update_realtime_member_field(mem, q->name, "penalty", rtpenalty);
8221 }
8222
8223 mem->penalty = penalty;
8224
8225 ast_queue_log(q->name, "NONE", interface, "PENALTY", "%d", penalty);
8226 queue_publish_member_blob(queue_member_penalty_type(), queue_member_blob_create(q, mem));
8227 ao2_ref(mem, -1);
8228 }
8229 ao2_unlock(q);
8230
8231 return foundinterface;
8232 }
8233
8234 /*!
8235 * \internal
8236 * \brief Set the ringinuse value of the specific queue member.
8237 *
8238 * \param q Which queue the member belongs.
8239 * \param mem Queue member being set.
8240 * \param ringinuse Set to 1 if the member is called when inuse.
8241 *
8242 * \pre The q is locked on entry.
8243 */
8244 static void set_queue_member_ringinuse(struct call_queue *q, struct member *mem, int ringinuse)
8245 {
8246 if (mem->realtime) {
8247 update_realtime_member_field(mem, q->name, realtime_ringinuse_field,
8248 ringinuse ? "1" : "0");
8249 }
8250
8251 mem->ringinuse = ringinuse;
8252
8253 ast_queue_log(q->name, "NONE", mem->interface, "RINGINUSE", "%d", ringinuse);
8254 queue_publish_member_blob(queue_member_ringinuse_type(), queue_member_blob_create(q, mem));
8255 }
8256
8257 static int set_member_ringinuse_help_members(struct call_queue *q, const char *interface, int ringinuse)
8258 {
8259 struct member *mem;
8260 int foundinterface = 0;
8261
8262 ao2_lock(q);
8263 if ((mem = interface_exists(q, interface))) {
8264 foundinterface++;
8265 set_queue_member_ringinuse(q, mem, ringinuse);
8266 ao2_ref(mem, -1);
8267 }
8268 ao2_unlock(q);
8269
8270 return foundinterface;
8271 }
8272
8273 static int set_member_value_help_members(struct call_queue *q, const char *interface, int property, int value)
8274 {
8275 switch(property) {
8276 case MEMBER_PENALTY:
8277 return set_member_penalty_help_members(q, interface, value);
8278
8279 case MEMBER_RINGINUSE:
8280 return set_member_ringinuse_help_members(q, interface, value);
8281
8282 default:
8283 ast_log(LOG_ERROR, "Attempted to set invalid property\n");
8284 return 0;
8285 }
8286 }
8287
8288 /*!
8289 * \internal
8290 * \brief Sets members penalty, if queuename=NULL we set member penalty in all the queues.
8291 * \param[in] queuename If specified, only act on a member if it belongs to this queue
8292 * \param[in] interface Interface of queue member(s) having priority set.
8293 * \param[in] property Which queue property is being set
8294 * \param[in] value Value penalty is being changed to for each member
8295 */
8296 static int set_member_value(const char *queuename, const char *interface, int property, int value)
8297 {
8298 int foundinterface = 0, foundqueue = 0;
8299 struct call_queue *q;
8300 struct ast_config *queue_config = NULL;
8301 struct ao2_iterator queue_iter;
8302
8303 /* property dependent restrictions on values should be checked in this switch */
8304 switch (property) {
8305 case MEMBER_PENALTY:
8306 if (value < 0 && !negative_penalty_invalid) {
8307 ast_log(LOG_ERROR, "Invalid penalty (%d)\n", value);
8308 return RESULT_FAILURE;
8309 }
8310 }
8311
8312 if (ast_strlen_zero(queuename)) { /* This means we need to iterate through all the queues. */
8313 if (ast_check_realtime("queues")) {
8314 queue_config = ast_load_realtime_multientry("queues", "name LIKE", "%", SENTINEL);
8315 if (queue_config) {
8316 char *category = NULL;
8317 while ((category = ast_category_browse(queue_config, category))) {
8318 const char *name = ast_variable_retrieve(queue_config, category, "name");
8319 if (ast_strlen_zero(name)) {
8320 ast_log(LOG_WARNING, "Ignoring realtime queue with a NULL or empty 'name.'\n");
8321 continue;
8322 }
8323 if ((q = find_load_queue_rt_friendly(name))) {
8324 foundqueue++;
8325 foundinterface += set_member_value_help_members(q, interface, property, value);
8326 queue_unref(q);
8327 }
8328 }
8329
8330 ast_config_destroy(queue_config);
8331 }
8332 }
8333
8334 /* After hitting realtime queues, go back and get the regular ones. */
8335 queue_iter = ao2_iterator_init(queues, 0);
8336 while ((q = ao2_t_iterator_next(&queue_iter, "Iterate through queues"))) {
8337 foundqueue++;
8338 foundinterface += set_member_value_help_members(q, interface, property, value);
8339 queue_unref(q);
8340 }
8341 ao2_iterator_destroy(&queue_iter);
8342 } else { /* We actually have a queuename, so we can just act on the single queue. */
8343 if ((q = find_load_queue_rt_friendly(queuename))) {
8344 foundqueue++;
8345 foundinterface += set_member_value_help_members(q, interface, property, value);
8346 queue_unref(q);
8347 }
8348 }
8349
8350 if (foundinterface) {
8351 return RESULT_SUCCESS;
8352 } else if (!foundqueue) {
8353 ast_log (LOG_ERROR, "Invalid queuename\n");
8354 } else {
8355 ast_log (LOG_ERROR, "Invalid interface\n");
8356 }
8357
8358 return RESULT_FAILURE;
8359 }
8360
8361 /*!
8362 * \brief Gets members penalty.
8363 * \return Return the members penalty or RESULT_FAILURE on error.
8364 */
8365 static int get_member_penalty(char *queuename, char *interface)
8366 {
8367 int foundqueue = 0, penalty;
8368 struct call_queue *q;
8369 struct member *mem;
8370
8371 if ((q = find_load_queue_rt_friendly(queuename))) {
8372 foundqueue = 1;
8373 ao2_lock(q);
8374 if ((mem = interface_exists(q, interface))) {
8375 penalty = mem->penalty;
8376 ao2_ref(mem, -1);
8377 ao2_unlock(q);
8378 queue_t_unref(q, "Search complete");
8379 return penalty;
8380 }
8381 ao2_unlock(q);
8382 queue_t_unref(q, "Search complete");
8383 }
8384
8385 /* some useful debugging */
8386 if (foundqueue) {
8387 ast_log (LOG_ERROR, "Invalid queuename\n");
8388 } else {
8389 ast_log (LOG_ERROR, "Invalid interface\n");
8390 }
8391
8392 return RESULT_FAILURE;
8393 }
8394
8395 /*! \brief Reload dynamic queue members persisted into the astdb */
8396 static void reload_queue_members(void)
8397 {
8398 char *cur_ptr;
8399 const char *queue_name;
8400 char *member;
8401 char *interface;
8402 char *membername = NULL;
8403 char *state_interface;
8404 char *penalty_tok;
8405 int penalty = 0;
8406 char *paused_tok;
8407 int paused = 0;
8408 char *wrapuptime_tok;
8409 int wrapuptime = 0;
8410 char *reason_paused;
8411 struct ast_db_entry *db_tree;
8412 struct ast_db_entry *entry;
8413 struct call_queue *cur_queue;
8414 char *queue_data;
8415
8416 /* Each key in 'pm_family' is the name of a queue */
8417 db_tree = ast_db_gettree(pm_family, NULL);
8418 for (entry = db_tree; entry; entry = entry->next) {
8419
8420 queue_name = entry->key + strlen(pm_family) + 2;
8421
8422 {
8423 struct call_queue tmpq = {
8424 .name = queue_name,
8425 };
8426 cur_queue = ao2_t_find(queues, &tmpq, OBJ_POINTER, "Reload queue members");
8427 }
8428
8429 if (!cur_queue) {
8430 cur_queue = find_load_queue_rt_friendly(queue_name);
8431 }
8432
8433 if (!cur_queue) {
8434 /* If the queue no longer exists, remove it from the
8435 * database */
8436 ast_log(LOG_WARNING, "Error loading persistent queue: '%s': it does not exist\n", queue_name);
8437 ast_db_del(pm_family, queue_name);
8438 continue;
8439 }
8440
8441 if (ast_db_get_allocated(pm_family, queue_name, &queue_data)) {
8442 queue_t_unref(cur_queue, "Expire reload reference");
8443 continue;
8444 }
8445
8446 cur_ptr = queue_data;
8447 while ((member = strsep(&cur_ptr, ",|"))) {
8448 if (ast_strlen_zero(member)) {
8449 continue;
8450 }
8451
8452 interface = strsep(&member, ";");
8453 penalty_tok = strsep(&member, ";");
8454 paused_tok = strsep(&member, ";");
8455 membername = strsep(&member, ";");
8456 state_interface = strsep(&member, ";");
8457 reason_paused = strsep(&member, ";");
8458 wrapuptime_tok = strsep(&member, ";");
8459
8460 if (!penalty_tok) {
8461 ast_log(LOG_WARNING, "Error parsing persistent member string for '%s' (penalty)\n", queue_name);
8462 break;
8463 }
8464 penalty = strtol(penalty_tok, NULL, 10);
8465 if (errno == ERANGE) {
8466 ast_log(LOG_WARNING, "Error converting penalty: %s: Out of range.\n", penalty_tok);
8467 break;
8468 }
8469
8470 if (!paused_tok) {
8471 ast_log(LOG_WARNING, "Error parsing persistent member string for '%s' (paused)\n", queue_name);
8472 break;
8473 }
8474 paused = strtol(paused_tok, NULL, 10);
8475 if ((errno == ERANGE) || paused < 0 || paused > 1) {
8476 ast_log(LOG_WARNING, "Error converting paused: %s: Expected 0 or 1.\n", paused_tok);
8477 break;
8478 }
8479
8480 if (!ast_strlen_zero(wrapuptime_tok)) {
8481 wrapuptime = strtol(wrapuptime_tok, NULL, 10);
8482 if (errno == ERANGE) {
8483 ast_log(LOG_WARNING, "Error converting wrapuptime: %s: Out of range.\n", wrapuptime_tok);
8484 break;
8485 }
8486 }
8487
8488 ast_debug(1, "Reload Members: Queue: %s Member: %s Name: %s Penalty: %d Paused: %d ReasonPause: %s Wrapuptime: %d\n",
8489 queue_name, interface, membername, penalty, paused, reason_paused, wrapuptime);
8490
8491 if (add_to_queue(queue_name, interface, membername, penalty, paused, 0, state_interface, reason_paused, wrapuptime) == RES_OUTOFMEMORY) {
8492 ast_log(LOG_ERROR, "Out of Memory when reloading persistent queue member\n");
8493 break;
8494 }
8495 }
8496 queue_t_unref(cur_queue, "Expire reload reference");
8497 ast_free(queue_data);
8498 }
8499
8500 if (db_tree) {
8501 ast_log(LOG_NOTICE, "Queue members successfully reloaded from database.\n");
8502 ast_db_freetree(db_tree);
8503 }
8504 }
8505
8506 /*! \brief PauseQueueMember application */
8507 static int pqm_exec(struct ast_channel *chan, const char *data)
8508 {
8509 char *parse;
8510 AST_DECLARE_APP_ARGS(args,
8511 AST_APP_ARG(queuename);
8512 AST_APP_ARG(interface);
8513 AST_APP_ARG(options);
8514 AST_APP_ARG(reason);
8515 );
8516
8517 if (ast_strlen_zero(data)) {
8518 ast_log(LOG_WARNING, "PauseQueueMember requires an argument ([queuename],interface[,options][,reason])\n");
8519 return -1;
8520 }
8521
8522 parse = ast_strdupa(data);
8523
8524 AST_STANDARD_APP_ARGS(args, parse);
8525
8526 if (ast_strlen_zero(args.interface)) {
8527 ast_log(LOG_WARNING, "Missing interface argument to PauseQueueMember ([queuename],interface[,options[,reason]])\n");
8528 return -1;
8529 }
8530
8531 if (set_member_paused(args.queuename, args.interface, args.reason, 1)) {
8532 ast_log(LOG_WARNING, "Attempt to pause interface %s, not found\n", args.interface);
8533 pbx_builtin_setvar_helper(chan, "PQMSTATUS", "NOTFOUND");
8534 return 0;
8535 }
8536
8537 pbx_builtin_setvar_helper(chan, "PQMSTATUS", "PAUSED");
8538
8539 return 0;
8540 }
8541
8542 /*! \brief UnpauseQueueMember application */
8543 static int upqm_exec(struct ast_channel *chan, const char *data)
8544 {
8545 char *parse;
8546 AST_DECLARE_APP_ARGS(args,
8547 AST_APP_ARG(queuename);
8548 AST_APP_ARG(interface);
8549 AST_APP_ARG(options);
8550 AST_APP_ARG(reason);
8551 );
8552
8553 if (ast_strlen_zero(data)) {
8554 ast_log(LOG_WARNING, "UnpauseQueueMember requires an argument ([queuename],interface[,options[,reason]])\n");
8555 return -1;
8556 }
8557
8558 parse = ast_strdupa(data);
8559
8560 AST_STANDARD_APP_ARGS(args, parse);
8561
8562 if (ast_strlen_zero(args.interface)) {
8563 ast_log(LOG_WARNING, "Missing interface argument to UnpauseQueueMember ([queuename],interface[,options[,reason]])\n");
8564 return -1;
8565 }
8566
8567 if (set_member_paused(args.queuename, args.interface, args.reason, 0)) {
8568 ast_log(LOG_WARNING, "Attempt to unpause interface %s, not found\n", args.interface);
8569 pbx_builtin_setvar_helper(chan, "UPQMSTATUS", "NOTFOUND");
8570 return 0;
8571 }
8572
8573 pbx_builtin_setvar_helper(chan, "UPQMSTATUS", "UNPAUSED");
8574
8575 return 0;
8576 }
8577
8578 /*! \brief RemoveQueueMember application */
8579 static int rqm_exec(struct ast_channel *chan, const char *data)
8580 {
8581 int res=-1;
8582 char *parse, *temppos = NULL;
8583 struct member *mem = NULL;
8584
8585 AST_DECLARE_APP_ARGS(args,
8586 AST_APP_ARG(queuename);
8587 AST_APP_ARG(interface);
8588 );
8589
8590
8591 if (ast_strlen_zero(data)) {
8592 ast_log(LOG_WARNING, "RemoveQueueMember requires an argument (queuename[,interface])\n");
8593 return -1;
8594 }
8595
8596 parse = ast_strdupa(data);
8597
8598 AST_STANDARD_APP_ARGS(args, parse);
8599
8600 if (ast_strlen_zero(args.interface)) {
8601 args.interface = ast_strdupa(ast_channel_name(chan));
8602 temppos = strrchr(args.interface, '-');
8603 if (temppos) {
8604 *temppos = '\0';
8605 }
8606 }
8607
8608 ast_debug(1, "queue: %s, member: %s\n", args.queuename, args.interface);
8609
8610 if (log_membername_as_agent) {
8611 mem = find_member_by_queuename_and_interface(args.queuename, args.interface);
8612 }
8613
8614 switch (remove_from_queue(args.queuename, args.interface)) {
8615 case RES_OKAY:
8616 if (!mem || ast_strlen_zero(mem->membername)) {
8617 ast_queue_log(args.queuename, ast_channel_uniqueid(chan), args.interface, "REMOVEMEMBER", "%s", "");
8618 } else {
8619 ast_queue_log(args.queuename, ast_channel_uniqueid(chan), mem->membername, "REMOVEMEMBER", "%s", "");
8620 }
8621 ast_log(LOG_NOTICE, "Removed interface '%s' from queue '%s'\n", args.interface, args.queuename);
8622 pbx_builtin_setvar_helper(chan, "RQMSTATUS", "REMOVED");
8623 res = 0;
8624 break;
8625 case RES_EXISTS:
8626 ast_debug(1, "Unable to remove interface '%s' from queue '%s': Not there\n", args.interface, args.queuename);
8627 pbx_builtin_setvar_helper(chan, "RQMSTATUS", "NOTINQUEUE");
8628 res = 0;
8629 break;
8630 case RES_NOSUCHQUEUE:
8631 ast_log(LOG_WARNING, "Unable to remove interface from queue '%s': No such queue\n", args.queuename);
8632 pbx_builtin_setvar_helper(chan, "RQMSTATUS", "NOSUCHQUEUE");
8633 res = 0;
8634 break;
8635 case RES_NOT_DYNAMIC:
8636 ast_log(LOG_WARNING, "Unable to remove interface from queue '%s': '%s' is not a dynamic member\n", args.queuename, args.interface);
8637 pbx_builtin_setvar_helper(chan, "RQMSTATUS", "NOTDYNAMIC");
8638 res = 0;
8639 break;
8640 }
8641
8642 if (mem) {
8643 ao2_ref(mem, -1);
8644 }
8645
8646 return res;
8647 }
8648
8649 /*! \brief AddQueueMember application */
8650 static int aqm_exec(struct ast_channel *chan, const char *data)
8651 {
8652 int res=-1;
8653 char *parse, *tmp, *temppos = NULL, *reason = NULL;
8654 AST_DECLARE_APP_ARGS(args,
8655 AST_APP_ARG(queuename);
8656 AST_APP_ARG(interface);
8657 AST_APP_ARG(penalty);
8658 AST_APP_ARG(options);
8659 AST_APP_ARG(membername);
8660 AST_APP_ARG(state_interface);
8661 AST_APP_ARG(wrapuptime);
8662 );
8663 int penalty = 0;
8664 int paused = 0;
8665 int wrapuptime;
8666 struct ast_flags flags = { 0 };
8667
8668 if (ast_strlen_zero(data)) {
8669 ast_log(LOG_WARNING, "AddQueueMember requires an argument (queuename[,interface[,penalty[,options[,membername[,stateinterface][,wrapuptime]]]]])\n");
8670 return -1;
8671 }
8672
8673 parse = ast_strdupa(data);
8674
8675 AST_STANDARD_APP_ARGS(args, parse);
8676
8677 if (args.options) {
8678 char *opts[AQM_OPT_ARG_ARRAY_SIZE] = { NULL, };
8679 ast_app_parse_options(aqm_opts, &flags, opts, args.options);
8680 if (ast_test_flag(&flags, AQMFLAG_PAUSED)) {
8681 paused = 1;
8682 if (ast_test_flag(&flags, AQMFLAG_REASON) && !ast_strlen_zero(opts[AQM_OPT_ARG_PAUSE_REASON])) {
8683 reason = ast_strdupa(opts[AQM_OPT_ARG_PAUSE_REASON]);
8684 }
8685 }
8686 }
8687
8688 if (ast_strlen_zero(args.interface)) {
8689 args.interface = ast_strdupa(ast_channel_name(chan));
8690 temppos = strrchr(args.interface, '-');
8691 if (temppos) {
8692 *temppos = '\0';
8693 }
8694 }
8695
8696 if (!ast_strlen_zero(args.penalty)) {
8697 if ((sscanf(args.penalty, "%30d", &penalty) != 1) || penalty < 0) {
8698 ast_log(LOG_WARNING, "Penalty '%s' is invalid, must be an integer >= 0\n", args.penalty);
8699 penalty = 0;
8700 }
8701 }
8702
8703 if (!ast_strlen_zero(args.wrapuptime)) {
8704 tmp = args.wrapuptime;
8705 ast_strip(tmp);
8706 wrapuptime = atoi(tmp);
8707 if (wrapuptime < 0) {
8708 wrapuptime = 0;
8709 }
8710 } else {
8711 wrapuptime = 0;
8712 }
8713
8714 switch (add_to_queue(args.queuename, args.interface, args.membername, penalty, paused, queue_persistent_members, args.state_interface, reason, wrapuptime)) {
8715 case RES_OKAY:
8716 if (ast_strlen_zero(args.membername) || !log_membername_as_agent) {
8717 ast_queue_log(args.queuename, ast_channel_uniqueid(chan), args.interface, "ADDMEMBER", "%s", paused ? "PAUSED" : "");
8718 } else {
8719 ast_queue_log(args.queuename, ast_channel_uniqueid(chan), args.membername, "ADDMEMBER", "%s", paused ? "PAUSED" : "");
8720 }
8721 ast_log(LOG_NOTICE, "Added interface '%s' to queue '%s'\n", args.interface, args.queuename);
8722 pbx_builtin_setvar_helper(chan, "AQMSTATUS", "ADDED");
8723 res = 0;
8724 break;
8725 case RES_EXISTS:
8726 ast_log(LOG_WARNING, "Unable to add interface '%s' to queue '%s': Already there\n", args.interface, args.queuename);
8727 pbx_builtin_setvar_helper(chan, "AQMSTATUS", "MEMBERALREADY");
8728 res = 0;
8729 break;
8730 case RES_NOSUCHQUEUE:
8731 ast_log(LOG_WARNING, "Unable to add interface to queue '%s': No such queue\n", args.queuename);
8732 pbx_builtin_setvar_helper(chan, "AQMSTATUS", "NOSUCHQUEUE");
8733 res = 0;
8734 break;
8735 case RES_OUTOFMEMORY:
8736 ast_log(LOG_ERROR, "Out of memory adding interface %s to queue %s\n", args.interface, args.queuename);
8737 break;
8738 }
8739
8740 return res;
8741 }
8742
8743 /*! \brief QueueLog application */
8744 static int ql_exec(struct ast_channel *chan, const char *data)
8745 {
8746 char *parse;
8747
8748 AST_DECLARE_APP_ARGS(args,
8749 AST_APP_ARG(queuename);
8750 AST_APP_ARG(uniqueid);
8751 AST_APP_ARG(membername);
8752 AST_APP_ARG(event);
8753 AST_APP_ARG(params);
8754 );
8755
8756 if (ast_strlen_zero(data)) {
8757 ast_log(LOG_WARNING, "QueueLog requires arguments (queuename,uniqueid,membername,event[,additionalinfo]\n");
8758 return -1;
8759 }
8760
8761 parse = ast_strdupa(data);
8762
8763 AST_STANDARD_APP_ARGS(args, parse);
8764
8765 if (ast_strlen_zero(args.queuename) || ast_strlen_zero(args.uniqueid)
8766 || ast_strlen_zero(args.membername) || ast_strlen_zero(args.event)) {
8767 ast_log(LOG_WARNING, "QueueLog requires arguments (queuename,uniqueid,membername,event[,additionalinfo])\n");
8768 return -1;
8769 }
8770
8771 ast_queue_log(args.queuename, args.uniqueid, args.membername, args.event,
8772 "%s", args.params ? args.params : "");
8773
8774 return 0;
8775 }
8776
8777 /*! \brief Copy rule from global list into specified queue */
8778 static void copy_rules(struct queue_ent *qe, const char *rulename)
8779 {
8780 struct penalty_rule *pr_iter;
8781 struct rule_list *rl_iter;
8782 const char *tmp = ast_strlen_zero(rulename) ? qe->parent->defaultrule : rulename;
8783 AST_LIST_LOCK(&rule_lists);
8784 AST_LIST_TRAVERSE(&rule_lists, rl_iter, list) {
8785 if (!strcasecmp(rl_iter->name, tmp)) {
8786 break;
8787 }
8788 }
8789 if (rl_iter) {
8790 AST_LIST_TRAVERSE(&rl_iter->rules, pr_iter, list) {
8791 struct penalty_rule *new_pr = ast_calloc(1, sizeof(*new_pr));
8792 if (!new_pr) {
8793 ast_log(LOG_ERROR, "Memory allocation error when copying penalty rules! Aborting!\n");
8794 break;
8795 }
8796 new_pr->time = pr_iter->time;
8797 new_pr->max_value = pr_iter->max_value;
8798 new_pr->min_value = pr_iter->min_value;
8799 new_pr->raise_value = pr_iter->raise_value;
8800 new_pr->max_relative = pr_iter->max_relative;
8801 new_pr->min_relative = pr_iter->min_relative;
8802 new_pr->raise_relative = pr_iter->raise_relative;
8803 new_pr->raise_respect_min = pr_iter->raise_respect_min;
8804 AST_LIST_INSERT_TAIL(&qe->qe_rules, new_pr, list);
8805 }
8806 }
8807 AST_LIST_UNLOCK(&rule_lists);
8808 }
8809
8810 /*!\brief The starting point for all queue calls
8811 *
8812 * The process involved here is to
8813 * 1. Parse the options specified in the call to Queue()
8814 * 2. Join the queue
8815 * 3. Wait in a loop until it is our turn to try calling a queue member
8816 * 4. Attempt to call a queue member
8817 * 5. If 4. did not result in a bridged call, then check for between
8818 * call options such as periodic announcements etc.
8819 * 6. Try 4 again unless some condition (such as an expiration time) causes us to
8820 * exit the queue.
8821 */
8822 static int queue_exec(struct ast_channel *chan, const char *data)
8823 {
8824 int res=-1;
8825 int ringing=0;
8826 const char *user_priority;
8827 const char *max_penalty_str;
8828 const char *min_penalty_str;
8829 const char *raise_penalty_str;
8830 int prio;
8831 int qcontinue = 0;
8832 int max_penalty, min_penalty, raise_penalty;
8833 enum queue_result reason = QUEUE_UNKNOWN;
8834 /* whether to exit Queue application after the timeout hits */
8835 int tries = 0;
8836 int noption = 0;
8837 char *parse;
8838 int makeannouncement = 0;
8839 int position = 0;
8840 AST_DECLARE_APP_ARGS(args,
8841 AST_APP_ARG(queuename);
8842 AST_APP_ARG(options);
8843 AST_APP_ARG(url);
8844 AST_APP_ARG(announceoverride);
8845 AST_APP_ARG(queuetimeoutstr);
8846 AST_APP_ARG(agi);
8847 AST_APP_ARG(gosub);
8848 AST_APP_ARG(rule);
8849 AST_APP_ARG(position);
8850 );
8851 /* Our queue entry */
8852 struct queue_ent qe = { 0 };
8853 struct ast_flags opts = { 0, };
8854 char *opt_args[OPT_ARG_ARRAY_SIZE];
8855 int max_forwards;
8856 int cid_allow;
8857 /* Reset variables to avoid stale data */
8858 pbx_builtin_setvar_helper(chan, "ANSWEREDTIME", "");
8859 pbx_builtin_setvar_helper(chan, "ANSWEREDTIME_MS", "");
8860 pbx_builtin_setvar_helper(chan, "DIALEDTIME", "");
8861 pbx_builtin_setvar_helper(chan, "DIALEDTIME_MS", "");
8862 pbx_builtin_setvar_helper(chan, "QUEUEWAIT", "");
8863 pbx_builtin_setvar_helper(chan, "QUEUEWAIT_MS", "");
8864
8865 if (ast_strlen_zero(data)) {
8866 ast_log(LOG_WARNING, "Queue requires an argument: queuename[,options[,URL[,announceoverride[,timeout[,agi[,gosub[,rule[,position]]]]]]]]\n");
8867 return -1;
8868 }
8869
8870 ast_channel_lock(chan);
8871 max_forwards = ast_max_forwards_get(chan);
8872 ast_channel_unlock(chan);
8873
8874 if (max_forwards <= 0) {
8875 ast_log(LOG_WARNING, "Channel '%s' cannot enter queue. Max forwards exceeded\n", ast_channel_name(chan));
8876 return -1;
8877 }
8878
8879 parse = ast_strdupa(data);
8880 AST_STANDARD_APP_ARGS(args, parse);
8881
8882 ast_debug(1, "queue: %s, options: %s, url: %s, announce: %s, timeout: %s, agi: %s, gosub: %s, rule: %s, position: %s\n",
8883 args.queuename,
8884 S_OR(args.options, ""),
8885 S_OR(args.url, ""),
8886 S_OR(args.announceoverride, ""),
8887 S_OR(args.queuetimeoutstr, ""),
8888 S_OR(args.agi, ""),
8889 S_OR(args.gosub, ""),
8890 S_OR(args.rule, ""),
8891 S_OR(args.position, ""));
8892
8893 if (!ast_strlen_zero(args.options)) {
8894 ast_app_parse_options(queue_exec_options, &opts, opt_args, args.options);
8895 }
8896
8897 /* Setup our queue entry */
8898 qe.start = time(NULL);
8899
8900 pbx_builtin_setvar_helper(chan, "ABANDONED", NULL);
8901
8902 /* set the expire time based on the supplied timeout; */
8903 if (!ast_strlen_zero(args.queuetimeoutstr)) {
8904 qe.expire = qe.start + atoi(args.queuetimeoutstr);
8905 } else {
8906 qe.expire = 0;
8907 }
8908
8909 /* Get the priority from the variable ${QUEUE_PRIO} */
8910 ast_channel_lock(chan);
8911 user_priority = pbx_builtin_getvar_helper(chan, "QUEUE_PRIO");
8912 if (user_priority) {
8913 if (sscanf(user_priority, "%30d", &prio) == 1) {
8914 ast_debug(1, "%s: Got priority %d from ${QUEUE_PRIO}.\n", ast_channel_name(chan), prio);
8915 } else {
8916 ast_log(LOG_WARNING, "${QUEUE_PRIO}: Invalid value (%s), channel %s.\n",
8917 user_priority, ast_channel_name(chan));
8918 prio = 0;
8919 }
8920 } else {
8921 ast_debug(3, "NO QUEUE_PRIO variable found. Using default.\n");
8922 prio = 0;
8923 }
8924
8925 /* Get the maximum penalty from the variable ${QUEUE_MAX_PENALTY} */
8926
8927 if ((max_penalty_str = pbx_builtin_getvar_helper(chan, "QUEUE_MAX_PENALTY"))) {
8928 if (sscanf(max_penalty_str, "%30d", &max_penalty) == 1) {
8929 ast_debug(1, "%s: Got max penalty %d from ${QUEUE_MAX_PENALTY}.\n", ast_channel_name(chan), max_penalty);
8930 } else {
8931 ast_log(LOG_WARNING, "${QUEUE_MAX_PENALTY}: Invalid value (%s), channel %s.\n",
8932 max_penalty_str, ast_channel_name(chan));
8933 max_penalty = INT_MAX;
8934 }
8935 } else {
8936 max_penalty = INT_MAX;
8937 }
8938
8939 if ((min_penalty_str = pbx_builtin_getvar_helper(chan, "QUEUE_MIN_PENALTY"))) {
8940 if (sscanf(min_penalty_str, "%30d", &min_penalty) == 1) {
8941 ast_debug(1, "%s: Got min penalty %d from ${QUEUE_MIN_PENALTY}.\n", ast_channel_name(chan), min_penalty);
8942 } else {
8943 ast_log(LOG_WARNING, "${QUEUE_MIN_PENALTY}: Invalid value (%s), channel %s.\n",
8944 min_penalty_str, ast_channel_name(chan));
8945 min_penalty = INT_MAX;
8946 }
8947 } else {
8948 min_penalty = INT_MAX;
8949 }
8950
8951 if ((raise_penalty_str = pbx_builtin_getvar_helper(chan, "QUEUE_RAISE_PENALTY"))) {
8952 if (*raise_penalty_str == 'r') {
8953 qe.raise_respect_min = 1;
8954 raise_penalty_str++;
8955 } else {
8956 qe.raise_respect_min = 0;
8957 }
8958 if (sscanf(raise_penalty_str, "%30d", &raise_penalty) == 1) {
8959 ast_debug(1, "%s: Got raise penalty %s%d from ${QUEUE_RAISE_PENALTY}.\n", ast_channel_name(chan), qe.raise_respect_min ? "r" : "", raise_penalty);
8960 } else {
8961 ast_log(LOG_WARNING, "${QUEUE_RAISE_PENALTY}: Invalid value (%s), channel %s.\n",
8962 raise_penalty_str, ast_channel_name(chan));
8963 raise_penalty = INT_MAX;
8964 }
8965 } else {
8966 raise_penalty = INT_MAX;
8967 }
8968 ast_channel_unlock(chan);
8969
8970 if (ast_test_flag(&opts, OPT_RINGING)) {
8971 ringing = 1;
8972 }
8973
8974 if (ringing != 1 && ast_test_flag(&opts, OPT_RING_WHEN_RINGING)) {
8975 qe.ring_when_ringing = 1;
8976 }
8977
8978 if (ast_test_flag(&opts, OPT_GO_ON)) {
8979 qcontinue = 1;
8980 }
8981
8982 if (args.position) {
8983 position = atoi(args.position);
8984 if (position < 0) {
8985 ast_log(LOG_WARNING, "Invalid position '%s' given for call to queue '%s'. Assuming no preference for position\n", args.position, args.queuename);
8986 position = 0;
8987 }
8988 }
8989
8990 ast_debug(1, "queue: %s, expires: %ld, priority: %d\n",
8991 args.queuename, (long)qe.expire, prio);
8992
8993 qe.chan = chan;
8994 qe.prio = prio;
8995 qe.max_penalty = max_penalty;
8996 qe.min_penalty = min_penalty;
8997 qe.raise_penalty = raise_penalty;
8998 qe.last_pos_said = 0;
8999 qe.last_pos = 0;
9000 qe.last_periodic_announce_time = time(NULL);
9001 qe.last_periodic_announce_sound = 0;
9002 qe.valid_digits = 0;
9003 if (join_queue(args.queuename, &qe, &reason, position)) {
9004 ast_log(LOG_WARNING, "Unable to join queue '%s'\n", args.queuename);
9005 set_queue_result(chan, reason);
9006 return 0;
9007 }
9008 ast_assert(qe.parent != NULL);
9009
9010 if (qe.parent->periodicannouncestartdelay >= 0) {
9011 qe.last_periodic_announce_time += qe.parent->periodicannouncestartdelay;
9012 qe.last_periodic_announce_time -= qe.parent->periodicannouncefrequency;
9013 }
9014
9015 cid_allow = qe.parent->log_restricted_caller_id || ((ast_party_id_presentation(&ast_channel_caller(chan)->id) & AST_PRES_RESTRICTION) == AST_PRES_ALLOWED);
9016
9017 if (log_caller_id_name) {
9018 char *escaped_cidname = NULL;
9019 /* Ensure caller ID name is valid and not NULL before processing */
9020 if (cid_allow && ast_channel_caller(chan)->id.name.valid && ast_channel_caller(chan)->id.name.str) {
9021 escaped_cidname = ast_strdupa(ast_channel_caller(chan)->id.name.str);
9022 /* Only iterate if '|' is found */
9023 if (strchr(escaped_cidname, '|')) {
9024 for (char *p = escaped_cidname; *p; p++) {
9025 if (*p == '|') {
9026 *p = '_';
9027 }
9028 }
9029 }
9030 }
9031
9032 ast_queue_log(args.queuename, ast_channel_uniqueid(chan), "NONE", "ENTERQUEUE", "%s|%s|%d|%s",
9033 S_OR(args.url, ""),
9034 S_COR(cid_allow && ast_channel_caller(chan)->id.number.valid, ast_channel_caller(chan)->id.number.str, ""),
9035 qe.opos,
9036 S_OR(escaped_cidname, ""));
9037 } else {
9038 ast_queue_log(args.queuename, ast_channel_uniqueid(chan), "NONE", "ENTERQUEUE", "%s|%s|%d",
9039 S_OR(args.url, ""),
9040 S_COR(cid_allow && ast_channel_caller(chan)->id.number.valid, ast_channel_caller(chan)->id.number.str, ""),
9041 qe.opos);
9042 }
9043
9044 /* PREDIAL: Preprocess any callee gosub arguments. */
9045 if (ast_test_flag(&opts, OPT_PREDIAL_CALLEE)
9046 && !ast_strlen_zero(opt_args[OPT_ARG_PREDIAL_CALLEE])) {
9047 ast_replace_subargument_delimiter(opt_args[OPT_ARG_PREDIAL_CALLEE]);
9048 qe.predial_callee = opt_args[OPT_ARG_PREDIAL_CALLEE];
9049 }
9050
9051 /* PREDIAL: Run gosub on the caller's channel */
9052 if (ast_test_flag(&opts, OPT_PREDIAL_CALLER)
9053 && !ast_strlen_zero(opt_args[OPT_ARG_PREDIAL_CALLER])) {
9054 ast_replace_subargument_delimiter(opt_args[OPT_ARG_PREDIAL_CALLER]);
9055 ast_app_exec_sub(NULL, chan, opt_args[OPT_ARG_PREDIAL_CALLER], 0);
9056 }
9057
9058 /* Music on hold class override */
9059 if (ast_test_flag(&opts, OPT_MUSICONHOLD_CLASS)
9060 && !ast_strlen_zero(opt_args[OPT_ARG_MUSICONHOLD_CLASS])) {
9061 ast_copy_string(qe.moh, opt_args[OPT_ARG_MUSICONHOLD_CLASS], sizeof(qe.moh));
9062 }
9063
9064 copy_rules(&qe, args.rule);
9065 qe.pr = AST_LIST_FIRST(&qe.qe_rules);
9066 check_turns:
9067 if (ringing) {
9068 ast_indicate(chan, AST_CONTROL_RINGING);
9069 } else {
9070 ast_moh_start(chan, qe.moh, NULL);
9071 }
9072
9073 /* This is the wait loop for callers 2 through maxlen */
9074 res = wait_our_turn(&qe, ringing, &reason);
9075 if (res) {
9076 goto stop;
9077 }
9078
9079 makeannouncement = qe.parent->announce_to_first_user;
9080
9081 for (;;) {
9082 /* This is the wait loop for the head caller*/
9083 /* To exit, they may get their call answered; */
9084 /* they may dial a digit from the queue context; */
9085 /* or, they may timeout. */
9086
9087 /* A request to withdraw this call from the queue arrived */
9088 if (qe.withdraw) {
9089 reason = QUEUE_WITHDRAW;
9090 res = 1;
9091 break;
9092 }
9093
9094 /* Leave if we have exceeded our queuetimeout */
9095 if (qe.expire && (time(NULL) >= qe.expire)) {
9096 record_abandoned(&qe);
9097 reason = QUEUE_TIMEOUT;
9098 res = 0;
9099 ast_queue_log(args.queuename, ast_channel_uniqueid(chan),"NONE", "EXITWITHTIMEOUT", "%d|%d|%ld",
9100 qe.pos, qe.opos, (long) (time(NULL) - qe.start));
9101 break;
9102 }
9103
9104 if (makeannouncement) {
9105 /* Make a position announcement, if enabled */
9106 if (qe.parent->announcefrequency) {
9107 if ((res = say_position(&qe, ringing))) {
9108 goto stop;
9109 }
9110 }
9111
9112 /* Make a periodic announcement, if enabled */
9113 if (qe.parent->periodicannouncefrequency) {
9114 if ((res = say_periodic_announcement(&qe, ringing))) {
9115 goto stop;
9116 }
9117 }
9118 }
9119
9120 /* A request to withdraw this call from the queue arrived */
9121 if (qe.withdraw) {
9122 reason = QUEUE_WITHDRAW;
9123 res = 1;
9124 break;
9125 }
9126
9127 /* Leave if we have exceeded our queuetimeout */
9128 if (qe.expire && (time(NULL) >= qe.expire)) {
9129 record_abandoned(&qe);
9130 reason = QUEUE_TIMEOUT;
9131 res = 0;
9132 ast_queue_log(args.queuename, ast_channel_uniqueid(chan), "NONE", "EXITWITHTIMEOUT",
9133 "%d|%d|%ld", qe.pos, qe.opos, (long) (time(NULL) - qe.start));
9134 break;
9135 }
9136
9137 /* see if we need to move to the next penalty level for this queue */
9138 while (qe.pr && ((time(NULL) - qe.start) > qe.pr->time)) {
9139 update_qe_rule(&qe);
9140 }
9141
9142 /* Try calling all queue members for 'timeout' seconds */
9143 res = try_calling(&qe, opts, opt_args, args.announceoverride, args.url, &tries, &noption, args.agi, args.gosub, ringing);
9144 if (res) {
9145 goto stop;
9146 }
9147
9148 if (qe.parent->leavewhenempty) {
9149 int status = 0;
9150 if ((status = get_member_status(qe.parent, qe.max_penalty, qe.min_penalty, qe.raise_penalty, qe.parent->leavewhenempty, 0, qe.raise_respect_min))) {
9151 record_abandoned(&qe);
9152 reason = QUEUE_LEAVEEMPTY;
9153 ast_queue_log(args.queuename, ast_channel_uniqueid(chan), "NONE", "EXITEMPTY", "%d|%d|%ld", qe.pos, qe.opos, (long)(time(NULL) - qe.start));
9154 res = 0;
9155 break;
9156 }
9157 }
9158
9159 /* exit after 'timeout' cycle if 'n' option enabled */
9160 if (noption && tries >= ao2_container_count(qe.parent->members)) {
9161 ast_verb(3, "Exiting on time-out cycle\n");
9162 ast_queue_log(args.queuename, ast_channel_uniqueid(chan), "NONE", "EXITWITHTIMEOUT",
9163 "%d|%d|%ld", qe.pos, qe.opos, (long) (time(NULL) - qe.start));
9164 record_abandoned(&qe);
9165 reason = QUEUE_TIMEOUT;
9166 res = 0;
9167 break;
9168 }
9169
9170
9171 /* Leave if we have exceeded our queuetimeout */
9172 if (qe.expire && (time(NULL) >= qe.expire)) {
9173 record_abandoned(&qe);
9174 reason = QUEUE_TIMEOUT;
9175 res = 0;
9176 ast_queue_log(qe.parent->name, ast_channel_uniqueid(qe.chan),"NONE", "EXITWITHTIMEOUT", "%d|%d|%ld", qe.pos, qe.opos, (long) (time(NULL) - qe.start));
9177 break;
9178 }
9179
9180 /* OK, we didn't get anybody; wait for 'retry' seconds; may get a digit to exit with */
9181 res = wait_a_bit(&qe);
9182 if (res) {
9183 goto stop;
9184 }
9185
9186 /* If using dynamic realtime members, we should regenerate the member list for this queue */
9187 update_realtime_members(qe.parent);
9188
9189 /* Since this is a priority queue and
9190 * it is not sure that we are still at the head
9191 * of the queue, go and check for our turn again.
9192 */
9193 if (!is_our_turn(&qe)) {
9194 ast_debug(1, "Darn priorities, going back in queue (%s)!\n", ast_channel_name(qe.chan));
9195 goto check_turns;
9196 }
9197 }
9198
9199 stop:
9200 if (qe.chan) {
9201 ast_channel_lock(qe.chan);
9202 ast_channel_stage_snapshot(qe.chan);
9203 /* 1. Handle QUEUEWAIT (Total time spent waiting in queue) */
9204 if (ast_strlen_zero(pbx_builtin_getvar_helper(qe.chan, "QUEUEWAIT"))) {
9205 set_duration_var(qe.chan, "QUEUEWAIT", (int64_t)(time(NULL) - qe.start) * 1000);
9206 }
9207
9208 /* 2. Handle DIALEDTIME (Total time spent from beginning of the call) */
9209 if (ast_strlen_zero(pbx_builtin_getvar_helper(qe.chan, "DIALEDTIME"))) {
9210 set_duration_var(qe.chan, "DIALEDTIME", ast_channel_get_duration_ms(qe.chan));
9211 }
9212
9213 /* 3. Handle ANSWEREDTIME (Time spent talking to an agent) */
9214 if (ast_strlen_zero(pbx_builtin_getvar_helper(qe.chan, "ANSWEREDTIME"))) {
9215 /* If we are here and it's still empty, the call was never answered */
9216 set_duration_var(qe.chan, "ANSWEREDTIME", 0);
9217 }
9218 ast_channel_stage_snapshot_done(qe.chan);
9219 ast_channel_unlock(qe.chan);
9220 }
9221 if (res) {
9222 if (reason == QUEUE_WITHDRAW) {
9223 record_abandoned(&qe);
9224 ast_queue_log(qe.parent->name, ast_channel_uniqueid(qe.chan), "NONE", "WITHDRAW", "%d|%d|%ld|%.40s", qe.pos, qe.opos, (long) (time(NULL) - qe.start), qe.withdraw_info ? qe.withdraw_info : "");
9225 if (qe.withdraw_info) {
9226 pbx_builtin_setvar_helper(qe.chan, "QUEUE_WITHDRAW_INFO", qe.withdraw_info);
9227 }
9228 res = 0;
9229 } else if (res < 0) {
9230 if (!qe.handled) {
9231 record_abandoned(&qe);
9232 ast_queue_log(args.queuename, ast_channel_uniqueid(chan), "NONE", "ABANDON",
9233 "%d|%d|%ld", qe.pos, qe.opos,
9234 (long) (time(NULL) - qe.start));
9235 res = -1;
9236 } else if (reason == QUEUE_LEAVEEMPTY) {
9237 /* Return back to dialplan, don't hang up */
9238 res = 0;
9239 } else if (qcontinue) {
9240 reason = QUEUE_CONTINUE;
9241 res = 0;
9242 }
9243 } else if (qe.valid_digits) {
9244 ast_queue_log(args.queuename, ast_channel_uniqueid(chan), "NONE", "EXITWITHKEY",
9245 "%s|%d|%d|%ld", qe.digits, qe.pos, qe.opos, (long) (time(NULL) - qe.start));
9246 }
9247 }
9248
9249 /* Free the optional withdraw info if present */
9250 /* This is done here to catch all cases. e.g. if the call eventually wasn't withdrawn, e.g. answered */
9251 if (qe.withdraw_info) {
9252 ast_free(qe.withdraw_info);
9253 qe.withdraw_info = NULL;
9254 }
9255
9256 /* Don't allow return code > 0 */
9257 if (res >= 0) {
9258 res = 0;
9259 if (ringing) {
9260 ast_indicate(chan, -1);
9261 } else {
9262 ast_moh_stop(chan);
9263 }
9264 ast_stopstream(chan);
9265 }
9266
9267 set_queue_variables(qe.parent, qe.chan);
9268
9269 leave_queue(&qe);
9270 if (reason != QUEUE_UNKNOWN)
9271 set_queue_result(chan, reason);
9272
9273 /*
9274 * every queue_ent is given a reference to it's parent
9275 * call_queue when it joins the queue. This ref must be taken
9276 * away right before the queue_ent is destroyed. In this case
9277 * the queue_ent is about to be returned on the stack
9278 */
9279 qe.parent = queue_unref(qe.parent);
9280
9281 return res;
9282 }
9283
9284 /*!
9285 * \brief create interface var with all queue details.
9286 * \retval 0 on success
9287 * \retval -1 on error
9288 */
9289 static int queue_function_var(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
9290 {
9291 int res = -1;
9292 struct call_queue *q;
9293 char interfacevar[256] = "";
9294 float sl = 0;
9295
9296 if (ast_strlen_zero(data)) {
9297 ast_log(LOG_ERROR, "%s requires an argument: queuename\n", cmd);
9298 return -1;
9299 }
9300
9301 if ((q = find_load_queue_rt_friendly(data))) {
9302 ao2_lock(q);
9303 if (q->setqueuevar) {
9304 sl = 0;
9305 res = 0;
9306
9307 if (q->callscompleted > 0) {
9308 sl = 100 * ((float) q->callscompletedinsl / (float) q->callscompleted);
9309 }
9310
9311 snprintf(interfacevar, sizeof(interfacevar),
9312 "QUEUEMAX=%d,QUEUESTRATEGY=%s,QUEUECALLS=%d,QUEUEHOLDTIME=%d,QUEUETALKTIME=%d,QUEUECOMPLETED=%d,QUEUEABANDONED=%d,QUEUESRVLEVEL=%d,QUEUESRVLEVELPERF=%2.1f",
9313 q->maxlen, int2strat(q->strategy), q->count, q->holdtime, q->talktime, q->callscompleted, q->callsabandoned, q->servicelevel, sl);
9314
9315 pbx_builtin_setvar_multiple(chan, interfacevar);
9316 }
9317
9318 ao2_unlock(q);
9319 queue_t_unref(q, "Done with QUEUE() function");
9320 } else {
9321 ast_log(LOG_WARNING, "queue %s was not found\n", data);
9322 }
9323
9324 snprintf(buf, len, "%d", res);
9325
9326 return 0;
9327 }
9328
9329 /*!
9330 * \brief Check if a given queue exists
9331 *
9332 */
9333 static int queue_function_exists(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
9334 {
9335 struct call_queue *q;
9336
9337 buf[0] = '\0';
9338
9339 if (ast_strlen_zero(data)) {
9340 ast_log(LOG_ERROR, "%s requires an argument: queuename\n", cmd);
9341 return -1;
9342 }
9343 q = find_load_queue_rt_friendly(data);
9344 snprintf(buf, len, "%d", q != NULL? 1 : 0);
9345 if (q) {
9346 queue_t_unref(q, "Done with temporary reference in QUEUE_EXISTS()");
9347 }
9348
9349 return 0;
9350 }
9351
9352 static struct member *get_interface_helper(struct call_queue *q, const char *interface)
9353 {
9354 struct member *m;
9355
9356 if (ast_strlen_zero(interface)) {
9357 ast_log(LOG_ERROR, "QUEUE_MEMBER: Missing required interface argument.\n");
9358 return NULL;
9359 }
9360
9361 m = interface_exists(q, interface);
9362 if (!m) {
9363 ast_log(LOG_ERROR, "Queue member interface '%s' not in queue '%s'.\n",
9364 interface, q->name);
9365 }
9366 return m;
9367 }
9368
9369 /*!
9370 * \brief Get number either busy / free / ready or total members of a specific queue
9371 * \brief Get or set member properties penalty / paused / ringinuse
9372 * \retval number of members (busy / free / ready / total) or member info (penalty / paused / ringinuse)
9373 * \retval -1 on error
9374 */
9375 static int queue_function_mem_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
9376 {
9377 int count = 0;
9378 struct member *m;
9379 struct ao2_iterator mem_iter;
9380 struct call_queue *q;
9381
9382 AST_DECLARE_APP_ARGS(args,
9383 AST_APP_ARG(queuename);
9384 AST_APP_ARG(option);
9385 AST_APP_ARG(interface);
9386 );
9387 /* Make sure the returned value on error is zero length string. */
9388 buf[0] = '\0';
9389
9390 if (ast_strlen_zero(data)) {
9391 ast_log(LOG_ERROR,
9392 "Missing required argument. %s(<queuename>,<option>[,<interface>])\n",
9393 cmd);
9394 return -1;
9395 }
9396
9397 AST_STANDARD_APP_ARGS(args, data);
9398
9399 if (ast_strlen_zero(args.queuename) || ast_strlen_zero(args.option)) {
9400 ast_log(LOG_ERROR,
9401 "Missing required argument. %s(<queuename>,<option>[,<interface>])\n",
9402 cmd);
9403 return -1;
9404 }
9405
9406 if ((q = find_load_queue_rt_friendly(args.queuename))) {
9407 ao2_lock(q);
9408 if (!strcasecmp(args.option, "logged")) {
9409 mem_iter = ao2_iterator_init(q->members, 0);
9410 while ((m = ao2_iterator_next(&mem_iter))) {
9411 /* Count the agents who are logged in and presently answering calls */
9412 if ((m->status != AST_DEVICE_UNAVAILABLE) && (m->status != AST_DEVICE_INVALID)) {
9413 count++;
9414 }
9415 ao2_ref(m, -1);
9416 }
9417 ao2_iterator_destroy(&mem_iter);
9418 } else if (!strcasecmp(args.option, "free")) {
9419 mem_iter = ao2_iterator_init(q->members, 0);
9420 while ((m = ao2_iterator_next(&mem_iter))) {
9421 /* Count the agents who are logged in and presently answering calls */
9422 if ((m->status == AST_DEVICE_NOT_INUSE) && (!m->paused)) {
9423 count++;
9424 }
9425 ao2_ref(m, -1);
9426 }
9427 ao2_iterator_destroy(&mem_iter);
9428 } else if (!strcasecmp(args.option, "ready")) {
9429 time_t now;
9430 time(&now);
9431 mem_iter = ao2_iterator_init(q->members, 0);
9432 while ((m = ao2_iterator_next(&mem_iter))) {
9433 /* Count the agents who are logged in, not paused and not wrapping up */
9434 if ((m->status == AST_DEVICE_NOT_INUSE) && (!m->paused) &&
9435 !(m->lastcall && get_wrapuptime(q, m) && ((now - get_wrapuptime(q, m)) < m->lastcall))) {
9436 count++;
9437 }
9438 ao2_ref(m, -1);
9439 }
9440 ao2_iterator_destroy(&mem_iter);
9441 } else if (!strcasecmp(args.option, "count")) {
9442 count = ao2_container_count(q->members);
9443 } else if (!strcasecmp(args.option, "penalty")) {
9444 m = get_interface_helper(q, args.interface);
9445 if (m) {
9446 count = m->penalty;
9447 ao2_ref(m, -1);
9448 }
9449 } else if (!strcasecmp(args.option, "paused")) {
9450 m = get_interface_helper(q, args.interface);
9451 if (m) {
9452 count = m->paused;
9453 ao2_ref(m, -1);
9454 }
9455 } else if ((!strcasecmp(args.option, "ignorebusy") /* ignorebusy is legacy */
9456 || !strcasecmp(args.option, "ringinuse"))) {
9457 m = get_interface_helper(q, args.interface);
9458 if (m) {
9459 count = m->ringinuse;
9460 ao2_ref(m, -1);
9461 }
9462 } else {
9463 ast_log(LOG_ERROR, "%s: Invalid option '%s' provided.\n", cmd, args.option);
9464 }
9465 ao2_unlock(q);
9466 queue_t_unref(q, "Done with temporary reference in QUEUE_MEMBER()");
9467 } else {
9468 ast_log(LOG_WARNING, "queue %s was not found\n", args.queuename);
9469 }
9470
9471 snprintf(buf, len, "%d", count);
9472
9473 return 0;
9474 }
9475
9476 /*! \brief Dialplan function QUEUE_MEMBER() Sets the members penalty / paused / ringinuse. */
9477 static int queue_function_mem_write(struct ast_channel *chan, const char *cmd, char *data, const char *value)
9478 {
9479 int memvalue;
9480
9481 AST_DECLARE_APP_ARGS(args,
9482 AST_APP_ARG(queuename);
9483 AST_APP_ARG(option);
9484 AST_APP_ARG(interface);
9485 );
9486
9487 if (ast_strlen_zero(data)) {
9488 ast_log(LOG_ERROR,
9489 "Missing required argument. %s([<queuename>],<option>,<interface>)\n",
9490 cmd);
9491 return -1;
9492 }
9493
9494 AST_STANDARD_APP_ARGS(args, data);
9495
9496 if (ast_strlen_zero(args.option)
9497 || ast_strlen_zero(args.interface)) {
9498 ast_log(LOG_ERROR,
9499 "Missing required argument. %s([<queuename>],<option>,<interface>)\n",
9500 cmd);
9501 return -1;
9502 }
9503
9504 /*
9505 * If queuename is empty then the option will be
9506 * set for the interface in all queues.
9507 */
9508
9509 memvalue = atoi(value);
9510 if (!strcasecmp(args.option, "penalty")) {
9511 if (set_member_value(args.queuename, args.interface, MEMBER_PENALTY, memvalue)) {
9512 ast_log(LOG_ERROR, "Invalid interface, queue, or penalty\n");
9513 return -1;
9514 }
9515 } else if (!strcasecmp(args.option, "paused")) {
9516 memvalue = (memvalue <= 0) ? 0 : 1;
9517 if (set_member_paused(args.queuename, args.interface, NULL, memvalue)) {
9518 ast_log(LOG_ERROR, "Invalid interface or queue\n");
9519 return -1;
9520 }
9521 } else if (!strcasecmp(args.option, "ignorebusy") /* ignorebusy is legacy */
9522 || !strcasecmp(args.option, "ringinuse")) {
9523 memvalue = (memvalue <= 0) ? 0 : 1;
9524 if (set_member_value(args.queuename, args.interface, MEMBER_RINGINUSE, memvalue)) {
9525 ast_log(LOG_ERROR, "Invalid interface or queue\n");
9526 return -1;
9527 }
9528 } else {
9529 ast_log(LOG_ERROR, "%s: Invalid option '%s' provided.\n", cmd, args.option);
9530 return -1;
9531 }
9532 return 0;
9533 }
9534
9535 /*!
9536 * \brief Get the total number of members in a specific queue (Deprecated)
9537 * \retval number of members
9538 * \retval -1 on error
9539 */
9540 static int queue_function_qac_dep(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
9541 {
9542 int count = 0;
9543 struct member *m;
9544 struct call_queue *q;
9545 struct ao2_iterator mem_iter;
9546 static int depflag = 1;
9547
9548 if (depflag) {
9549 depflag = 0;
9550 ast_log(LOG_NOTICE, "The function QUEUE_MEMBER_COUNT has been deprecated in favor of the QUEUE_MEMBER function and will not be in further releases.\n");
9551 }
9552
9553 if (ast_strlen_zero(data)) {
9554 ast_log(LOG_ERROR, "%s requires an argument: queuename\n", cmd);
9555 return -1;
9556 }
9557
9558 if ((q = find_load_queue_rt_friendly(data))) {
9559 ao2_lock(q);
9560 mem_iter = ao2_iterator_init(q->members, 0);
9561 while ((m = ao2_iterator_next(&mem_iter))) {
9562 /* Count the agents who are logged in and presently answering calls */
9563 if ((m->status != AST_DEVICE_UNAVAILABLE) && (m->status != AST_DEVICE_INVALID)) {
9564 count++;
9565 }
9566 ao2_ref(m, -1);
9567 }
9568 ao2_iterator_destroy(&mem_iter);
9569 ao2_unlock(q);
9570 queue_t_unref(q, "Done with temporary reference in QUEUE_MEMBER_COUNT");
9571 } else {
9572 ast_log(LOG_WARNING, "queue %s was not found\n", data);
9573 }
9574
9575 snprintf(buf, len, "%d", count);
9576
9577 return 0;
9578 }
9579
9580 /*! \brief Dialplan function QUEUE_GET_CHANNEL() Get caller channel waiting at specified position in the queue */
9581 static int queue_function_queuegetchannel(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
9582 {
9583 int position;
9584 char *parse;
9585 struct call_queue *q;
9586 struct ast_variable *var;
9587
9588 AST_DECLARE_APP_ARGS(args,
9589 AST_APP_ARG(queuename);
9590 AST_APP_ARG(position);
9591 );
9592
9593 buf[0] = '\0';
9594
9595 if (ast_strlen_zero(data)) {
9596 ast_log(LOG_ERROR, "Missing argument. QUEUE_GET_CHANNEL(<queuename>,<position>)\n");
9597 return -1;
9598 }
9599
9600 parse = ast_strdupa(data);
9601 AST_STANDARD_APP_ARGS(args, parse);
9602
9603 if (ast_strlen_zero(args.queuename)) {
9604 ast_log (LOG_ERROR, "The <queuename> parameter is required.\n");
9605 return -1;
9606 }
9607
9608 if (ast_strlen_zero(args.position)) {
9609 position = 1;
9610 } else {
9611 if (sscanf(args.position, "%30d", &position) != 1) {
9612 ast_log (LOG_ERROR, "<position> parameter must be an integer.\n");
9613 return -1;
9614 }
9615 if (position < 1) {
9616 ast_log (LOG_ERROR, "<position> parameter must be an integer greater than zero.\n");
9617 return -1;
9618 }
9619 }
9620
9621 {
9622 struct call_queue tmpq = {
9623 .name = args.queuename,
9624 };
9625
9626 q = ao2_t_find(queues, &tmpq, OBJ_POINTER, "Find for QUEUE_GET_CHANNEL()");
9627 }
9628 if (q) {
9629 ao2_lock(q);
9630 if (q->count >= position) {
9631 struct queue_ent *qe;
9632
9633 for (qe = q->head; qe; qe = qe->next) {
9634 if (qe->pos == position) {
9635 ast_copy_string(buf, ast_channel_name(qe->chan), len);
9636 break;
9637 }
9638 }
9639 }
9640 ao2_unlock(q);
9641 queue_t_unref(q, "Done with reference in QUEUE_GET_CHANNEL()");
9642 return 0;
9643 }
9644
9645 var = ast_load_realtime("queues", "name", args.queuename, SENTINEL);
9646 if (var) {
9647 /* if the queue is realtime but was not found in memory, this
9648 * means that the queue had been deleted from memory since it was
9649 * "dead."
9650 */
9651 ast_variables_destroy(var);
9652 return 0;
9653 }
9654
9655 ast_log(LOG_WARNING, "queue %s was not found\n", args.queuename);
9656 return 0;
9657 }
9658
9659 /*! \brief Dialplan function QUEUE_WAITING_COUNT() Get number callers waiting in a specific queue */
9660 static int queue_function_queuewaitingcount(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
9661 {
9662 int count = 0;
9663 struct call_queue *q, tmpq = {
9664 .name = data,
9665 };
9666 struct ast_variable *var = NULL;
9667
9668 buf[0] = '\0';
9669
9670 if (ast_strlen_zero(data)) {
9671 ast_log(LOG_ERROR, "QUEUE_WAITING_COUNT requires an argument: queuename\n");
9672 return -1;
9673 }
9674
9675 if ((q = ao2_t_find(queues, &tmpq, OBJ_POINTER, "Find for QUEUE_WAITING_COUNT()"))) {
9676 ao2_lock(q);
9677 count = q->count;
9678 ao2_unlock(q);
9679 queue_t_unref(q, "Done with reference in QUEUE_WAITING_COUNT()");
9680 } else if ((var = ast_load_realtime("queues", "name", data, SENTINEL))) {
9681 /* if the queue is realtime but was not found in memory, this
9682 * means that the queue had been deleted from memory since it was
9683 * "dead." This means it has a 0 waiting count
9684 */
9685 count = 0;
9686 ast_variables_destroy(var);
9687 } else {
9688 ast_log(LOG_WARNING, "queue %s was not found\n", data);
9689 }
9690
9691 snprintf(buf, len, "%d", count);
9692
9693 return 0;
9694 }
9695
9696 /*! \brief Dialplan function QUEUE_MEMBER_LIST() Get list of members in a specific queue */
9697 static int queue_function_queuememberlist(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
9698 {
9699 struct call_queue *q;
9700 struct member *m;
9701
9702 /* Ensure an otherwise empty list doesn't return garbage */
9703 buf[0] = '\0';
9704
9705 if (ast_strlen_zero(data)) {
9706 ast_log(LOG_ERROR, "QUEUE_MEMBER_LIST requires an argument: queuename\n");
9707 return -1;
9708 }
9709
9710 if ((q = find_load_queue_rt_friendly(data))) {
9711 int buflen = 0, count = 0;
9712 struct ao2_iterator mem_iter;
9713
9714 ao2_lock(q);
9715 mem_iter = ao2_iterator_init(q->members, 0);
9716 while ((m = ao2_iterator_next(&mem_iter))) {
9717 /* strcat() is always faster than printf() */
9718 if (count++) {
9719 strncat(buf + buflen, ",", len - buflen - 1);
9720 buflen++;
9721 }
9722 strncat(buf + buflen, m->interface, len - buflen - 1);
9723 buflen += strlen(m->interface);
9724 /* Safeguard against overflow (negative length) */
9725 if (buflen >= len - 2) {
9726 ao2_ref(m, -1);
9727 ast_log(LOG_WARNING, "Truncating list\n");
9728 break;
9729 }
9730 ao2_ref(m, -1);
9731 }
9732 ao2_iterator_destroy(&mem_iter);
9733 ao2_unlock(q);
9734 queue_t_unref(q, "Done with QUEUE_MEMBER_LIST()");
9735 } else
9736 ast_log(LOG_WARNING, "queue %s was not found\n", data);
9737
9738 /* We should already be terminated, but let's make sure. */
9739 buf[len - 1] = '\0';
9740
9741 return 0;
9742 }
9743
9744 /*! \brief Dialplan function QUEUE_MEMBER_PENALTY() Gets the members penalty. */
9745 static int queue_function_memberpenalty_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
9746 {
9747 int penalty;
9748 AST_DECLARE_APP_ARGS(args,
9749 AST_APP_ARG(queuename);
9750 AST_APP_ARG(interface);
9751 );
9752 /* Make sure the returned value on error is NULL. */
9753 buf[0] = '\0';
9754
9755 if (ast_strlen_zero(data)) {
9756 ast_log(LOG_ERROR, "Missing argument. QUEUE_MEMBER_PENALTY(<queuename>,<interface>)\n");
9757 return -1;
9758 }
9759
9760 AST_STANDARD_APP_ARGS(args, data);
9761
9762 if (args.argc < 2) {
9763 ast_log(LOG_ERROR, "Missing argument. QUEUE_MEMBER_PENALTY(<queuename>,<interface>)\n");
9764 return -1;
9765 }
9766
9767 penalty = get_member_penalty (args.queuename, args.interface);
9768
9769 if (penalty >= 0) { /* remember that buf is already '\0' */
9770 snprintf (buf, len, "%d", penalty);
9771 }
9772
9773 return 0;
9774 }
9775
9776 /*! \brief Dialplan function QUEUE_MEMBER_PENALTY() Sets the members penalty. */
9777 static int queue_function_memberpenalty_write(struct ast_channel *chan, const char *cmd, char *data, const char *value)
9778 {
9779 int penalty;
9780 AST_DECLARE_APP_ARGS(args,
9781 AST_APP_ARG(queuename);
9782 AST_APP_ARG(interface);
9783 );
9784
9785 if (ast_strlen_zero(data)) {
9786 ast_log(LOG_ERROR, "Missing argument. QUEUE_MEMBER_PENALTY(<queuename>,<interface>)\n");
9787 return -1;
9788 }
9789
9790 AST_STANDARD_APP_ARGS(args, data);
9791
9792 if (args.argc < 2) {
9793 ast_log(LOG_ERROR, "Missing argument. QUEUE_MEMBER_PENALTY(<queuename>,<interface>)\n");
9794 return -1;
9795 }
9796
9797 penalty = atoi(value);
9798
9799 if (ast_strlen_zero(args.interface)) {
9800 ast_log (LOG_ERROR, "<interface> parameter can't be null\n");
9801 return -1;
9802 }
9803
9804 /* if queuename = NULL then penalty will be set for interface in all the queues. */
9805 if (set_member_value(args.queuename, args.interface, MEMBER_PENALTY, penalty)) {
9806 ast_log(LOG_ERROR, "Invalid interface, queue or penalty\n");
9807 return -1;
9808 }
9809
9810 return 0;
9811 }
9812
9813 static struct ast_custom_function queueexists_function = {
9814 .name = "QUEUE_EXISTS",
9815 .read = queue_function_exists,
9816 };
9817
9818 static struct ast_custom_function queuevar_function = {
9819 .name = "QUEUE_VARIABLES",
9820 .read = queue_function_var,
9821 };
9822
9823 static struct ast_custom_function queuemembercount_function = {
9824 .name = "QUEUE_MEMBER",
9825 .read = queue_function_mem_read,
9826 .write = queue_function_mem_write,
9827 };
9828
9829 static struct ast_custom_function queuemembercount_dep = {
9830 .name = "QUEUE_MEMBER_COUNT",
9831 .read = queue_function_qac_dep,
9832 };
9833
9834 static struct ast_custom_function queuegetchannel_function = {
9835 .name = "QUEUE_GET_CHANNEL",
9836 .read = queue_function_queuegetchannel,
9837 };
9838
9839 static struct ast_custom_function queuewaitingcount_function = {
9840 .name = "QUEUE_WAITING_COUNT",
9841 .read = queue_function_queuewaitingcount,
9842 };
9843
9844 static struct ast_custom_function queuememberlist_function = {
9845 .name = "QUEUE_MEMBER_LIST",
9846 .read = queue_function_queuememberlist,
9847 };
9848
9849 static struct ast_custom_function queuememberpenalty_function = {
9850 .name = "QUEUE_MEMBER_PENALTY",
9851 .read = queue_function_memberpenalty_read,
9852 .write = queue_function_memberpenalty_write,
9853 };
9854
9855 /*! Reset the global queue rules parameters even if there is no "general" section of queuerules.conf */
9856 static void queue_rules_reset_global_params(void)
9857 {
9858 realtime_rules = 0;
9859 }
9860
9861 /*! Set the global queue rules parameters as defined in the "general" section of queuerules.conf */
9862 static void queue_rules_set_global_params(struct ast_config *cfg)
9863 {
9864 const char *general_val = NULL;
9865 if ((general_val = ast_variable_retrieve(cfg, "general", "realtime_rules"))) {
9866 realtime_rules = ast_true(general_val);
9867 }
9868 }
9869
9870 /*! \brief Reload the rules defined in queuerules.conf
9871 *
9872 * \param reload If 1, then only process queuerules.conf if the file
9873 * has changed since the last time we inspected it.
9874 * \return Always returns AST_MODULE_LOAD_SUCCESS
9875 */
9876 static int reload_queue_rules(int reload)
9877 {
9878 struct ast_config *cfg;
9879 struct rule_list *rl_iter, *new_rl;
9880 struct penalty_rule *pr_iter;
9881 char *rulecat = NULL;
9882 struct ast_variable *rulevar = NULL;
9883 struct ast_flags config_flags = { (reload && !realtime_rules) ? CONFIG_FLAG_FILEUNCHANGED : 0 };
9884
9885 if (!(cfg = ast_config_load("queuerules.conf", config_flags))) {
9886 ast_log(LOG_NOTICE, "No queuerules.conf file found, queues will not follow penalty rules\n");
9887 return AST_MODULE_LOAD_SUCCESS;
9888 } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
9889 ast_log(LOG_NOTICE, "queuerules.conf has not changed since it was last loaded. Not taking any action.\n");
9890 return AST_MODULE_LOAD_SUCCESS;
9891 } else if (cfg == CONFIG_STATUS_FILEINVALID) {
9892 ast_log(LOG_ERROR, "Config file queuerules.conf is in an invalid format. Aborting.\n");
9893 return AST_MODULE_LOAD_SUCCESS;
9894 }
9895
9896 AST_LIST_LOCK(&rule_lists);
9897 while ((rl_iter = AST_LIST_REMOVE_HEAD(&rule_lists, list))) {
9898 while ((pr_iter = AST_LIST_REMOVE_HEAD(&rl_iter->rules, list)))
9899 ast_free(pr_iter);
9900 ast_free(rl_iter);
9901 }
9902 queue_rules_reset_global_params();
9903 while ((rulecat = ast_category_browse(cfg, rulecat))) {
9904 if (!strcasecmp(rulecat, "general")) {
9905 queue_rules_set_global_params(cfg);
9906 continue;
9907 }
9908 if (!(new_rl = ast_calloc(1, sizeof(*new_rl)))) {
9909 AST_LIST_UNLOCK(&rule_lists);
9910 ast_config_destroy(cfg);
9911 return AST_MODULE_LOAD_DECLINE;
9912 } else {
9913 ast_copy_string(new_rl->name, rulecat, sizeof(new_rl->name));
9914 AST_LIST_INSERT_TAIL(&rule_lists, new_rl, list);
9915 for (rulevar = ast_variable_browse(cfg, rulecat); rulevar; rulevar = rulevar->next)
9916 if(!strcasecmp(rulevar->name, "penaltychange"))
9917 insert_penaltychange(new_rl->name, rulevar->value, rulevar->lineno);
9918 else
9919 ast_log(LOG_WARNING, "Don't know how to handle rule type '%s' on line %d\n", rulevar->name, rulevar->lineno);
9920 }
9921 }
9922
9923 ast_config_destroy(cfg);
9924
9925 if (realtime_rules && load_realtime_rules()) {
9926 AST_LIST_UNLOCK(&rule_lists);
9927 return AST_MODULE_LOAD_DECLINE;
9928 }
9929
9930 AST_LIST_UNLOCK(&rule_lists);
9931 return AST_MODULE_LOAD_SUCCESS;
9932 }
9933
9934 /*! Always set the global queue defaults, even if there is no "general" section in queues.conf */
9935 static void queue_reset_global_params(void)
9936 {
9937 queue_persistent_members = 0;
9938 autofill_default = 0;
9939 montype_default = 0;
9940 shared_lastcall = 0;
9941 negative_penalty_invalid = 0;
9942 log_membername_as_agent = 0;
9943 force_longest_waiting_caller = 0;
9944 log_unpause_on_reason_change = 0;
9945 }
9946
9947 /*! Set the global queue parameters as defined in the "general" section of queues.conf */
9948 static void queue_set_global_params(struct ast_config *cfg)
9949 {
9950 const char *general_val = NULL;
9951 if ((general_val = ast_variable_retrieve(cfg, "general", "persistentmembers"))) {
9952 queue_persistent_members = ast_true(general_val);
9953 }
9954 if ((general_val = ast_variable_retrieve(cfg, "general", "autofill"))) {
9955 autofill_default = ast_true(general_val);
9956 }
9957 if ((general_val = ast_variable_retrieve(cfg, "general", "monitor-type"))) {
9958 if (!strcasecmp(general_val, "mixmonitor"))
9959 montype_default = 1;
9960 }
9961 if ((general_val = ast_variable_retrieve(cfg, "general", "shared_lastcall"))) {
9962 shared_lastcall = ast_true(general_val);
9963 }
9964 if ((general_val = ast_variable_retrieve(cfg, "general", "negative_penalty_invalid"))) {
9965 negative_penalty_invalid = ast_true(general_val);
9966 }
9967 if ((general_val = ast_variable_retrieve(cfg, "general", "log_membername_as_agent"))) {
9968 log_membername_as_agent = ast_true(general_val);
9969 }
9970 if ((general_val = ast_variable_retrieve(cfg, "general", "force_longest_waiting_caller"))) {
9971 if (!strcasecmp(general_val, "prio")) {
9972 force_longest_waiting_caller = FORCELONGESTWAITINGCALLER_PRIO;
9973 } else if (ast_true(general_val)) {
9974 force_longest_waiting_caller = FORCELONGESTWAITINGCALLER_YES;
9975 } else {
9976 force_longest_waiting_caller = FORCELONGESTWAITINGCALLER_NO;
9977 }
9978 }
9979 if ((general_val = ast_variable_retrieve(cfg, "general", "log_unpause_on_reason_change"))) {
9980 log_unpause_on_reason_change = ast_true(general_val);
9981 }
9982 /* Apply log-caller-id-name in the same place as other global settings */
9983 if ((general_val = ast_variable_retrieve(cfg, "general", "log-caller-id-name"))) {
9984 log_caller_id_name = ast_true(general_val);
9985 }
9986 }
9987
9988 /*! \brief reload information pertaining to a single member
9989 *
9990 * This function is called when a member = line is encountered in
9991 * queues.conf.
9992 *
9993 * \param memberdata The part after member = in the config file
9994 * \param q The queue to which this member belongs
9995 */
9996 static void reload_single_member(const char *memberdata, struct call_queue *q)
9997 {
9998 char *membername, *interface, *state_interface, *tmp;
9999 char *parse;
10000 struct member *cur, *newm;
10001 struct member tmpmem;
10002 int penalty;
10003 int ringinuse;
10004 int wrapuptime;
10005 int paused;
10006 AST_DECLARE_APP_ARGS(args,
10007 AST_APP_ARG(interface);
10008 AST_APP_ARG(penalty);
10009 AST_APP_ARG(membername);
10010 AST_APP_ARG(state_interface);
10011 AST_APP_ARG(ringinuse);
10012 AST_APP_ARG(wrapuptime);
10013 AST_APP_ARG(paused);
10014 );
10015
10016 if (ast_strlen_zero(memberdata)) {
10017 ast_log(LOG_WARNING, "Empty queue member definition. Moving on!\n");
10018 return;
10019 }
10020
10021 /* Add a new member */
10022 parse = ast_strdupa(memberdata);
10023
10024 AST_STANDARD_APP_ARGS(args, parse);
10025
10026 interface = args.interface;
10027 if (!ast_strlen_zero(args.penalty)) {
10028 tmp = args.penalty;
10029 ast_strip(tmp);
10030 penalty = atoi(tmp);
10031 if (penalty < 0) {
10032 penalty = 0;
10033 }
10034 } else {
10035 penalty = 0;
10036 }
10037
10038 if (!ast_strlen_zero(args.membername)) {
10039 membername = args.membername;
10040 ast_strip(membername);
10041 } else {
10042 membername = interface;
10043 }
10044
10045 if (!ast_strlen_zero(args.state_interface)) {
10046 state_interface = args.state_interface;
10047 ast_strip(state_interface);
10048 } else {
10049 state_interface = interface;
10050 }
10051
10052 if (!ast_strlen_zero(args.ringinuse)) {
10053 tmp = args.ringinuse;
10054 ast_strip(tmp);
10055 if (ast_true(tmp)) {
10056 ringinuse = 1;
10057 } else if (ast_false(tmp)) {
10058 ringinuse = 0;
10059 } else {
10060 ast_log(LOG_ERROR, "Member %s has an invalid ringinuse value. Using %s ringinuse value.\n",
10061 membername, q->name);
10062 ringinuse = q->ringinuse;
10063 }
10064 } else {
10065 ringinuse = q->ringinuse;
10066 }
10067
10068 if (!ast_strlen_zero(args.wrapuptime)) {
10069 tmp = args.wrapuptime;
10070 ast_strip(tmp);
10071 wrapuptime = atoi(tmp);
10072 if (wrapuptime < 0) {
10073 wrapuptime = 0;
10074 }
10075 } else {
10076 wrapuptime = 0;
10077 }
10078
10079 if (!ast_strlen_zero(args.paused)) {
10080 tmp = args.paused;
10081 ast_strip(tmp);
10082 if (ast_true(tmp)) {
10083 paused = 1;
10084 } else if (ast_false(tmp)) {
10085 paused = 0;
10086 } else {
10087 ast_log(LOG_ERROR, "Member %s has an invalid paused value.\n", membername);
10088 paused = 0;
10089 }
10090 } else {
10091 paused = 0;
10092 }
10093
10094 /* Find the old position in the list */
10095 ast_copy_string(tmpmem.interface, interface, sizeof(tmpmem.interface));
10096 cur = ao2_find(q->members, &tmpmem, OBJ_POINTER);
10097
10098 if (cur) {
10099 paused = cur->paused;
10100 }
10101
10102 if ((newm = create_queue_member(interface, membername, penalty, paused, state_interface, ringinuse, wrapuptime))) {
10103 newm->wrapuptime = wrapuptime;
10104 if (cur) {
10105 ao2_lock(q->members);
10106 /* Round Robin Queue Position must be copied if this is replacing an existing member */
10107 newm->queuepos = cur->queuepos;
10108 /* Don't reset agent stats either */
10109 newm->calls = cur->calls;
10110 newm->lastcall = cur->lastcall;
10111
10112 ao2_link(q->members, newm);
10113 ao2_unlink(q->members, cur);
10114 ao2_unlock(q->members);
10115 } else {
10116 /* Otherwise we need to add using the function that will apply a round robin queue position manually. */
10117 member_add_to_queue(q, newm);
10118 }
10119 ao2_ref(newm, -1);
10120 }
10121 newm = NULL;
10122
10123 if (cur) {
10124 ao2_ref(cur, -1);
10125 }
10126 }
10127
10128 static int mark_member_dead(void *obj, void *arg, int flags)
10129 {
10130 struct member *member = obj;
10131 if (!member->dynamic && !member->realtime) {
10132 member->delme = 1;
10133 }
10134 return 0;
10135 }
10136
10137 static int kill_dead_members(void *obj, void *arg, int flags)
10138 {
10139 struct member *member = obj;
10140
10141 if (!member->delme) {
10142 member->status = get_queue_member_status(member);
10143 return 0;
10144 } else {
10145 return CMP_MATCH;
10146 }
10147 }
10148
10149 /*! \brief Reload information pertaining to a particular queue
10150 *
10151 * Once we have isolated a queue within reload_queues, we call this. This will either
10152 * reload information for the queue or if we're just reloading member information, we'll just
10153 * reload that without touching other settings within the queue
10154 *
10155 * \param cfg The configuration which we are reading
10156 * \param mask Tells us what information we need to reload
10157 * \param queuename The name of the queue we are reloading information from
10158 */
10159 static void reload_single_queue(struct ast_config *cfg, struct ast_flags *mask, const char *queuename)
10160 {
10161 int new;
10162 struct call_queue *q = NULL;
10163 struct member *member;
10164 /*We're defining a queue*/
10165 struct call_queue tmpq = {
10166 .name = queuename,
10167 };
10168 const char *tmpvar;
10169 const int queue_reload = ast_test_flag(mask, QUEUE_RELOAD_PARAMETERS);
10170 const int member_reload = ast_test_flag(mask, QUEUE_RELOAD_MEMBER);
10171 int prev_weight = 0;
10172 struct ast_variable *var;
10173 struct ao2_iterator mem_iter;
10174
10175 if (!(q = ao2_t_find(queues, &tmpq, OBJ_POINTER, "Find queue for reload"))) {
10176 if (queue_reload) {
10177 /* Make one then */
10178 if (!(q = alloc_queue(queuename))) {
10179 return;
10180 }
10181 } else {
10182 /* Since we're not reloading queues, this means that we found a queue
10183 * in the configuration file which we don't know about yet. Just return.
10184 */
10185 return;
10186 }
10187 new = 1;
10188 } else {
10189 new = 0;
10190 }
10191
10192 if (!new) {
10193 ao2_lock(q);
10194 prev_weight = q->weight ? 1 : 0;
10195 }
10196 /* Check if we already found a queue with this name in the config file */
10197 if (q->found) {
10198 ast_log(LOG_WARNING, "Queue '%s' already defined! Skipping!\n", queuename);
10199 if (!new) {
10200 /* It should be impossible to *not* hit this case*/
10201 ao2_unlock(q);
10202 }
10203 queue_t_unref(q, "We exist! Expiring temporary pointer");
10204 return;
10205 }
10206 /* Due to the fact that the "linear" strategy will have a different allocation
10207 * scheme for queue members, we must devise the queue's strategy before other initializations.
10208 * To be specific, the linear strategy needs to function like a linked list, meaning the ao2
10209 * container used will have only a single bucket instead of the typical number.
10210 */
10211 if (queue_reload) {
10212 if ((tmpvar = ast_variable_retrieve(cfg, queuename, "strategy"))) {
10213 q->strategy = strat2int(tmpvar);
10214 if (q->strategy < 0) {
10215 ast_log(LOG_WARNING, "'%s' isn't a valid strategy for queue '%s', using ringall instead\n",
10216 tmpvar, q->name);
10217 q->strategy = QUEUE_STRATEGY_RINGALL;
10218 }
10219 } else {
10220 q->strategy = QUEUE_STRATEGY_RINGALL;
10221 }
10222 init_queue(q);
10223 }
10224 if (member_reload) {
10225 ao2_callback(q->members, OBJ_NODATA, mark_member_dead, NULL);
10226 q->found = 1;
10227 }
10228
10229 /* On the first pass we just read the parameters of the queue */
10230 for (var = ast_variable_browse(cfg, queuename); var; var = var->next) {
10231 if (queue_reload && strcasecmp(var->name, "member")) {
10232 queue_set_param(q, var->name, var->value, var->lineno, 1);
10233 }
10234 }
10235
10236 /* On the second pass, we read members */
10237 for (var = ast_variable_browse(cfg, queuename); var; var = var->next) {
10238 if (member_reload && !strcasecmp(var->name, "member")) {
10239 reload_single_member(var->value, q);
10240 }
10241 }
10242
10243 /* Update ringinuse for dynamic members */
10244 if (member_reload) {
10245 ao2_lock(q->members);
10246 mem_iter = ao2_iterator_init(q->members, AO2_ITERATOR_DONTLOCK);
10247 while ((member = ao2_iterator_next(&mem_iter))) {
10248 if (member->dynamic) {
10249 member->ringinuse = q->ringinuse;
10250 }
10251 ao2_ref(member, -1);
10252 }
10253 ao2_iterator_destroy(&mem_iter);
10254 ao2_unlock(q->members);
10255 }
10256
10257 /* At this point, we've determined if the queue has a weight, so update use_weight
10258 * as appropriate
10259 */
10260 if (!q->weight && prev_weight) {
10261 ast_atomic_fetchadd_int(&use_weight, -1);
10262 } else if (q->weight && !prev_weight) {
10263 ast_atomic_fetchadd_int(&use_weight, +1);
10264 }
10265
10266 /* Free remaining members marked as delme */
10267 if (member_reload) {
10268 ao2_lock(q->members);
10269 ao2_callback(q->members, OBJ_NODATA | OBJ_MULTIPLE, queue_delme_members_decrement_followers, q);
10270 ao2_callback(q->members, OBJ_NODATA | OBJ_MULTIPLE | OBJ_UNLINK, kill_dead_members, q);
10271 ao2_unlock(q->members);
10272 }
10273
10274 if (new) {
10275 queues_t_link(queues, q, "Add queue to container");
10276 } else {
10277 ao2_unlock(q);
10278 }
10279 queue_t_unref(q, "Expiring creation reference");
10280 }
10281
10282 static int mark_unfound(void *obj, void *arg, int flags)
10283 {
10284 struct call_queue *q = obj;
10285 char *queuename = arg;
10286 if (!q->realtime && (ast_strlen_zero(queuename) || !strcasecmp(queuename, q->name))) {
10287 q->found = 0;
10288 }
10289 return 0;
10290 }
10291
10292 static int kill_if_unfound(void *obj, void *arg, int flags)
10293 {
10294 struct call_queue *q = obj;
10295 char *queuename = arg;
10296 if (!q->realtime && !q->found && (ast_strlen_zero(queuename) || !strcasecmp(queuename, q->name))) {
10297 q->dead = 1;
10298 return CMP_MATCH;
10299 } else {
10300 return 0;
10301 }
10302 }
10303
10304 /*! \brief reload the queues.conf file
10305 *
10306 * This function reloads the information in the general section of the queues.conf
10307 * file and potentially more, depending on the value of mask.
10308 *
10309 * \param reload 0 if we are calling this the first time, 1 every other time
10310 * \param mask Gives flags telling us what information to actually reload
10311 * \param queuename If set to a non-zero string, then only reload information from
10312 * that particular queue. Otherwise inspect all queues
10313 * \retval -1 Failure occurred
10314 * \retval 0 All clear!
10315 */
10316 static int reload_queues(int reload, struct ast_flags *mask, const char *queuename)
10317 {
10318 struct ast_config *cfg;
10319 char *cat;
10320 struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
10321 const int queue_reload = ast_test_flag(mask, QUEUE_RELOAD_PARAMETERS);
10322
10323 if (!(cfg = ast_config_load("queues.conf", config_flags))) {
10324 ast_log(LOG_NOTICE, "No call queueing config file (queues.conf), so no call queues\n");
10325 return -1;
10326 } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
10327 return 0;
10328 } else if (cfg == CONFIG_STATUS_FILEINVALID) {
10329 ast_log(LOG_ERROR, "Config file queues.conf is in an invalid format. Aborting.\n");
10330 return -1;
10331 }
10332
10333 /* We've made it here, so it looks like we're doing operations on all queues. */
10334 ao2_lock(queues);
10335
10336 /* Mark non-realtime queues not found at the beginning. */
10337 ao2_callback(queues, OBJ_NODATA, mark_unfound, (char *) queuename);
10338
10339 /* Chug through config file. */
10340 cat = NULL;
10341 queue_reset_global_params();
10342 while ((cat = ast_category_browse(cfg, cat)) ) {
10343 if (!strcasecmp(cat, "general") && queue_reload) {
10344 queue_set_global_params(cfg);
10345 continue;
10346 }
10347 if (ast_strlen_zero(queuename) || !strcasecmp(cat, queuename))
10348 reload_single_queue(cfg, mask, cat);
10349 }
10350
10351 ast_config_destroy(cfg);
10352 if (queue_reload) {
10353 /* Unlink and mark dead all non-realtime queues that were not found in the configuration file. */
10354 ao2_callback(queues, OBJ_NODATA | OBJ_MULTIPLE | OBJ_UNLINK | OBJ_NOLOCK, kill_if_unfound, (char *) queuename);
10355 }
10356 ao2_unlock(queues);
10357 return 0;
10358 }
10359
10360 /*! \brief Facilitates resetting statistics for a queue
10361 *
10362 * This function actually does not reset any statistics, but
10363 * rather finds a call_queue struct which corresponds to the
10364 * passed-in queue name and passes that structure to the
10365 * clear_queue function. If no queuename is passed in, then
10366 * all queues will have their statistics reset.
10367 *
10368 * \param queuename The name of the queue to reset the statistics
10369 * for. If this is NULL or zero-length, then this means to reset
10370 * the statistics for all queues
10371 * \retval 0 always
10372 */
10373 static int clear_stats(const char *queuename)
10374 {
10375 struct call_queue *q;
10376 struct ao2_iterator queue_iter;
10377
10378 queue_iter = ao2_iterator_init(queues, 0);
10379 while ((q = ao2_t_iterator_next(&queue_iter, "Iterate through queues"))) {
10380 ao2_lock(q);
10381 if (ast_strlen_zero(queuename) || !strcasecmp(q->name, queuename))
10382 clear_queue(q);
10383 ao2_unlock(q);
10384 queue_t_unref(q, "Done with iterator");
10385 }
10386 ao2_iterator_destroy(&queue_iter);
10387 return 0;
10388 }
10389
10390 /*! \brief The command center for all reload operations
10391 *
10392 * Whenever any piece of queue information is to be reloaded, this function
10393 * is called. It interprets the flags set in the mask parameter and acts
10394 * based on how they are set.
10395 *
10396 * \param reload True if we are reloading information, false if we are loading
10397 * information for the first time.
10398 * \param mask A bitmask which tells the handler what actions to take
10399 * \param queuename The name of the queue on which we wish to take action
10400 * \retval 0 All reloads were successful
10401 * \retval non-zero There was a failure
10402 */
10403 static int reload_handler(int reload, struct ast_flags *mask, const char *queuename)
10404 {
10405 int res = 0;
10406
10407 if (ast_test_flag(mask, QUEUE_RELOAD_RULES)) {
10408 res |= reload_queue_rules(reload);
10409 }
10410 if (ast_test_flag(mask, QUEUE_RESET_STATS)) {
10411 res |= clear_stats(queuename);
10412 }
10413 if (ast_test_flag(mask, (QUEUE_RELOAD_PARAMETERS | QUEUE_RELOAD_MEMBER))) {
10414 res |= reload_queues(reload, mask, queuename);
10415 }
10416 return res;
10417 }
10418
10419 /*! \brief direct output to manager or cli with proper terminator */
10420 static void do_print(struct mansession *s, int fd, const char *str)
10421 {
10422 if (s) {
10423 astman_append(s, "%s\r\n", str);
10424 } else {
10425 ast_cli(fd, "%s\n", str);
10426 }
10427 }
10428
10429 /*! \brief Print a single queue to AMI or the CLI */
10430 static void print_queue(struct mansession *s, int fd, struct call_queue *q)
10431 {
10432 float sl;
10433 float sl2;
10434 struct ao2_iterator mem_iter;
10435 struct ast_str *out = ast_str_alloca(512);
10436 time_t now = time(NULL);
10437
10438 ast_str_set(&out, 0, "%s has %d calls (max ", q->name, q->count);
10439 if (q->maxlen) {
10440 ast_str_append(&out, 0, "%d", q->maxlen);
10441 } else {
10442 ast_str_append(&out, 0, "unlimited");
10443 }
10444 sl = 0;
10445 sl2 = 0;
10446 if (q->callscompleted > 0) {
10447 sl = 100 * ((float) q->callscompletedinsl / (float) q->callscompleted);
10448 }
10449 if (q->callscompleted + q->callsabandoned > 0) {
10450 sl2 =100 * (((float)q->callsabandonedinsl + (float)q->callscompletedinsl) / ((float)q->callsabandoned + (float)q->callscompleted));
10451 }
10452
10453 ast_str_append(&out, 0, ") in '%s' strategy (%ds holdtime, %ds talktime), W:%d, C:%d, A:%d, SL:%2.1f%%, SL2:%2.1f%% within %ds",
10454 int2strat(q->strategy), q->holdtime, q->talktime, q->weight, q->callscompleted, q->callsabandoned, sl, sl2, q->servicelevel);
10455 do_print(s, fd, ast_str_buffer(out));
10456 if (!ao2_container_count(q->members)) {
10457 do_print(s, fd, " No Members");
10458 } else {
10459 struct member *mem;
10460
10461 do_print(s, fd, " Members: ");
10462 mem_iter = ao2_iterator_init(q->members, 0);
10463 while ((mem = ao2_iterator_next(&mem_iter))) {
10464 ast_str_set(&out, 0, " %s", mem->membername);
10465 if (strcasecmp(mem->membername, mem->interface)) {
10466 ast_str_append(&out, 0, " (%s", mem->interface);
10467 if (!ast_strlen_zero(mem->state_interface)
10468 && strcmp(mem->state_interface, mem->interface)) {
10469 ast_str_append(&out, 0, " from %s", mem->state_interface);
10470 }
10471 ast_str_append(&out, 0, ")");
10472 }
10473 if (mem->penalty) {
10474 ast_str_append(&out, 0, " with penalty %d", mem->penalty);
10475 }
10476
10477 ast_str_append(&out, 0, " (ringinuse %s)", mem->ringinuse ? "enabled" : "disabled");
10478
10479 ast_str_append(&out, 0, "%s%s%s%s%s%s%s%s%s",
10480 mem->dynamic ? ast_term_color(COLOR_CYAN, COLOR_BLACK) : "", mem->dynamic ? " (dynamic)" : "", ast_term_reset(),
10481 mem->realtime ? ast_term_color(COLOR_MAGENTA, COLOR_BLACK) : "", mem->realtime ? " (realtime)" : "", ast_term_reset(),
10482 mem->starttime ? ast_term_color(COLOR_BROWN, COLOR_BLACK) : "", mem->starttime ? " (in call)" : "", ast_term_reset());
10483
10484 if (mem->paused) {
10485 ast_str_append(&out, 0, " %s(paused%s%s was %ld secs ago)%s",
10486 ast_term_color(COLOR_BROWN, COLOR_BLACK),
10487 ast_strlen_zero(mem->reason_paused) ? "" : ":",
10488 ast_strlen_zero(mem->reason_paused) ? "" : mem->reason_paused,
10489 (long) (now - mem->lastpause),
10490 ast_term_reset());
10491 }
10492
10493 ast_str_append(&out, 0, " (%s%s%s)",
10494 ast_term_color(
10495 mem->status == AST_DEVICE_UNAVAILABLE || mem->status == AST_DEVICE_UNKNOWN ?
10496 COLOR_RED : COLOR_GREEN, COLOR_BLACK),
10497 ast_devstate2str(mem->status), ast_term_reset());
10498 if (mem->calls) {
10499 ast_str_append(&out, 0, " has taken %d calls (last was %ld secs ago)",
10500 mem->calls, (long) (now - mem->lastcall));
10501 } else {
10502 ast_str_append(&out, 0, " has taken no calls yet");
10503 }
10504 ast_str_append(&out, 0, " %s(login was %ld secs ago)%s",
10505 ast_term_color(COLOR_BROWN, COLOR_BLACK),
10506 (long) (now - mem->logintime),
10507 ast_term_reset());
10508 do_print(s, fd, ast_str_buffer(out));
10509 ao2_ref(mem, -1);
10510 }
10511 ao2_iterator_destroy(&mem_iter);
10512 }
10513 if (!q->head) {
10514 do_print(s, fd, " No Callers");
10515 } else {
10516 struct queue_ent *qe;
10517 int pos = 1;
10518
10519 do_print(s, fd, " Callers: ");
10520 for (qe = q->head; qe; qe = qe->next) {
10521 ast_str_set(&out, 0, " %d. %s (wait: %ld:%2.2ld, prio: %d)",
10522 pos++, ast_channel_name(qe->chan), (long) (now - qe->start) / 60,
10523 (long) (now - qe->start) % 60, qe->prio);
10524 do_print(s, fd, ast_str_buffer(out));
10525 }
10526 }
10527 do_print(s, fd, ""); /* blank line between entries */
10528 }
10529
10530 AO2_STRING_FIELD_SORT_FN(call_queue, name);
10531
10532 /*!
10533 * \brief Show queue(s) status and statistics
10534 *
10535 * List the queues strategy, calls processed, members logged in,
10536 * other queue statistics such as avg hold time.
10537 */
10538 static char *__queues_show(struct mansession *s, int fd, int argc, const char * const *argv)
10539 {
10540 struct call_queue *q;
10541 struct ast_str *out = ast_str_alloca(512);
10542 struct ao2_container *sorted_queues;
10543
10544 struct ao2_iterator queue_iter;
10545 int found = 0;
10546
10547 if (argc != 2 && argc != 3) {
10548 return CLI_SHOWUSAGE;
10549 }
10550
10551 if (argc == 3) { /* specific queue */
10552 if ((q = find_load_queue_rt_friendly(argv[2]))) {
10553 ao2_lock(q);
10554 print_queue(s, fd, q);
10555 ao2_unlock(q);
10556 queue_unref(q);
10557 } else {
10558 ast_str_set(&out, 0, "No such queue: %s.", argv[2]);
10559 do_print(s, fd, ast_str_buffer(out));
10560 }
10561 return CLI_SUCCESS;
10562 }
10563
10564 if (ast_check_realtime("queues")) {
10565 /* This block is to find any queues which are defined in realtime but
10566 * which have not yet been added to the in-core container
10567 */
10568 struct ast_config *cfg = ast_load_realtime_multientry("queues", "name LIKE", "%", SENTINEL);
10569 if (cfg) {
10570 char *category = NULL;
10571 while ((category = ast_category_browse(cfg, category))) {
10572 const char *queuename = ast_variable_retrieve(cfg, category, "name");
10573 if (ast_strlen_zero(queuename)) {
10574 ast_log(LOG_WARNING, "Ignoring realtime queue with a NULL or empty 'name.'\n");
10575 continue;
10576 }
10577 if ((q = find_load_queue_rt_friendly(queuename))) {
10578 queue_t_unref(q, "Done with temporary pointer");
10579 }
10580 }
10581 ast_config_destroy(cfg);
10582 }
10583 }
10584
10585 /*
10586 * Snapping a copy of the container prevents having to lock both the queues container
10587 * and the queue itself at the same time. It also allows us to sort the entries.
10588 */
10589 sorted_queues = ao2_container_alloc_rbtree(AO2_ALLOC_OPT_LOCK_NOLOCK, 0, call_queue_sort_fn, NULL);
10590 if (!sorted_queues) {
10591 return CLI_SUCCESS;
10592 }
10593 if (ao2_container_dup(sorted_queues, queues, 0)) {
10594 ao2_ref(sorted_queues, -1);
10595 return CLI_SUCCESS;
10596 }
10597
10598 /*
10599 * No need to lock the container since it's temporary and static.
10600 * We also unlink the entries as we use them so the container is
10601 * empty when the iterator finishes. We can then just unref the container.
10602 */
10603 queue_iter = ao2_iterator_init(sorted_queues, AO2_ITERATOR_DONTLOCK | AO2_ITERATOR_UNLINK);
10604 while ((q = ao2_t_iterator_next(&queue_iter, "Iterate through queues"))) {
10605 struct call_queue *realtime_queue = NULL;
10606 ao2_lock(q);
10607 /* This check is to make sure we don't print information for realtime
10608 * queues which have been deleted from realtime but which have not yet
10609 * been deleted from the in-core container. Only do this if we're not
10610 * looking for a specific queue.
10611 */
10612 if (q->realtime) {
10613 realtime_queue = find_load_queue_rt_friendly(q->name);
10614 if (!realtime_queue) {
10615 ao2_unlock(q);
10616 queue_t_unref(q, "Done with iterator");
10617 continue;
10618 }
10619 queue_t_unref(realtime_queue, "Queue is already in memory");
10620 }
10621
10622 found = 1;
10623 print_queue(s, fd, q);
10624
10625 ao2_unlock(q);
10626 queue_t_unref(q, "Done with iterator"); /* Unref the iterator's reference */
10627 }
10628 ao2_iterator_destroy(&queue_iter);
10629 ao2_ref(sorted_queues, -1);
10630 if (!found) {
10631 ast_str_set(&out, 0, "No queues.");
10632 do_print(s, fd, ast_str_buffer(out));
10633 }
10634 return CLI_SUCCESS;
10635 }
10636
10637 /*!
10638 * \brief Check if a given word is in a space-delimited list
10639 *
10640 * \param list Space delimited list of words
10641 * \param word The word used to search the list
10642 *
10643 * \note This function will not return 1 if the word is at the very end of the
10644 * list (followed immediately by a \0, not a space) since it is used for
10645 * checking tab-completion and a word at the end is still being tab-completed.
10646 *
10647 * \retval 1 if the word is found
10648 * \retval 0 if the word is not found
10649 */
10650 static int word_in_list(const char *list, const char *word) {
10651 int list_len, word_len = strlen(word);
10652 const char *find, *end_find, *end_list;
10653
10654 /* strip whitespace from front */
10655 while(isspace(*list)) {
10656 list++;
10657 }
10658
10659 while((find = strstr(list, word))) {
10660 /* beginning of find starts inside another word? */
10661 if (find != list && *(find - 1) != ' ') {
10662 list = find;
10663 /* strip word from front */
10664 while(!isspace(*list) && *list != '\0') {
10665 list++;
10666 }
10667 /* strip whitespace from front */
10668 while(isspace(*list)) {
10669 list++;
10670 }
10671 continue;
10672 }
10673
10674 /* end of find ends inside another word or at very end of list? */
10675 list_len = strlen(list);
10676 end_find = find + word_len;
10677 end_list = list + list_len;
10678 if (end_find == end_list || *end_find != ' ') {
10679 list = find;
10680 /* strip word from front */
10681 while(!isspace(*list) && *list != '\0') {
10682 list++;
10683 }
10684 /* strip whitespace from front */
10685 while(isspace(*list)) {
10686 list++;
10687 }
10688 continue;
10689 }
10690
10691 /* terminating conditions satisfied, word at beginning or separated by ' ' */
10692 return 1;
10693 }
10694
10695 return 0;
10696 }
10697
10698 /*!
10699 * \brief Check if a given word is in a space-delimited list
10700 *
10701 * \param line The line as typed not including the current word being completed
10702 * \param word The word currently being completed
10703 * \param pos The number of completed words in line
10704 * \param state The nth desired completion option
10705 * \param word_list_offset Offset into the line where the list of queues begins. If non-zero, queues in the list will not be offered for further completion.
10706 *
10707 * \return Returns the queue tab-completion for the given word and state
10708 */
10709 static char *complete_queue(const char *line, const char *word, int pos, int state, ptrdiff_t word_list_offset)
10710 {
10711 struct call_queue *q;
10712 char *ret = NULL;
10713 int which = 0;
10714 int wordlen = strlen(word);
10715 struct ao2_iterator queue_iter;
10716 const char *word_list = NULL;
10717
10718 /* for certain commands, already completed items should be left out of
10719 * the list */
10720 if (word_list_offset && strlen(line) >= word_list_offset) {
10721 word_list = line + word_list_offset;
10722 }
10723
10724 queue_iter = ao2_iterator_init(queues, 0);
10725 while ((q = ao2_t_iterator_next(&queue_iter, "Iterate through queues"))) {
10726 if (!strncasecmp(word, q->name, wordlen) && ++which > state
10727 && (!word_list_offset || !word_list || !word_in_list(word_list, q->name))) {
10728 ret = ast_strdup(q->name);
10729 queue_t_unref(q, "Done with iterator");
10730 break;
10731 }
10732 queue_t_unref(q, "Done with iterator");
10733 }
10734 ao2_iterator_destroy(&queue_iter);
10735
10736 /* Pretend "rules" is at the end of the queues list in certain
10737 * circumstances since it is an alternate command that should be
10738 * tab-completable for "queue show" */
10739 if (!ret && which == state && !wordlen && !strncmp("queue show", line, 10)) {
10740 ret = ast_strdup("rules");
10741 }
10742
10743 return ret;
10744 }
10745
10746 static char *complete_queue_show(const char *line, const char *word, int pos, int state)
10747 {
10748 if (pos == 2) {
10749 return complete_queue(line, word, pos, state, 0);
10750 }
10751 return NULL;
10752 }
10753
10754 static char *queue_show(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
10755 {
10756 switch ( cmd ) {
10757 case CLI_INIT:
10758 e->command = "queue show";
10759 e->usage =
10760 "Usage: queue show\n"
10761 " Provides summary information on a specified queue.\n";
10762 return NULL;
10763 case CLI_GENERATE:
10764 return complete_queue_show(a->line, a->word, a->pos, a->n);
10765 }
10766
10767 return __queues_show(NULL, a->fd, a->argc, a->argv);
10768 }
10769
10770 static int manager_queue_rule_show(struct mansession *s, const struct message *m)
10771 {
10772 const char *rule = astman_get_header(m, "Rule");
10773 const char *id = astman_get_header(m, "ActionID");
10774 struct rule_list *rl_iter;
10775 struct penalty_rule *pr_iter;
10776
10777 astman_append(s, "Response: Success\r\n");
10778 if (!ast_strlen_zero(id)) {
10779 astman_append(s, "ActionID: %s\r\n", id);
10780 }
10781
10782 AST_LIST_LOCK(&rule_lists);
10783 AST_LIST_TRAVERSE(&rule_lists, rl_iter, list) {
10784 if (ast_strlen_zero(rule) || !strcasecmp(rule, rl_iter->name)) {
10785 astman_append(s, "RuleList: %s\r\n", rl_iter->name);
10786 AST_LIST_TRAVERSE(&rl_iter->rules, pr_iter, list) {
10787 astman_append(s, "Rule: %d,%s%d,%s%d\r\n", pr_iter->time, pr_iter->max_relative && pr_iter->max_value >= 0 ? "+" : "", pr_iter->max_value, pr_iter->min_relative && pr_iter->min_value >= 0 ? "+" : "", pr_iter->min_value );
10788 }
10789 if (!ast_strlen_zero(rule)) {
10790 break;
10791 }
10792 }
10793 }
10794 AST_LIST_UNLOCK(&rule_lists);
10795
10796 /*
10797 * Two blank lines instead of one because the Response and
10798 * ActionID headers used to not be present.
10799 */
10800 astman_append(s, "\r\n\r\n");
10801
10802 return RESULT_SUCCESS;
10803 }
10804
10805 /*! \brief Summary of queue info via the AMI */
10806 static int manager_queues_summary(struct mansession *s, const struct message *m)
10807 {
10808 time_t now;
10809 int qmemcount = 0;
10810 int qmemavail = 0;
10811 int qchancount = 0;
10812 int qlongestholdtime = 0;
10813 int qsummaries = 0;
10814 const char *id = astman_get_header(m, "ActionID");
10815 const char *queuefilter = astman_get_header(m, "Queue");
10816 char idText[256];
10817 struct call_queue *q;
10818 struct queue_ent *qe;
10819 struct member *mem;
10820 struct ao2_iterator queue_iter;
10821 struct ao2_iterator mem_iter;
10822
10823 if (ast_check_realtime("queues")) {
10824 load_realtime_queues(queuefilter);
10825 }
10826
10827 astman_send_listack(s, m, "Queue summary will follow", "start");
10828 time(&now);
10829 idText[0] = '\0';
10830 if (!ast_strlen_zero(id)) {
10831 snprintf(idText, sizeof(idText), "ActionID: %s\r\n", id);
10832 }
10833 queue_iter = ao2_iterator_init(queues, 0);
10834 while ((q = ao2_t_iterator_next(&queue_iter, "Iterate through queues"))) {
10835 ao2_lock(q);
10836
10837 /* List queue properties */
10838 if (ast_strlen_zero(queuefilter) || !strcasecmp(q->name, queuefilter)) {
10839 /* Reset the necessary local variables if no queuefilter is set*/
10840 qmemcount = 0;
10841 qmemavail = 0;
10842 qchancount = 0;
10843 qlongestholdtime = 0;
10844
10845 /* List Queue Members */
10846 mem_iter = ao2_iterator_init(q->members, 0);
10847 while ((mem = ao2_iterator_next(&mem_iter))) {
10848 if ((mem->status != AST_DEVICE_UNAVAILABLE) && (mem->status != AST_DEVICE_INVALID)) {
10849 ++qmemcount;
10850 if (member_status_available(mem->status) && !mem->paused) {
10851 ++qmemavail;
10852 }
10853 }
10854 ao2_ref(mem, -1);
10855 }
10856 ao2_iterator_destroy(&mem_iter);
10857 for (qe = q->head; qe; qe = qe->next) {
10858 if ((now - qe->start) > qlongestholdtime) {
10859 qlongestholdtime = now - qe->start;
10860 }
10861 ++qchancount;
10862 }
10863 astman_append(s, "Event: QueueSummary\r\n"
10864 "Queue: %s\r\n"
10865 "LoggedIn: %d\r\n"
10866 "Available: %d\r\n"
10867 "Callers: %d\r\n"
10868 "HoldTime: %d\r\n"
10869 "TalkTime: %d\r\n"
10870 "LongestHoldTime: %d\r\n"
10871 "%s"
10872 "\r\n",
10873 q->name, qmemcount, qmemavail, qchancount, q->holdtime, q->talktime, qlongestholdtime, idText);
10874 ++qsummaries;
10875 }
10876 ao2_unlock(q);
10877 queue_t_unref(q, "Done with iterator");
10878 }
10879 ao2_iterator_destroy(&queue_iter);
10880
10881 astman_send_list_complete_start(s, m, "QueueSummaryComplete", qsummaries);
10882 astman_send_list_complete_end(s);
10883
10884 return RESULT_SUCCESS;
10885 }
10886
10887 /*! \brief Queue status info via AMI */
10888 static int manager_queues_status(struct mansession *s, const struct message *m)
10889 {
10890 time_t now;
10891 int pos;
10892 int q_items = 0;
10893 const char *id = astman_get_header(m,"ActionID");
10894 const char *queuefilter = astman_get_header(m,"Queue");
10895 const char *memberfilter = astman_get_header(m,"Member");
10896 char idText[256];
10897 struct call_queue *q;
10898 struct queue_ent *qe;
10899 float sl = 0;
10900 float sl2 = 0;
10901 struct member *mem;
10902 struct ao2_iterator queue_iter;
10903 struct ao2_iterator mem_iter;
10904
10905 if (ast_check_realtime("queues")) {
10906 load_realtime_queues(queuefilter);
10907 }
10908
10909 astman_send_listack(s, m, "Queue status will follow", "start");
10910 time(&now);
10911 idText[0] = '\0';
10912 if (!ast_strlen_zero(id)) {
10913 snprintf(idText, sizeof(idText), "ActionID: %s\r\n", id);
10914 }
10915
10916 queue_iter = ao2_iterator_init(queues, 0);
10917 while ((q = ao2_t_iterator_next(&queue_iter, "Iterate through queues"))) {
10918 ao2_lock(q);
10919
10920 /* List queue properties */
10921 if (ast_strlen_zero(queuefilter) || !strcasecmp(q->name, queuefilter)) {
10922 sl = ((q->callscompleted > 0) ? 100 * ((float)q->callscompletedinsl / (float)q->callscompleted) : 0);
10923 sl2 = (((q->callscompleted + q->callsabandoned) > 0) ? 100 * (((float)q->callsabandonedinsl + (float)q->callscompletedinsl) / ((float)q->callsabandoned + (float)q->callscompleted)) : 0);
10924
10925 astman_append(s, "Event: QueueParams\r\n"
10926 "Queue: %s\r\n"
10927 "Max: %d\r\n"
10928 "Strategy: %s\r\n"
10929 "Calls: %d\r\n"
10930 "Holdtime: %d\r\n"
10931 "TalkTime: %d\r\n"
10932 "Completed: %d\r\n"
10933 "Abandoned: %d\r\n"
10934 "ServiceLevel: %d\r\n"
10935 "ServicelevelPerf: %2.1f\r\n"
10936 "ServicelevelPerf2: %2.1f\r\n"
10937 "Weight: %d\r\n"
10938 "%s"
10939 "\r\n",
10940 q->name, q->maxlen, int2strat(q->strategy), q->count, q->holdtime, q->talktime, q->callscompleted,
10941 q->callsabandoned, q->servicelevel, sl, sl2, q->weight, idText);
10942 ++q_items;
10943
10944 /* List Queue Members */
10945 mem_iter = ao2_iterator_init(q->members, 0);
10946 while ((mem = ao2_iterator_next(&mem_iter))) {
10947 if (ast_strlen_zero(memberfilter) || !strcmp(mem->interface, memberfilter) || !strcmp(mem->membername, memberfilter)) {
10948 astman_append(s, "Event: QueueMember\r\n"
10949 "Queue: %s\r\n"
10950 "Name: %s\r\n"
10951 "Location: %s\r\n"
10952 "StateInterface: %s\r\n"
10953 "Membership: %s\r\n"
10954 "Penalty: %d\r\n"
10955 "CallsTaken: %d\r\n"
10956 "LastCall: %d\r\n"
10957 "LastPause: %d\r\n"
10958 "LoginTime: %d\r\n"
10959 "InCall: %d\r\n"
10960 "Status: %d\r\n"
10961 "Paused: %d\r\n"
10962 "PausedReason: %s\r\n"
10963 "Wrapuptime: %d\r\n"
10964 "%s"
10965 "\r\n",
10966 q->name, mem->membername, mem->interface, mem->state_interface, mem->dynamic ? "dynamic" : "static",
10967 mem->penalty, mem->calls, (int)mem->lastcall, (int)mem->lastpause, (int)mem->logintime, mem->starttime ? 1 : 0, mem->status,
10968 mem->paused, mem->reason_paused, mem->wrapuptime, idText);
10969 ++q_items;
10970 }
10971 ao2_ref(mem, -1);
10972 }
10973 ao2_iterator_destroy(&mem_iter);
10974
10975 /* List Queue Entries */
10976 pos = 1;
10977 for (qe = q->head; qe; qe = qe->next) {
10978 astman_append(s, "Event: QueueEntry\r\n"
10979 "Queue: %s\r\n"
10980 "Position: %d\r\n"
10981 "Channel: %s\r\n"
10982 "Uniqueid: %s\r\n"
10983 "CallerIDNum: %s\r\n"
10984 "CallerIDName: %s\r\n"
10985 "ConnectedLineNum: %s\r\n"
10986 "ConnectedLineName: %s\r\n"
10987 "Wait: %ld\r\n"
10988 "Priority: %d\r\n"
10989 "%s"
10990 "\r\n",
10991 q->name, pos++, ast_channel_name(qe->chan), ast_channel_uniqueid(qe->chan),
10992 S_COR(ast_channel_caller(qe->chan)->id.number.valid, ast_channel_caller(qe->chan)->id.number.str, "unknown"),
10993 S_COR(ast_channel_caller(qe->chan)->id.name.valid, ast_channel_caller(qe->chan)->id.name.str, "unknown"),
10994 S_COR(ast_channel_connected(qe->chan)->id.number.valid, ast_channel_connected(qe->chan)->id.number.str, "unknown"),
10995 S_COR(ast_channel_connected(qe->chan)->id.name.valid, ast_channel_connected(qe->chan)->id.name.str, "unknown"),
10996 (long) (now - qe->start), qe->prio, idText);
10997 ++q_items;
10998 }
10999 }
11000 ao2_unlock(q);
11001 queue_t_unref(q, "Done with iterator");
11002 }
11003 ao2_iterator_destroy(&queue_iter);
11004
11005 astman_send_list_complete_start(s, m, "QueueStatusComplete", q_items);
11006 astman_send_list_complete_end(s);
11007
11008 return RESULT_SUCCESS;
11009 }
11010
11011 static int manager_add_queue_member(struct mansession *s, const struct message *m)
11012 {
11013 const char *queuename, *interface, *penalty_s, *paused_s, *reason, *membername, *state_interface, *wrapuptime_s;
11014 int paused, penalty, wrapuptime = 0;
11015
11016 queuename = astman_get_header(m, "Queue");
11017 interface = astman_get_header(m, "Interface");
11018 penalty_s = astman_get_header(m, "Penalty");
11019 paused_s = astman_get_header(m, "Paused");
11020 reason = astman_get_header(m, "Reason"); /* Optional */
11021 membername = astman_get_header(m, "MemberName");
11022 state_interface = astman_get_header(m, "StateInterface");
11023 wrapuptime_s = astman_get_header(m, "Wrapuptime");
11024
11025 if (ast_strlen_zero(queuename)) {
11026 astman_send_error(s, m, "'Queue' not specified.");
11027 return 0;
11028 }
11029
11030 if (ast_strlen_zero(interface)) {
11031 astman_send_error(s, m, "'Interface' not specified.");
11032 return 0;
11033 }
11034
11035 if (ast_strlen_zero(penalty_s)) {
11036 penalty = 0;
11037 } else if (sscanf(penalty_s, "%30d", &penalty) != 1 || penalty < 0) {
11038 penalty = 0;
11039 }
11040
11041 if (ast_strlen_zero(wrapuptime_s)) {
11042 wrapuptime = 0;
11043 } else if (sscanf(wrapuptime_s, "%30d", &wrapuptime) != 1 || wrapuptime < 0) {
11044 wrapuptime = 0;
11045 }
11046
11047 if (ast_strlen_zero(paused_s)) {
11048 paused = 0;
11049 } else {
11050 paused = abs(ast_true(paused_s));
11051 }
11052
11053 switch (add_to_queue(queuename, interface, membername, penalty, paused, queue_persistent_members, state_interface, reason, wrapuptime)) {
11054 case RES_OKAY:
11055 if (ast_strlen_zero(membername) || !log_membername_as_agent) {
11056 ast_queue_log(queuename, "MANAGER", interface, "ADDMEMBER", "%s", paused ? "PAUSED" : "");
11057 } else {
11058 ast_queue_log(queuename, "MANAGER", membername, "ADDMEMBER", "%s", paused ? "PAUSED" : "");
11059 }
11060 astman_send_ack(s, m, "Added interface to queue");
11061 break;
11062 case RES_EXISTS:
11063 astman_send_error(s, m, "Unable to add interface: Already there");
11064 break;
11065 case RES_NOSUCHQUEUE:
11066 astman_send_error(s, m, "Unable to add interface to queue: No such queue");
11067 break;
11068 case RES_OUTOFMEMORY:
11069 astman_send_error(s, m, "Out of memory");
11070 break;
11071 }
11072
11073 return 0;
11074 }
11075
11076 static int manager_remove_queue_member(struct mansession *s, const struct message *m)
11077 {
11078 const char *queuename, *interface;
11079 struct member *mem = NULL;
11080
11081 queuename = astman_get_header(m, "Queue");
11082 interface = astman_get_header(m, "Interface");
11083
11084 if (ast_strlen_zero(queuename) || ast_strlen_zero(interface)) {
11085 astman_send_error(s, m, "Need 'Queue' and 'Interface' parameters.");
11086 return 0;
11087 }
11088
11089 if (log_membername_as_agent) {
11090 mem = find_member_by_queuename_and_interface(queuename, interface);
11091 }
11092
11093 switch (remove_from_queue(queuename, interface)) {
11094 case RES_OKAY:
11095 if (!mem || ast_strlen_zero(mem->membername)) {
11096 ast_queue_log(queuename, "MANAGER", interface, "REMOVEMEMBER", "%s", "");
11097 } else {
11098 ast_queue_log(queuename, "MANAGER", mem->membername, "REMOVEMEMBER", "%s", "");
11099 }
11100 astman_send_ack(s, m, "Removed interface from queue");
11101 break;
11102 case RES_EXISTS:
11103 astman_send_error(s, m, "Unable to remove interface: Not there");
11104 break;
11105 case RES_NOSUCHQUEUE:
11106 astman_send_error(s, m, "Unable to remove interface from queue: No such queue");
11107 break;
11108 case RES_OUTOFMEMORY:
11109 astman_send_error(s, m, "Out of memory");
11110 break;
11111 case RES_NOT_DYNAMIC:
11112 astman_send_error(s, m, "Member not dynamic");
11113 break;
11114 }
11115
11116 if (mem) {
11117 ao2_ref(mem, -1);
11118 }
11119
11120 return 0;
11121 }
11122
11123 static int manager_pause_queue_member(struct mansession *s, const struct message *m)
11124 {
11125 const char *queuename, *interface, *paused_s, *reason;
11126 int paused;
11127
11128 interface = astman_get_header(m, "Interface");
11129 paused_s = astman_get_header(m, "Paused");
11130 queuename = astman_get_header(m, "Queue"); /* Optional - if not supplied, pause the given Interface in all queues */
11131 reason = astman_get_header(m, "Reason"); /* Optional */
11132
11133 if (ast_strlen_zero(interface) || ast_strlen_zero(paused_s)) {
11134 astman_send_error(s, m, "Need 'Interface' and 'Paused' parameters.");
11135 return 0;
11136 }
11137
11138 paused = abs(ast_true(paused_s));
11139
11140 if (set_member_paused(queuename, interface, reason, paused)) {
11141 astman_send_error(s, m, "Interface not found");
11142 } else {
11143 astman_send_ack(s, m, paused ? "Interface paused successfully" : "Interface unpaused successfully");
11144 }
11145 return 0;
11146 }
11147
11148 static int manager_queue_log_custom(struct mansession *s, const struct message *m)
11149 {
11150 const char *queuename, *event, *message, *interface, *uniqueid;
11151
11152 queuename = astman_get_header(m, "Queue");
11153 uniqueid = astman_get_header(m, "UniqueId");
11154 interface = astman_get_header(m, "Interface");
11155 event = astman_get_header(m, "Event");
11156 message = astman_get_header(m, "Message");
11157
11158 if (ast_strlen_zero(queuename) || ast_strlen_zero(event)) {
11159 astman_send_error(s, m, "Need 'Queue' and 'Event' parameters.");
11160 return 0;
11161 }
11162
11163 ast_queue_log(queuename, S_OR(uniqueid, "NONE"), interface, event, "%s", message);
11164 astman_send_ack(s, m, "Event added successfully");
11165
11166 return 0;
11167 }
11168
11169 static int manager_queue_reload(struct mansession *s, const struct message *m)
11170 {
11171 struct ast_flags mask = {0,};
11172 const char *queuename = NULL;
11173 int header_found = 0;
11174
11175 queuename = astman_get_header(m, "Queue");
11176 if (!strcasecmp(S_OR(astman_get_header(m, "Members"), ""), "yes")) {
11177 ast_set_flag(&mask, QUEUE_RELOAD_MEMBER);
11178 header_found = 1;
11179 }
11180 if (!strcasecmp(S_OR(astman_get_header(m, "Rules"), ""), "yes")) {
11181 ast_set_flag(&mask, QUEUE_RELOAD_RULES);
11182 header_found = 1;
11183 }
11184 if (!strcasecmp(S_OR(astman_get_header(m, "Parameters"), ""), "yes")) {
11185 ast_set_flag(&mask, QUEUE_RELOAD_PARAMETERS);
11186 header_found = 1;
11187 }
11188
11189 if (!header_found) {
11190 ast_set_flag(&mask, AST_FLAGS_ALL & ~QUEUE_RESET_STATS);
11191 }
11192
11193 if (!reload_handler(1, &mask, queuename)) {
11194 astman_send_ack(s, m, "Queue reloaded successfully");
11195 } else {
11196 astman_send_error(s, m, "Error encountered while reloading queue");
11197 }
11198 return 0;
11199 }
11200
11201 static int manager_queue_reset(struct mansession *s, const struct message *m)
11202 {
11203 const char *queuename = NULL;
11204 struct ast_flags mask = {QUEUE_RESET_STATS,};
11205
11206 queuename = astman_get_header(m, "Queue");
11207
11208 if (!reload_handler(1, &mask, queuename)) {
11209 astman_send_ack(s, m, "Queue stats reset successfully");
11210 } else {
11211 astman_send_error(s, m, "Error encountered while resetting queue stats");
11212 }
11213 return 0;
11214 }
11215
11216 static char *complete_queue_add_member(const char *line, const char *word, int pos, int state)
11217 {
11218 /* 0 - queue; 1 - add; 2 - member; 3 - <interface>; 4 - to; 5 - <queue>; 6 - penalty; 7 - <penalty>; 8 - as; 9 - <membername> */
11219 switch (pos) {
11220 case 3: /* Don't attempt to complete name of interface (infinite possibilities) */
11221 return NULL;
11222 case 4: /* only one possible match, "to" */
11223 return state == 0 ? ast_strdup("to") : NULL;
11224 case 5: /* <queue> */
11225 return complete_queue(line, word, pos, state, 0);
11226 case 6: /* only one possible match, "penalty" */
11227 return state == 0 ? ast_strdup("penalty") : NULL;
11228 case 7:
11229 if (0 <= state && state < 100) { /* 0-99 */
11230 char *num;
11231 if ((num = ast_malloc(3))) {
11232 sprintf(num, "%d", state);
11233 }
11234 return num;
11235 } else {
11236 return NULL;
11237 }
11238 case 8: /* only one possible match, "as" */
11239 return state == 0 ? ast_strdup("as") : NULL;
11240 case 9: /* Don't attempt to complete name of member (infinite possibilities) */
11241 return NULL;
11242 default:
11243 return NULL;
11244 }
11245 }
11246
11247 static int manager_queue_member_ringinuse(struct mansession *s, const struct message *m)
11248 {
11249 const char *queuename, *interface, *ringinuse_s;
11250 int ringinuse;
11251
11252 interface = astman_get_header(m, "Interface");
11253 ringinuse_s = astman_get_header(m, "RingInUse");
11254
11255 /* Optional - if not supplied, set the ringinuse value for the given Interface in all queues */
11256 queuename = astman_get_header(m, "Queue");
11257
11258 if (ast_strlen_zero(interface) || ast_strlen_zero(ringinuse_s)) {
11259 astman_send_error(s, m, "Need 'Interface' and 'RingInUse' parameters.");
11260 return 0;
11261 }
11262
11263 if (ast_true(ringinuse_s)) {
11264 ringinuse = 1;
11265 } else if (ast_false(ringinuse_s)) {
11266 ringinuse = 0;
11267 } else {
11268 astman_send_error(s, m, "'RingInUse' parameter must be a truth value (yes/no, on/off, 0/1, etc)");
11269 return 0;
11270 }
11271
11272 if (set_member_value(queuename, interface, MEMBER_RINGINUSE, ringinuse)) {
11273 astman_send_error(s, m, "Invalid interface, queuename, or ringinuse value\n");
11274 } else {
11275 astman_send_ack(s, m, "Interface ringinuse set successfully");
11276 }
11277
11278 return 0;
11279 }
11280
11281 static int manager_queue_member_penalty(struct mansession *s, const struct message *m)
11282 {
11283 const char *queuename, *interface, *penalty_s;
11284 int penalty;
11285
11286 interface = astman_get_header(m, "Interface");
11287 penalty_s = astman_get_header(m, "Penalty");
11288 /* Optional - if not supplied, set the penalty value for the given Interface in all queues */
11289 queuename = astman_get_header(m, "Queue");
11290
11291 if (ast_strlen_zero(interface) || ast_strlen_zero(penalty_s)) {
11292 astman_send_error(s, m, "Need 'Interface' and 'Penalty' parameters.");
11293 return 0;
11294 }
11295
11296 penalty = atoi(penalty_s);
11297
11298 if (set_member_value((char *)queuename, (char *)interface, MEMBER_PENALTY, penalty)) {
11299 astman_send_error(s, m, "Invalid interface, queuename or penalty");
11300 } else {
11301 astman_send_ack(s, m, "Interface penalty set successfully");
11302 }
11303
11304 return 0;
11305 }
11306
11307 static int manager_change_priority_caller_on_queue(struct mansession *s, const struct message *m)
11308 {
11309 const char *queuename, *caller, *priority_s, *immediate_s;
11310 int priority = 0, immediate = 0;
11311
11312 queuename = astman_get_header(m, "Queue");
11313 caller = astman_get_header(m, "Caller");
11314 priority_s = astman_get_header(m, "Priority");
11315 immediate_s = astman_get_header(m, "Immediate");
11316
11317 if (ast_strlen_zero(queuename)) {
11318 astman_send_error(s, m, "'Queue' not specified.");
11319 return 0;
11320 }
11321
11322 if (ast_strlen_zero(caller)) {
11323 astman_send_error(s, m, "'Caller' not specified.");
11324 return 0;
11325 }
11326
11327 if (ast_strlen_zero(priority_s)) {
11328 astman_send_error(s, m, "'Priority' not specified.");
11329 return 0;
11330 } else if (sscanf(priority_s, "%30d", &priority) != 1) {
11331 astman_send_error(s, m, "'Priority' need integer.");
11332 return 0;
11333 }
11334
11335 if (!ast_strlen_zero(immediate_s)) {
11336 immediate = ast_true(immediate_s);
11337 }
11338
11339 switch (change_priority_caller_on_queue(queuename, caller, priority, immediate)) {
11340 case RES_OKAY:
11341 astman_send_ack(s, m, "Priority change for caller on queue");
11342 break;
11343 case RES_NOSUCHQUEUE:
11344 astman_send_error(s, m, "Unable to change priority caller on queue: No such queue");
11345 break;
11346 case RES_NOT_CALLER:
11347 astman_send_error(s, m, "Unable to change priority caller on queue: No such caller");
11348 break;
11349 }
11350
11351 return 0;
11352 }
11353
11354 static int manager_request_withdraw_caller_from_queue(struct mansession *s, const struct message *m)
11355 {
11356 const char *queuename, *caller, *withdraw_info;
11357
11358 queuename = astman_get_header(m, "Queue");
11359 caller = astman_get_header(m, "Caller");
11360 withdraw_info = astman_get_header(m, "WithdrawInfo");
11361
11362 if (ast_strlen_zero(queuename)) {
11363 astman_send_error(s, m, "'Queue' not specified.");
11364 return 0;
11365 }
11366
11367 if (ast_strlen_zero(caller)) {
11368 astman_send_error(s, m, "'Caller' not specified.");
11369 return 0;
11370 }
11371
11372 switch (request_withdraw_caller_from_queue(queuename, caller, withdraw_info)) {
11373 case RES_OKAY:
11374 astman_send_ack(s, m, "Withdraw requested successfully");
11375 break;
11376 case RES_NOSUCHQUEUE:
11377 astman_send_error(s, m, "Unable to request withdraw from queue: No such queue");
11378 break;
11379 case RES_NOT_CALLER:
11380 astman_send_error(s, m, "Unable to request withdraw from queue: No such caller");
11381 break;
11382 case RES_EXISTS:
11383 astman_send_error(s, m, "Unable to request withdraw from queue: Already requested");
11384 break;
11385 }
11386
11387 return 0;
11388 }
11389
11390
11391 static char *handle_queue_add_member(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
11392 {
11393 const char *queuename, *interface, *membername = NULL, *state_interface = NULL, *reason = NULL;
11394 int penalty, paused = 0;
11395
11396 switch ( cmd ) {
11397 case CLI_INIT:
11398 e->command = "queue add member";
11399 e->usage =
11400 "Usage: queue add member <dial string> to <queue> [penalty <penalty> [as <membername> [state_interface <interface> [paused <reason>]]]]\n"
11401 " Add a dial string (Such as a channel,e.g. SIP/6001) to a queue with optionally: a penalty, membername and a state_interface\n";
11402 return NULL;
11403 case CLI_GENERATE:
11404 return complete_queue_add_member(a->line, a->word, a->pos, a->n);
11405 }
11406
11407 if ((a->argc != 6) && (a->argc != 8) && (a->argc != 10) && (a->argc != 12) && (a->argc != 14)) {
11408 return CLI_SHOWUSAGE;
11409 } else if (strcmp(a->argv[4], "to")) {
11410 return CLI_SHOWUSAGE;
11411 } else if ((a->argc >= 8) && strcmp(a->argv[6], "penalty")) {
11412 return CLI_SHOWUSAGE;
11413 } else if ((a->argc >= 10) && strcmp(a->argv[8], "as")) {
11414 return CLI_SHOWUSAGE;
11415 } else if ((a->argc == 12) && strcmp(a->argv[10], "state_interface")) {
11416 return CLI_SHOWUSAGE;
11417 } else if ((a->argc == 14) && strcmp(a->argv[12], "paused")) {
11418 return CLI_SHOWUSAGE;
11419 }
11420
11421 queuename = a->argv[5];
11422 interface = a->argv[3];
11423 if (a->argc >= 8) {
11424 if (sscanf(a->argv[7], "%30d", &penalty) == 1) {
11425 if (penalty < 0) {
11426 ast_cli(a->fd, "Penalty must be >= 0\n");
11427 penalty = 0;
11428 }
11429 } else {
11430 ast_cli(a->fd, "Penalty must be an integer >= 0\n");
11431 penalty = 0;
11432 }
11433 } else {
11434 penalty = 0;
11435 }
11436
11437 if (a->argc >= 10) {
11438 membername = a->argv[9];
11439 }
11440
11441 if (a->argc >= 12) {
11442 state_interface = a->argv[11];
11443 }
11444
11445 if (a->argc >= 14) {
11446 paused = 1;
11447 reason = a->argv[13];
11448 }
11449
11450 switch (add_to_queue(queuename, interface, membername, penalty, paused, queue_persistent_members, state_interface, reason, 0)) {
11451 case RES_OKAY:
11452 if (ast_strlen_zero(membername) || !log_membername_as_agent) {
11453 ast_queue_log(queuename, "CLI", interface, "ADDMEMBER", "%s", paused ? "PAUSED" : "");
11454 } else {
11455 ast_queue_log(queuename, "CLI", membername, "ADDMEMBER", "%s", paused ? "PAUSED" : "");
11456 }
11457 ast_cli(a->fd, "Added interface '%s' to queue '%s'\n", interface, queuename);
11458 return CLI_SUCCESS;
11459 case RES_EXISTS:
11460 ast_cli(a->fd, "Unable to add interface '%s' to queue '%s': Already there\n", interface, queuename);
11461 return CLI_FAILURE;
11462 case RES_NOSUCHQUEUE:
11463 ast_cli(a->fd, "Unable to add interface to queue '%s': No such queue\n", queuename);
11464 return CLI_FAILURE;
11465 case RES_OUTOFMEMORY:
11466 ast_cli(a->fd, "Out of memory\n");
11467 return CLI_FAILURE;
11468 case RES_NOT_DYNAMIC:
11469 ast_cli(a->fd, "Member not dynamic\n");
11470 return CLI_FAILURE;
11471 default:
11472 return CLI_FAILURE;
11473 }
11474 }
11475
11476 static char *complete_queue_remove_member(const char *line, const char *word, int pos, int state)
11477 {
11478 int which = 0;
11479 struct call_queue *q;
11480 struct member *m;
11481 struct ao2_iterator queue_iter;
11482 struct ao2_iterator mem_iter;
11483 int wordlen = strlen(word);
11484
11485 /* 0 - queue; 1 - remove; 2 - member; 3 - <member>; 4 - from; 5 - <queue> */
11486 if (pos > 5 || pos < 3) {
11487 return NULL;
11488 }
11489 if (pos == 4) { /* only one possible match, 'from' */
11490 return (state == 0 ? ast_strdup("from") : NULL);
11491 }
11492
11493 if (pos == 5) { /* No need to duplicate code */
11494 return complete_queue(line, word, pos, state, 0);
11495 }
11496
11497 /* here is the case for 3, <member> */
11498 queue_iter = ao2_iterator_init(queues, 0);
11499 while ((q = ao2_t_iterator_next(&queue_iter, "Iterate through queues"))) {
11500 ao2_lock(q);
11501 mem_iter = ao2_iterator_init(q->members, 0);
11502 while ((m = ao2_iterator_next(&mem_iter))) {
11503 if (!strncasecmp(word, m->membername, wordlen) && ++which > state) {
11504 char *tmp;
11505 tmp = ast_strdup(m->interface);
11506 ao2_ref(m, -1);
11507 ao2_iterator_destroy(&mem_iter);
11508 ao2_unlock(q);
11509 queue_t_unref(q, "Done with iterator, returning interface name");
11510 ao2_iterator_destroy(&queue_iter);
11511 return tmp;
11512 }
11513 ao2_ref(m, -1);
11514 }
11515 ao2_iterator_destroy(&mem_iter);
11516 ao2_unlock(q);
11517 queue_t_unref(q, "Done with iterator");
11518 }
11519 ao2_iterator_destroy(&queue_iter);
11520
11521 return NULL;
11522 }
11523
11524 static char *handle_queue_remove_member(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
11525 {
11526 const char *queuename, *interface;
11527 struct member *mem = NULL;
11528 char *res = CLI_FAILURE;
11529
11530 switch (cmd) {
11531 case CLI_INIT:
11532 e->command = "queue remove member";
11533 e->usage =
11534 "Usage: queue remove member <channel> from <queue>\n"
11535 " Remove a specific channel from a queue.\n";
11536 return NULL;
11537 case CLI_GENERATE:
11538 return complete_queue_remove_member(a->line, a->word, a->pos, a->n);
11539 }
11540
11541 if (a->argc != 6) {
11542 return CLI_SHOWUSAGE;
11543 } else if (strcmp(a->argv[4], "from")) {
11544 return CLI_SHOWUSAGE;
11545 }
11546
11547 queuename = a->argv[5];
11548 interface = a->argv[3];
11549
11550 if (log_membername_as_agent) {
11551 mem = find_member_by_queuename_and_interface(queuename, interface);
11552 }
11553
11554 switch (remove_from_queue(queuename, interface)) {
11555 case RES_OKAY:
11556 if (!mem || ast_strlen_zero(mem->membername)) {
11557 ast_queue_log(queuename, "CLI", interface, "REMOVEMEMBER", "%s", "");
11558 } else {
11559 ast_queue_log(queuename, "CLI", mem->membername, "REMOVEMEMBER", "%s", "");
11560 }
11561 ast_cli(a->fd, "Removed interface %s from queue '%s'\n", interface, queuename);
11562 res = CLI_SUCCESS;
11563 break;
11564 case RES_EXISTS:
11565 ast_cli(a->fd, "Unable to remove interface '%s' from queue '%s': Not there\n", interface, queuename);
11566 break;
11567 case RES_NOSUCHQUEUE:
11568 ast_cli(a->fd, "Unable to remove interface from queue '%s': No such queue\n", queuename);
11569 break;
11570 case RES_OUTOFMEMORY:
11571 ast_cli(a->fd, "Out of memory\n");
11572 break;
11573 case RES_NOT_DYNAMIC:
11574 ast_cli(a->fd, "Unable to remove interface '%s' from queue '%s': Member is not dynamic\n", interface, queuename);
11575 break;
11576 }
11577
11578 if (mem) {
11579 ao2_ref(mem, -1);
11580 }
11581
11582 return res;
11583 }
11584
11585
11586
11587 static char *handle_queue_change_priority_caller(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
11588 {
11589 const char *queuename, *caller;
11590 int priority, immediate = 0;
11591 char *res = CLI_FAILURE;
11592
11593 switch (cmd) {
11594 case CLI_INIT:
11595 e->command = "queue priority caller";
11596 e->usage =
11597 "Usage: queue priority caller <channel> on <queue> to <priority> [immediate]\n"
11598 " Change the priority of a channel on a queue, optionally applying the change in relation to existing callers.\n";
11599 return NULL;
11600 case CLI_GENERATE:
11601 return NULL;
11602 }
11603
11604 if (a->argc < 8) {
11605 return CLI_SHOWUSAGE;
11606 } else if (strcmp(a->argv[4], "on")) {
11607 return CLI_SHOWUSAGE;
11608 } else if (strcmp(a->argv[6], "to")) {
11609 return CLI_SHOWUSAGE;
11610 } else if (sscanf(a->argv[7], "%30d", &priority) != 1) {
11611 ast_log (LOG_ERROR, "<priority> parameter must be an integer.\n");
11612 return CLI_SHOWUSAGE;
11613 } else if (a->argc == 9) {
11614 if (strcmp(a->argv[8], "immediate")) {
11615 return CLI_SHOWUSAGE;
11616 }
11617 immediate = 1;
11618 }
11619
11620 caller = a->argv[3];
11621 queuename = a->argv[5];
11622
11623 switch (change_priority_caller_on_queue(queuename, caller, priority, immediate)) {
11624 case RES_OKAY:
11625 res = CLI_SUCCESS;
11626 break;
11627 case RES_NOSUCHQUEUE:
11628 ast_cli(a->fd, "Unable change priority caller %s on queue '%s': No such queue\n", caller, queuename);
11629 break;
11630 case RES_NOT_CALLER:
11631 ast_cli(a->fd, "Unable to change priority caller '%s' on queue '%s': Not there\n", caller, queuename);
11632
11633 break;
11634 }
11635
11636 return res;
11637 }
11638
11639
11640
11641 static char *complete_queue_pause_member(const char *line, const char *word, int pos, int state)
11642 {
11643 /* 0 - queue; 1 - pause; 2 - member; 3 - <interface>; 4 - queue; 5 - <queue>; 6 - reason; 7 - <reason> */
11644 switch (pos) {
11645 case 3: /* Don't attempt to complete name of interface (infinite possibilities) */
11646 return NULL;
11647 case 4: /* only one possible match, "queue" */
11648 return state == 0 ? ast_strdup("queue") : NULL;
11649 case 5: /* <queue> */
11650 return complete_queue(line, word, pos, state, 0);
11651 case 6: /* "reason" */
11652 return state == 0 ? ast_strdup("reason") : NULL;
11653 case 7: /* Can't autocomplete a reason, since it's 100% customizeable */
11654 return NULL;
11655 default:
11656 return NULL;
11657 }
11658 }
11659
11660 static char *handle_queue_pause_member(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
11661 {
11662 const char *queuename, *interface, *reason;
11663 int paused;
11664
11665 switch (cmd) {
11666 case CLI_INIT:
11667 e->command = "queue {pause|unpause} member";
11668 e->usage =
11669 "Usage: queue {pause|unpause} member <member> [queue <queue> [reason <reason>]]\n"
11670 " Pause or unpause a queue member. Not specifying a particular queue\n"
11671 " will pause or unpause a member across all queues to which the member\n"
11672 " belongs.\n";
11673 return NULL;
11674 case CLI_GENERATE:
11675 return complete_queue_pause_member(a->line, a-> word, a->pos, a->n);
11676 }
11677
11678 if (a->argc < 4 || a->argc == 5 || a->argc == 7 || a->argc > 8) {
11679 return CLI_SHOWUSAGE;
11680 } else if (a->argc >= 5 && strcmp(a->argv[4], "queue")) {
11681 return CLI_SHOWUSAGE;
11682 } else if (a->argc == 8 && strcmp(a->argv[6], "reason")) {
11683 return CLI_SHOWUSAGE;
11684 }
11685
11686
11687 interface = a->argv[3];
11688 queuename = a->argc >= 6 ? a->argv[5] : NULL;
11689 reason = a->argc == 8 ? a->argv[7] : NULL;
11690 paused = !strcasecmp(a->argv[1], "pause");
11691
11692 if (set_member_paused(queuename, interface, reason, paused) == RESULT_SUCCESS) {
11693 ast_cli(a->fd, "%spaused interface '%s'", paused ? "" : "un", interface);
11694 if (!ast_strlen_zero(queuename)) {
11695 ast_cli(a->fd, " in queue '%s'", queuename);
11696 }
11697 if (!ast_strlen_zero(reason)) {
11698 ast_cli(a->fd, " for reason '%s'", reason);
11699 }
11700 ast_cli(a->fd, "\n");
11701 return CLI_SUCCESS;
11702 } else {
11703 ast_cli(a->fd, "Unable to %spause interface '%s'", paused ? "" : "un", interface);
11704 if (!ast_strlen_zero(queuename)) {
11705 ast_cli(a->fd, " in queue '%s'", queuename);
11706 }
11707 if (!ast_strlen_zero(reason)) {
11708 ast_cli(a->fd, " for reason '%s'", reason);
11709 }
11710 ast_cli(a->fd, "\n");
11711 return CLI_FAILURE;
11712 }
11713 }
11714
11715 static char *complete_queue_set_member_value(const char *line, const char *word, int pos, int state)
11716 {
11717 /* 0 - queue; 1 - set; 2 - penalty/ringinuse; 3 - <value>; 4 - on; 5 - <member>; 6 - in; 7 - <queue>;*/
11718 switch (pos) {
11719 case 4:
11720 if (state == 0) {
11721 return ast_strdup("on");
11722 } else {
11723 return NULL;
11724 }
11725 case 6:
11726 if (state == 0) {
11727 return ast_strdup("in");
11728 } else {
11729 return NULL;
11730 }
11731 case 7:
11732 return complete_queue(line, word, pos, state, 0);
11733 default:
11734 return NULL;
11735 }
11736 }
11737
11738 static char *handle_queue_set_member_ringinuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
11739 {
11740 const char *queuename = NULL, *interface;
11741 int ringinuse;
11742
11743 switch (cmd) {
11744 case CLI_INIT:
11745 e->command = "queue set ringinuse";
11746 e->usage =
11747 "Usage: queue set ringinuse <yes/no> on <interface> [in <queue>]\n"
11748 " Set a member's ringinuse in the queue specified. If no queue is specified\n"
11749 " then that interface's penalty is set in all queues to which that interface is a member.\n";
11750 break;
11751 return NULL;
11752 case CLI_GENERATE:
11753 return complete_queue_set_member_value(a->line, a->word, a->pos, a->n);
11754 }
11755
11756 /* Sensible argument counts */
11757 if (a->argc != 6 && a->argc != 8) {
11758 return CLI_SHOWUSAGE;
11759 }
11760
11761 /* Uses proper indicational words */
11762 if (strcmp(a->argv[4], "on") || (a->argc > 6 && strcmp(a->argv[6], "in"))) {
11763 return CLI_SHOWUSAGE;
11764 }
11765
11766 /* Set the queue name if applicable */
11767 if (a->argc == 8) {
11768 queuename = a->argv[7];
11769 }
11770
11771 /* Interface being set */
11772 interface = a->argv[5];
11773
11774 /* Check and set the ringinuse value */
11775 if (ast_true(a->argv[3])) {
11776 ringinuse = 1;
11777 } else if (ast_false(a->argv[3])) {
11778 ringinuse = 0;
11779 } else {
11780 return CLI_SHOWUSAGE;
11781 }
11782
11783 switch (set_member_value(queuename, interface, MEMBER_RINGINUSE, ringinuse)) {
11784 case RESULT_SUCCESS:
11785 ast_cli(a->fd, "Set ringinuse on interface '%s' from queue '%s'\n", interface, queuename);
11786 return CLI_SUCCESS;
11787 case RESULT_FAILURE:
11788 ast_cli(a->fd, "Failed to set ringinuse on interface '%s' from queue '%s'\n", interface, queuename);
11789 return CLI_FAILURE;
11790 default:
11791 return CLI_FAILURE;
11792 }
11793 }
11794
11795 static char *handle_queue_set_member_penalty(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
11796 {
11797 const char *queuename = NULL, *interface;
11798 int penalty = 0;
11799
11800 switch (cmd) {
11801 case CLI_INIT:
11802 e->command = "queue set penalty";
11803 e->usage =
11804 "Usage: queue set penalty <penalty> on <interface> [in <queue>]\n"
11805 " Set a member's penalty in the queue specified. If no queue is specified\n"
11806 " then that interface's penalty is set in all queues to which that interface is a member\n";
11807 return NULL;
11808 case CLI_GENERATE:
11809 return complete_queue_set_member_value(a->line, a->word, a->pos, a->n);
11810 }
11811
11812 if (a->argc != 6 && a->argc != 8) {
11813 return CLI_SHOWUSAGE;
11814 } else if (strcmp(a->argv[4], "on") || (a->argc > 6 && strcmp(a->argv[6], "in"))) {
11815 return CLI_SHOWUSAGE;
11816 }
11817
11818 if (a->argc == 8) {
11819 queuename = a->argv[7];
11820 }
11821 interface = a->argv[5];
11822 penalty = atoi(a->argv[3]);
11823
11824 switch (set_member_value(queuename, interface, MEMBER_PENALTY, penalty)) {
11825 case RESULT_SUCCESS:
11826 ast_cli(a->fd, "Set penalty on interface '%s' from queue '%s'\n", interface, queuename);
11827 return CLI_SUCCESS;
11828 case RESULT_FAILURE:
11829 ast_cli(a->fd, "Failed to set penalty on interface '%s' from queue '%s'\n", interface, queuename);
11830 return CLI_FAILURE;
11831 default:
11832 return CLI_FAILURE;
11833 }
11834 }
11835
11836 static char *complete_queue_rule_show(const char *line, const char *word, int pos, int state)
11837 {
11838 int which = 0;
11839 struct rule_list *rl_iter;
11840 int wordlen = strlen(word);
11841 char *ret = NULL;
11842 if (pos != 3) /* Wha? */ {
11843 return NULL;
11844 }
11845
11846 AST_LIST_LOCK(&rule_lists);
11847 AST_LIST_TRAVERSE(&rule_lists, rl_iter, list) {
11848 if (!strncasecmp(word, rl_iter->name, wordlen) && ++which > state) {
11849 ret = ast_strdup(rl_iter->name);
11850 break;
11851 }
11852 }
11853 AST_LIST_UNLOCK(&rule_lists);
11854
11855 return ret;
11856 }
11857
11858 static char *handle_queue_rule_show(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
11859 {
11860 const char *rule;
11861 struct rule_list *rl_iter;
11862 struct penalty_rule *pr_iter;
11863 switch (cmd) {
11864 case CLI_INIT:
11865 e->command = "queue show rules";
11866 e->usage =
11867 "Usage: queue show rules [rulename]\n"
11868 " Show the list of rules associated with rulename. If no\n"
11869 " rulename is specified, list all rules defined in queuerules.conf\n";
11870 return NULL;
11871 case CLI_GENERATE:
11872 return complete_queue_rule_show(a->line, a->word, a->pos, a->n);
11873 }
11874
11875 if (a->argc != 3 && a->argc != 4) {
11876 return CLI_SHOWUSAGE;
11877 }
11878
11879 rule = a->argc == 4 ? a->argv[3] : "";
11880 AST_LIST_LOCK(&rule_lists);
11881 AST_LIST_TRAVERSE(&rule_lists, rl_iter, list) {
11882 if (ast_strlen_zero(rule) || !strcasecmp(rl_iter->name, rule)) {
11883 ast_cli(a->fd, "Rule: %s\n", rl_iter->name);
11884 AST_LIST_TRAVERSE(&rl_iter->rules, pr_iter, list) {
11885 ast_cli(a->fd, "\tAfter %d seconds, adjust QUEUE_MAX_PENALTY %s %d, adjust QUEUE_MIN_PENALTY %s %d and adjust QUEUE_RAISE_PENALTY %s %d\n", pr_iter->time, pr_iter->max_relative ? "by" : "to", pr_iter->max_value, pr_iter->min_relative ? "by" : "to", pr_iter->min_value, pr_iter->raise_relative ? "by" : "to", pr_iter->raise_value);
11886 }
11887 }
11888 }
11889 AST_LIST_UNLOCK(&rule_lists);
11890 return CLI_SUCCESS;
11891 }
11892
11893 static char *handle_queue_reset(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
11894 {
11895 struct ast_flags mask = {QUEUE_RESET_STATS,};
11896 int i;
11897
11898 switch (cmd) {
11899 case CLI_INIT:
11900 e->command = "queue reset stats";
11901 e->usage =
11902 "Usage: queue reset stats [<queuenames>]\n"
11903 "\n"
11904 "Issuing this command will reset statistics for\n"
11905 "<queuenames>, or for all queues if no queue is\n"
11906 "specified.\n";
11907 return NULL;
11908 case CLI_GENERATE:
11909 if (a->pos >= 3) {
11910 return complete_queue(a->line, a->word, a->pos, a->n, 17);
11911 } else {
11912 return NULL;
11913 }
11914 }
11915
11916 if (a->argc < 3) {
11917 return CLI_SHOWUSAGE;
11918 }
11919
11920 if (a->argc == 3) {
11921 reload_handler(1, &mask, NULL);
11922 return CLI_SUCCESS;
11923 }
11924
11925 for (i = 3; i < a->argc; ++i) {
11926 reload_handler(1, &mask, a->argv[i]);
11927 }
11928
11929 return CLI_SUCCESS;
11930 }
11931
11932 static char *handle_queue_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
11933 {
11934 struct ast_flags mask = {0,};
11935 int i;
11936
11937 switch (cmd) {
11938 case CLI_INIT:
11939 e->command = "queue reload {parameters|members|rules|all}";
11940 e->usage =
11941 "Usage: queue reload {parameters|members|rules|all} [<queuenames>]\n"
11942 "Reload queues. If <queuenames> are specified, only reload information pertaining\n"
11943 "to <queuenames>. One of 'parameters,' 'members,' 'rules,' or 'all' must be\n"
11944 "specified in order to know what information to reload. Below is an explanation\n"
11945 "of each of these qualifiers.\n"
11946 "\n"
11947 "\t'members' - reload queue members from queues.conf\n"
11948 "\t'parameters' - reload all queue options except for queue members\n"
11949 "\t'rules' - reload the queuerules.conf file\n"
11950 "\t'all' - reload queue rules, parameters, and members\n"
11951 "\n"
11952 "Note: the 'rules' qualifier here cannot actually be applied to a specific queue.\n"
11953 "Use of the 'rules' qualifier causes queuerules.conf to be reloaded. Even if only\n"
11954 "one queue is specified when using this command, reloading queue rules may cause\n"
11955 "other queues to be affected\n";
11956 return NULL;
11957 case CLI_GENERATE:
11958 if (a->pos >= 3) {
11959 /* find the point at which the list of queue names starts */
11960 const char *command_end = a->line + strlen("queue reload ");
11961 command_end = strchr(command_end, ' ');
11962 if (!command_end) {
11963 command_end = a->line + strlen(a->line);
11964 }
11965 return complete_queue(a->line, a->word, a->pos, a->n, command_end - a->line);
11966 } else {
11967 return NULL;
11968 }
11969 }
11970
11971 if (a->argc < 3)
11972 return CLI_SHOWUSAGE;
11973
11974 if (!strcasecmp(a->argv[2], "rules")) {
11975 ast_set_flag(&mask, QUEUE_RELOAD_RULES);
11976 } else if (!strcasecmp(a->argv[2], "members")) {
11977 ast_set_flag(&mask, QUEUE_RELOAD_MEMBER);
11978 } else if (!strcasecmp(a->argv[2], "parameters")) {
11979 ast_set_flag(&mask, QUEUE_RELOAD_PARAMETERS);
11980 } else if (!strcasecmp(a->argv[2], "all")) {
11981 ast_set_flag(&mask, AST_FLAGS_ALL & ~QUEUE_RESET_STATS);
11982 }
11983
11984 if (a->argc == 3) {
11985 reload_handler(1, &mask, NULL);
11986 return CLI_SUCCESS;
11987 }
11988
11989 for (i = 3; i < a->argc; ++i) {
11990 reload_handler(1, &mask, a->argv[i]);
11991 }
11992
11993 return CLI_SUCCESS;
11994 }
11995
11996 /*!
11997 * \brief Update Queue with data of an outgoing call
11998 */
11999 static int qupd_exec(struct ast_channel *chan, const char *data)
12000 {
12001 int oldtalktime;
12002 char *parse;
12003 struct call_queue *q;
12004 struct member *mem;
12005 int newtalktime = 0;
12006
12007 AST_DECLARE_APP_ARGS(args,
12008 AST_APP_ARG(queuename);
12009 AST_APP_ARG(uniqueid);
12010 AST_APP_ARG(agent);
12011 AST_APP_ARG(status);
12012 AST_APP_ARG(talktime);
12013 AST_APP_ARG(params););
12014
12015 if (ast_strlen_zero(data)) {
12016 ast_log(LOG_WARNING, "QueueUpdate requires arguments (queuename,uniqueid,agent,status,talktime,params[totaltime,callednumber])\n");
12017 return -1;
12018 }
12019
12020 parse = ast_strdupa(data);
12021
12022 AST_STANDARD_APP_ARGS(args, parse);
12023
12024 if (ast_strlen_zero(args.queuename) || ast_strlen_zero(args.uniqueid) || ast_strlen_zero(args.agent) || ast_strlen_zero(args.status)) {
12025 ast_log(LOG_WARNING, "Missing argument to QueueUpdate (queuename,uniqueid,agent,status,talktime,params[totaltime|callednumber])\n");
12026 return -1;
12027 }
12028
12029 if (!ast_strlen_zero(args.talktime)) {
12030 newtalktime = atoi(args.talktime);
12031 }
12032
12033 q = find_load_queue_rt_friendly(args.queuename);
12034 if (!q) {
12035 ast_log(LOG_WARNING, "QueueUpdate could not find requested queue '%s'\n", args.queuename);
12036 return 0;
12037 }
12038
12039 ao2_lock(q);
12040 if (q->members) {
12041 struct ao2_iterator mem_iter = ao2_iterator_init(q->members, 0);
12042 while ((mem = ao2_iterator_next(&mem_iter))) {
12043 if (!strcasecmp(mem->membername, args.agent)) {
12044 if (!strcasecmp(args.status, "ANSWER")) {
12045 oldtalktime = q->talktime;
12046 q->talktime = (((oldtalktime << 2) - oldtalktime) + newtalktime) >> 2;
12047 time(&mem->lastcall);
12048 mem->calls++;
12049 mem->lastqueue = q;
12050 q->callscompleted++;
12051
12052 if (newtalktime <= q->servicelevel) {
12053 q->callscompletedinsl++;
12054 }
12055 } else {
12056
12057 time(&mem->lastcall);
12058 q->callsabandoned++;
12059 }
12060
12061 ast_queue_log(args.queuename, args.uniqueid, args.agent, "OUTCALL", "%s|%s|%s", args.status, args.talktime, args.params);
12062 }
12063
12064 ao2_ref(mem, -1);
12065 }
12066
12067 ao2_iterator_destroy(&mem_iter);
12068 }
12069
12070 ao2_unlock(q);
12071 queue_t_unref(q, "Done with temporary pointer");
12072
12073 return 0;
12074 }
12075
12076 static struct ast_cli_entry cli_queue[] = {
12077 AST_CLI_DEFINE(queue_show, "Show status of a specified queue"),
12078 AST_CLI_DEFINE(handle_queue_rule_show, "Show the rules defined in queuerules.conf"),
12079 AST_CLI_DEFINE(handle_queue_add_member, "Add a channel to a specified queue"),
12080 AST_CLI_DEFINE(handle_queue_remove_member, "Removes a channel from a specified queue"),
12081 AST_CLI_DEFINE(handle_queue_pause_member, "Pause or unpause a queue member"),
12082 AST_CLI_DEFINE(handle_queue_set_member_penalty, "Set penalty for a channel of a specified queue"),
12083 AST_CLI_DEFINE(handle_queue_set_member_ringinuse, "Set ringinuse for a channel of a specified queue"),
12084 AST_CLI_DEFINE(handle_queue_reload, "Reload queues, members, queue rules, or parameters"),
12085 AST_CLI_DEFINE(handle_queue_reset, "Reset statistics for a queue"),
12086 AST_CLI_DEFINE(handle_queue_change_priority_caller, "Change priority caller on queue"),
12087 };
12088
12089 static struct stasis_message_router *agent_router;
12090 static struct stasis_forward *topic_forwarder;
12091
12092 static int unload_module(void)
12093 {
12094 stasis_message_router_unsubscribe_and_join(agent_router);
12095 agent_router = NULL;
12096
12097 topic_forwarder = stasis_forward_cancel(topic_forwarder);
12098
12099 STASIS_MESSAGE_TYPE_CLEANUP(queue_caller_join_type);
12100 STASIS_MESSAGE_TYPE_CLEANUP(queue_caller_leave_type);
12101 STASIS_MESSAGE_TYPE_CLEANUP(queue_caller_abandon_type);
12102
12103 STASIS_MESSAGE_TYPE_CLEANUP(queue_member_status_type);
12104 STASIS_MESSAGE_TYPE_CLEANUP(queue_member_added_type);
12105 STASIS_MESSAGE_TYPE_CLEANUP(queue_member_removed_type);
12106 STASIS_MESSAGE_TYPE_CLEANUP(queue_member_pause_type);
12107 STASIS_MESSAGE_TYPE_CLEANUP(queue_member_penalty_type);
12108 STASIS_MESSAGE_TYPE_CLEANUP(queue_member_ringinuse_type);
12109
12110 STASIS_MESSAGE_TYPE_CLEANUP(queue_agent_called_type);
12111 STASIS_MESSAGE_TYPE_CLEANUP(queue_agent_connect_type);
12112 STASIS_MESSAGE_TYPE_CLEANUP(queue_agent_complete_type);
12113 STASIS_MESSAGE_TYPE_CLEANUP(queue_agent_dump_type);
12114 STASIS_MESSAGE_TYPE_CLEANUP(queue_agent_ringnoanswer_type);
12115
12116 ast_cli_unregister_multiple(cli_queue, ARRAY_LEN(cli_queue));
12117 ast_manager_unregister("QueueStatus");
12118 ast_manager_unregister("QueueRule");
12119 ast_manager_unregister("QueueSummary");
12120 ast_manager_unregister("QueueAdd");
12121 ast_manager_unregister("QueueRemove");
12122 ast_manager_unregister("QueuePause");
12123 ast_manager_unregister("QueueLog");
12124 ast_manager_unregister("QueueUpdate");
12125 ast_manager_unregister("QueuePenalty");
12126 ast_manager_unregister("QueueReload");
12127 ast_manager_unregister("QueueReset");
12128 ast_manager_unregister("QueueMemberRingInUse");
12129 ast_manager_unregister("QueueChangePriorityCaller");
12130 ast_manager_unregister("QueueWithdrawCaller");
12131 ast_unregister_application(app_aqm);
12132 ast_unregister_application(app_rqm);
12133 ast_unregister_application(app_pqm);
12134 ast_unregister_application(app_upqm);
12135 ast_unregister_application(app_ql);
12136 ast_unregister_application(app_qupd);
12137 ast_unregister_application(app);
12138 ast_custom_function_unregister(&queueexists_function);
12139 ast_custom_function_unregister(&queuevar_function);
12140 ast_custom_function_unregister(&queuemembercount_function);
12141 ast_custom_function_unregister(&queuemembercount_dep);
12142 ast_custom_function_unregister(&queuememberlist_function);
12143 ast_custom_function_unregister(&queuegetchannel_function);
12144 ast_custom_function_unregister(&queuewaitingcount_function);
12145 ast_custom_function_unregister(&queuememberpenalty_function);
12146
12147 device_state_sub = stasis_unsubscribe_and_join(device_state_sub);
12148
12149 ast_unload_realtime("queue_members");
12150 ao2_cleanup(queues);
12151 ao2_cleanup(pending_members);
12152
12153 queues = NULL;
12154 return 0;
12155 }
12156
12157 /*!
12158 * \brief Load the module
12159 *
12160 * Module loading including tests for configuration or dependencies.
12161 * This function can return AST_MODULE_LOAD_FAILURE, AST_MODULE_LOAD_DECLINE,
12162 * or AST_MODULE_LOAD_SUCCESS. If a dependency or environment variable fails
12163 * tests return AST_MODULE_LOAD_FAILURE. If the module can not load the
12164 * configuration file or other non-critical problem return
12165 * AST_MODULE_LOAD_DECLINE. On success return AST_MODULE_LOAD_SUCCESS.
12166 */
12167 static int load_module(void)
12168 {
12169 int err = 0;
12170 struct ast_flags mask = {AST_FLAGS_ALL, };
12171 struct ast_config *member_config;
12172 struct stasis_topic *queue_topic;
12173 struct stasis_topic *manager_topic;
12174
12175 queues = ao2_container_alloc_hash(AO2_ALLOC_OPT_LOCK_MUTEX, 0, MAX_QUEUE_BUCKETS,
12176 queue_hash_cb, NULL, queue_cmp_cb);
12177 if (!queues) {
12178 return AST_MODULE_LOAD_DECLINE;
12179 }
12180
12181 pending_members = ao2_container_alloc_hash(AO2_ALLOC_OPT_LOCK_MUTEX, 0,
12182 MAX_CALL_ATTEMPT_BUCKETS, pending_members_hash, NULL, pending_members_cmp);
12183 if (!pending_members) {
12184 unload_module();
12185 return AST_MODULE_LOAD_DECLINE;
12186 }
12187
12188 use_weight = 0;
12189
12190 if (reload_handler(0, &mask, NULL)) {
12191 unload_module();
12192 return AST_MODULE_LOAD_DECLINE;
12193 }
12194
12195 ast_realtime_require_field("queue_members", "paused", RQ_INTEGER1, 1, "uniqueid", RQ_UINTEGER2, 5, "reason_paused", RQ_CHAR, 80, SENTINEL);
12196
12197 /*
12198 * This section is used to determine which name for 'ringinuse' to use in realtime members
12199 * Necessary for supporting older setups.
12200 *
12201 * It also checks if 'reason_paused' exists in the realtime backend
12202 */
12203 member_config = ast_load_realtime_multientry("queue_members", "interface LIKE", "%", "queue_name LIKE", "%", SENTINEL);
12204 if (!member_config) {
12205 realtime_ringinuse_field = "ringinuse";
12206 } else {
12207 const char *config_val;
12208
12209 if ((config_val = ast_variable_retrieve(member_config, NULL, "ringinuse"))) {
12210 ast_log(LOG_NOTICE, "ringinuse field entries found in queue_members table. Using 'ringinuse'\n");
12211 realtime_ringinuse_field = "ringinuse";
12212 } else if ((config_val = ast_variable_retrieve(member_config, NULL, "ignorebusy"))) {
12213 ast_log(LOG_NOTICE, "ignorebusy field found in queue_members table with no ringinuse field. Using 'ignorebusy'\n");
12214 realtime_ringinuse_field = "ignorebusy";
12215 } else {
12216 ast_log(LOG_NOTICE, "No entries were found for ringinuse/ignorebusy in queue_members table. Using 'ringinuse'\n");
12217 realtime_ringinuse_field = "ringinuse";
12218 }
12219
12220 if (ast_variable_retrieve(member_config, NULL, "reason_paused")) {
12221 realtime_reason_paused = 1;
12222 }
12223 }
12224 ast_config_destroy(member_config);
12225
12226 if (queue_persistent_members) {
12227 reload_queue_members();
12228 }
12229
12230 err |= ast_cli_register_multiple(cli_queue, ARRAY_LEN(cli_queue));
12231 err |= ast_register_application_xml(app, queue_exec);
12232 err |= ast_register_application_xml(app_aqm, aqm_exec);
12233 err |= ast_register_application_xml(app_rqm, rqm_exec);
12234 err |= ast_register_application_xml(app_pqm, pqm_exec);
12235 err |= ast_register_application_xml(app_upqm, upqm_exec);
12236 err |= ast_register_application_xml(app_ql, ql_exec);
12237 err |= ast_register_application_xml(app_qupd, qupd_exec);
12238 err |= ast_manager_register_xml("QueueStatus", 0, manager_queues_status);
12239 err |= ast_manager_register_xml("QueueSummary", 0, manager_queues_summary);
12240 err |= ast_manager_register_xml("QueueAdd", EVENT_FLAG_AGENT, manager_add_queue_member);
12241 err |= ast_manager_register_xml("QueueRemove", EVENT_FLAG_AGENT, manager_remove_queue_member);
12242 err |= ast_manager_register_xml("QueuePause", EVENT_FLAG_AGENT, manager_pause_queue_member);
12243 err |= ast_manager_register_xml("QueueLog", EVENT_FLAG_AGENT, manager_queue_log_custom);
12244 err |= ast_manager_register_xml("QueuePenalty", EVENT_FLAG_AGENT, manager_queue_member_penalty);
12245 err |= ast_manager_register_xml("QueueMemberRingInUse", EVENT_FLAG_AGENT, manager_queue_member_ringinuse);
12246 err |= ast_manager_register_xml("QueueRule", 0, manager_queue_rule_show);
12247 err |= ast_manager_register_xml("QueueReload", 0, manager_queue_reload);
12248 err |= ast_manager_register_xml("QueueReset", 0, manager_queue_reset);
12249 err |= ast_manager_register_xml("QueueChangePriorityCaller", 0, manager_change_priority_caller_on_queue);
12250 err |= ast_manager_register_xml("QueueWithdrawCaller", 0, manager_request_withdraw_caller_from_queue);
12251 err |= ast_custom_function_register(&queuevar_function);
12252 err |= ast_custom_function_register(&queueexists_function);
12253 err |= ast_custom_function_register(&queuemembercount_function);
12254 err |= ast_custom_function_register(&queuemembercount_dep);
12255 err |= ast_custom_function_register(&queuememberlist_function);
12256 err |= ast_custom_function_register(&queuegetchannel_function);
12257 err |= ast_custom_function_register(&queuewaitingcount_function);
12258 err |= ast_custom_function_register(&queuememberpenalty_function);
12259
12260 /* in the following subscribe call, do I use DEVICE_STATE, or DEVICE_STATE_CHANGE? */
12261 device_state_sub = stasis_subscribe(ast_device_state_topic_all(), device_state_cb, NULL);
12262 if (!device_state_sub) {
12263 err = -1;
12264 }
12265 stasis_subscription_accept_message_type(device_state_sub, ast_device_state_message_type());
12266 stasis_subscription_set_filter(device_state_sub, STASIS_SUBSCRIPTION_FILTER_SELECTIVE);
12267
12268 manager_topic = ast_manager_get_topic();
12269 queue_topic = ast_queue_topic_all();
12270 if (!manager_topic || !queue_topic) {
12271 unload_module();
12272 return AST_MODULE_LOAD_DECLINE;
12273 }
12274 topic_forwarder = stasis_forward_all(queue_topic, manager_topic);
12275 if (!topic_forwarder) {
12276 unload_module();
12277 return AST_MODULE_LOAD_DECLINE;
12278 }
12279
12280 if (!ast_channel_agent_login_type()
12281 || !ast_channel_agent_logoff_type()) {
12282 unload_module();
12283 return AST_MODULE_LOAD_DECLINE;
12284 }
12285 agent_router = stasis_message_router_create(ast_channel_topic_all());
12286 if (!agent_router) {
12287 unload_module();
12288 return AST_MODULE_LOAD_DECLINE;
12289 }
12290 err |= stasis_message_router_add(agent_router,
12291 ast_channel_agent_login_type(),
12292 queue_agent_cb,
12293 NULL);
12294 err |= stasis_message_router_add(agent_router,
12295 ast_channel_agent_logoff_type(),
12296 queue_agent_cb,
12297 NULL);
12298
12299 err |= STASIS_MESSAGE_TYPE_INIT(queue_caller_join_type);
12300 err |= STASIS_MESSAGE_TYPE_INIT(queue_caller_leave_type);
12301 err |= STASIS_MESSAGE_TYPE_INIT(queue_caller_abandon_type);
12302
12303 err |= STASIS_MESSAGE_TYPE_INIT(queue_member_status_type);
12304 err |= STASIS_MESSAGE_TYPE_INIT(queue_member_added_type);
12305 err |= STASIS_MESSAGE_TYPE_INIT(queue_member_removed_type);
12306 err |= STASIS_MESSAGE_TYPE_INIT(queue_member_pause_type);
12307 err |= STASIS_MESSAGE_TYPE_INIT(queue_member_penalty_type);
12308 err |= STASIS_MESSAGE_TYPE_INIT(queue_member_ringinuse_type);
12309
12310 err |= STASIS_MESSAGE_TYPE_INIT(queue_agent_called_type);
12311 err |= STASIS_MESSAGE_TYPE_INIT(queue_agent_connect_type);
12312 err |= STASIS_MESSAGE_TYPE_INIT(queue_agent_complete_type);
12313 err |= STASIS_MESSAGE_TYPE_INIT(queue_agent_dump_type);
12314 err |= STASIS_MESSAGE_TYPE_INIT(queue_agent_ringnoanswer_type);
12315
12316 if (err) {
12317 unload_module();
12318 return AST_MODULE_LOAD_DECLINE;
12319 }
12320 return AST_MODULE_LOAD_SUCCESS;
12321 }
12322
12323 static int reload(void)
12324 {
12325 struct ast_flags mask = {AST_FLAGS_ALL & ~QUEUE_RESET_STATS,};
12326 ast_unload_realtime("queue_members");
12327 reload_handler(1, &mask, NULL);
12328 return 0;
12329 }
12330
12331 /*!
12332 * \brief Find a member by looking up queuename and interface.
12333 * \return member or NULL if member not found.
12334 */
12335 static struct member *find_member_by_queuename_and_interface(const char *queuename, const char *interface)
12336 {
12337 struct member *mem = NULL;
12338 struct call_queue *q;
12339
12340 if ((q = find_load_queue_rt_friendly(queuename))) {
12341 ao2_lock(q);
12342 mem = ao2_find(q->members, interface, OBJ_KEY);
12343 ao2_unlock(q);
12344 queue_t_unref(q, "Expiring temporary reference.");
12345 }
12346 return mem;
12347 }
12348
12349 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "True Call Queueing",
12350 .support_level = AST_MODULE_SUPPORT_CORE,
12351 .load = load_module,
12352 .unload = unload_module,
12353 .reload = reload,
12354 .load_pri = AST_MODPRI_DEVSTATE_CONSUMER,
12355 );