Fri Jan 18 19:57:05 2013

Asterisk developer's documentation


app_queue.c

Go to the documentation of this file.
00001 /*
00002  * Asterisk -- An open source telephony toolkit.
00003  *
00004  * Copyright (C) 1999 - 2006, Digium, Inc.
00005  *
00006  * Mark Spencer <markster@digium.com>
00007  *
00008  * See http://www.asterisk.org for more information about
00009  * the Asterisk project. Please do not directly contact
00010  * any of the maintainers of this project for assistance;
00011  * the project provides a web site, mailing lists and IRC
00012  * channels for your use.
00013  *
00014  * This program is free software, distributed under the terms of
00015  * the GNU General Public License Version 2. See the LICENSE file
00016  * at the top of the source tree.
00017  */
00018 
00019 /*! \file
00020  *
00021  * \brief True call queues with optional send URL on answer
00022  *
00023  * \author Mark Spencer <markster@digium.com>
00024  *
00025  * \arg Config in \ref Config_qu queues.conf
00026  *
00027  * \par Development notes
00028  * \note 2004-11-25: Persistent Dynamic Members added by:
00029  *             NetNation Communications (www.netnation.com)
00030  *             Kevin Lindsay <kevinl@netnation.com>
00031  *
00032  *             Each dynamic agent in each queue is now stored in the astdb.
00033  *             When asterisk is restarted, each agent will be automatically
00034  *             readded into their recorded queues. This feature can be
00035  *             configured with the 'persistent_members=<1|0>' setting in the
00036  *             '[general]' category in queues.conf. The default is on.
00037  *
00038  * \note 2004-06-04: Priorities in queues added by inAccess Networks (work funded by Hellas On Line (HOL) www.hol.gr).
00039  *
00040  * \note These features added by David C. Troy <dave@toad.net>:
00041  *    - Per-queue holdtime calculation
00042  *    - Estimated holdtime announcement
00043  *    - Position announcement
00044  *    - Abandoned/completed call counters
00045  *    - Failout timer passed as optional app parameter
00046  *    - Optional monitoring of calls, started when call is answered
00047  *
00048  * Patch Version 1.07 2003-12-24 01
00049  *
00050  * Added servicelevel statistic by Michiel Betel <michiel@betel.nl>
00051  * Added Priority jumping code for adding and removing queue members by Jonathan Stanton <asterisk@doilooklikeicare.com>
00052  *
00053  * Fixed to work with CVS as of 2004-02-25 and released as 1.07a
00054  * by Matthew Enger <m.enger@xi.com.au>
00055  *
00056  * \ingroup applications
00057  */
00058 
00059 /*** MODULEINFO
00060    <use>res_monitor</use>
00061    <support_level>core</support_level>
00062  ***/
00063 
00064 #include "asterisk.h"
00065 
00066 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 378781 $")
00067 
00068 #include <sys/time.h>
00069 #include <sys/signal.h>
00070 #include <netinet/in.h>
00071 #include <ctype.h>
00072 
00073 #include "asterisk/lock.h"
00074 #include "asterisk/file.h"
00075 #include "asterisk/channel.h"
00076 #include "asterisk/pbx.h"
00077 #include "asterisk/app.h"
00078 #include "asterisk/linkedlists.h"
00079 #include "asterisk/module.h"
00080 #include "asterisk/translate.h"
00081 #include "asterisk/say.h"
00082 #include "asterisk/features.h"
00083 #include "asterisk/musiconhold.h"
00084 #include "asterisk/cli.h"
00085 #include "asterisk/manager.h"
00086 #include "asterisk/config.h"
00087 #include "asterisk/monitor.h"
00088 #include "asterisk/utils.h"
00089 #include "asterisk/causes.h"
00090 #include "asterisk/astdb.h"
00091 #include "asterisk/devicestate.h"
00092 #include "asterisk/stringfields.h"
00093 #include "asterisk/event.h"
00094 #include "asterisk/astobj2.h"
00095 #include "asterisk/strings.h"
00096 #include "asterisk/global_datastores.h"
00097 #include "asterisk/taskprocessor.h"
00098 #include "asterisk/aoc.h"
00099 #include "asterisk/callerid.h"
00100 #include "asterisk/cel.h"
00101 #include "asterisk/data.h"
00102 
00103 /* Define, to debug reference counts on queues, without debugging reference counts on queue members */
00104 /* #define REF_DEBUG_ONLY_QUEUES */
00105 
00106 /*!
00107  * \par Please read before modifying this file.
00108  * There are three locks which are regularly used
00109  * throughout this file, the queue list lock, the lock
00110  * for each individual queue, and the interface list lock.
00111  * Please be extra careful to always lock in the following order
00112  * 1) queue list lock
00113  * 2) individual queue lock
00114  * 3) interface list lock
00115  * This order has sort of "evolved" over the lifetime of this
00116  * application, but it is now in place this way, so please adhere
00117  * to this order!
00118  */
00119 
00120 /*** DOCUMENTATION
00121    <application name="Queue" language="en_US">
00122       <synopsis>
00123          Queue a call for a call queue.
00124       </synopsis>
00125       <syntax>
00126          <parameter name="queuename" required="true" />
00127          <parameter name="options">
00128             <optionlist>
00129                <option name="C">
00130                   <para>Mark all calls as "answered elsewhere" when cancelled.</para>
00131                </option>
00132                <option name="c">
00133                   <para>Continue in the dialplan if the callee hangs up.</para>
00134                </option>
00135                <option name="d">
00136                   <para>data-quality (modem) call (minimum delay).</para>
00137                </option>
00138                <option name="h">
00139                   <para>Allow <emphasis>callee</emphasis> to hang up by pressing <literal>*</literal>.</para>
00140                </option>
00141                <option name="H">
00142                   <para>Allow <emphasis>caller</emphasis> to hang up by pressing <literal>*</literal>.</para>
00143                </option>
00144                <option name="n">
00145                   <para>No retries on the timeout; will exit this application and
00146                   go to the next step.</para>
00147                </option>
00148                <option name="i">
00149                   <para>Ignore call forward requests from queue members and do nothing
00150                   when they are requested.</para>
00151                </option>
00152                <option name="I">
00153                   <para>Asterisk will ignore any connected line update requests or any redirecting party
00154                   update requests it may receive on this dial attempt.</para>
00155                </option>
00156                <option name="r">
00157                   <para>Ring instead of playing MOH. Periodic Announcements are still made, if applicable.</para>
00158                </option>
00159                <option name="R">
00160                   <para>Ring instead of playing MOH when a member channel is actually ringing.</para>
00161                </option>
00162                <option name="t">
00163                   <para>Allow the <emphasis>called</emphasis> user to transfer the calling user.</para>
00164                </option>
00165                <option name="T">
00166                   <para>Allow the <emphasis>calling</emphasis> user to transfer the call.</para>
00167                </option>
00168                <option name="w">
00169                   <para>Allow the <emphasis>called</emphasis> user to write the conversation to
00170                   disk via Monitor.</para>
00171                </option>
00172                <option name="W">
00173                   <para>Allow the <emphasis>calling</emphasis> user to write the conversation to
00174                   disk via Monitor.</para>
00175                </option>
00176                <option name="k">
00177                   <para>Allow the <emphasis>called</emphasis> party to enable parking of the call by sending
00178                   the DTMF sequence defined for call parking in <filename>features.conf</filename>.</para>
00179                </option>
00180                <option name="K">
00181                   <para>Allow the <emphasis>calling</emphasis> party to enable parking of the call by sending
00182                   the DTMF sequence defined for call parking in <filename>features.conf</filename>.</para>
00183                </option>
00184                <option name="x">
00185                   <para>Allow the <emphasis>called</emphasis> user to write the conversation
00186                   to disk via MixMonitor.</para>
00187                </option>
00188                <option name="X">
00189                   <para>Allow the <emphasis>calling</emphasis> user to write the conversation to
00190                   disk via MixMonitor.</para>
00191                </option>
00192             </optionlist>
00193          </parameter>
00194          <parameter name="URL">
00195             <para><replaceable>URL</replaceable> will be sent to the called party if the channel supports it.</para>
00196          </parameter>
00197          <parameter name="announceoverride" />
00198          <parameter name="timeout">
00199             <para>Will cause the queue to fail out after a specified number of
00200             seconds, checked between each <filename>queues.conf</filename> <replaceable>timeout</replaceable> and
00201             <replaceable>retry</replaceable> cycle.</para>
00202          </parameter>
00203          <parameter name="AGI">
00204             <para>Will setup an AGI script to be executed on the calling party's channel once they are
00205             connected to a queue member.</para>
00206          </parameter>
00207          <parameter name="macro">
00208             <para>Will run a macro on the calling party's channel once they are connected to a queue member.</para>
00209          </parameter>
00210          <parameter name="gosub">
00211             <para>Will run a gosub on the calling party's channel once they are connected to a queue member.</para>
00212          </parameter>
00213          <parameter name="rule">
00214             <para>Will cause the queue's defaultrule to be overridden by the rule specified.</para>
00215          </parameter>
00216          <parameter name="position">
00217             <para>Attempt to enter the caller into the queue at the numerical position specified. <literal>1</literal>
00218             would attempt to enter the caller at the head of the queue, and <literal>3</literal> would attempt to place
00219             the caller third in the queue.</para>
00220          </parameter>
00221       </syntax>
00222       <description>
00223          <para>In addition to transferring the call, a call may be parked and then picked
00224          up by another user.</para>
00225          <para>This application will return to the dialplan if the queue does not exist, or
00226          any of the join options cause the caller to not enter the queue.</para>
00227          <para>This application does not automatically answer and should be preceeded
00228          by an application such as Answer(), Progress(), or Ringing().</para>
00229          <para>This application sets the following channel variable upon completion:</para>
00230          <variablelist>
00231             <variable name="QUEUESTATUS">
00232                <para>The status of the call as a text string.</para>
00233                <value name="TIMEOUT" />
00234                <value name="FULL" />
00235                <value name="JOINEMPTY" />
00236                <value name="LEAVEEMPTY" />
00237                <value name="JOINUNAVAIL" />
00238                <value name="LEAVEUNAVAIL" />
00239                <value name="CONTINUE" />
00240             </variable>
00241          </variablelist>
00242       </description>
00243       <see-also>
00244          <ref type="application">Queue</ref>
00245          <ref type="application">QueueLog</ref>
00246          <ref type="application">AddQueueMember</ref>
00247          <ref type="application">RemoveQueueMember</ref>
00248          <ref type="application">PauseQueueMember</ref>
00249          <ref type="application">UnpauseQueueMember</ref>
00250          <ref type="function">QUEUE_VARIABLES</ref>
00251          <ref type="function">QUEUE_MEMBER</ref>
00252          <ref type="function">QUEUE_MEMBER_COUNT</ref>
00253          <ref type="function">QUEUE_EXISTS</ref>
00254          <ref type="function">QUEUE_WAITING_COUNT</ref>
00255          <ref type="function">QUEUE_MEMBER_LIST</ref>
00256          <ref type="function">QUEUE_MEMBER_PENALTY</ref>
00257       </see-also>
00258    </application>
00259    <application name="AddQueueMember" language="en_US">
00260       <synopsis>
00261          Dynamically adds queue members.
00262       </synopsis>
00263       <syntax>
00264          <parameter name="queuename" required="true" />
00265          <parameter name="interface" />
00266          <parameter name="penalty" />
00267          <parameter name="options" />
00268          <parameter name="membername" />
00269          <parameter name="stateinterface" />
00270       </syntax>
00271       <description>
00272          <para>Dynamically adds interface to an existing queue. If the interface is
00273          already in the queue it will return an error.</para>
00274          <para>This application sets the following channel variable upon completion:</para>
00275          <variablelist>
00276             <variable name="AQMSTATUS">
00277                <para>The status of the attempt to add a queue member as a text string.</para>
00278                <value name="ADDED" />
00279                <value name="MEMBERALREADY" />
00280                <value name="NOSUCHQUEUE" />
00281             </variable>
00282          </variablelist>
00283       </description>
00284       <see-also>
00285          <ref type="application">Queue</ref>
00286          <ref type="application">QueueLog</ref>
00287          <ref type="application">AddQueueMember</ref>
00288          <ref type="application">RemoveQueueMember</ref>
00289          <ref type="application">PauseQueueMember</ref>
00290          <ref type="application">UnpauseQueueMember</ref>
00291          <ref type="function">QUEUE_VARIABLES</ref>
00292          <ref type="function">QUEUE_MEMBER</ref>
00293          <ref type="function">QUEUE_MEMBER_COUNT</ref>
00294          <ref type="function">QUEUE_EXISTS</ref>
00295          <ref type="function">QUEUE_WAITING_COUNT</ref>
00296          <ref type="function">QUEUE_MEMBER_LIST</ref>
00297          <ref type="function">QUEUE_MEMBER_PENALTY</ref>
00298       </see-also>
00299    </application>
00300    <application name="RemoveQueueMember" language="en_US">
00301       <synopsis>
00302          Dynamically removes queue members.
00303       </synopsis>
00304       <syntax>
00305          <parameter name="queuename" required="true" />
00306          <parameter name="interface" />
00307       </syntax>
00308       <description>
00309          <para>If the interface is <emphasis>NOT</emphasis> in the queue it will return an error.</para>
00310          <para>This application sets the following channel variable upon completion:</para>
00311          <variablelist>
00312             <variable name="RQMSTATUS">
00313                <value name="REMOVED" />
00314                <value name="NOTINQUEUE" />
00315                <value name="NOSUCHQUEUE" />
00316                <value name="NOTDYNAMIC" />
00317             </variable>
00318          </variablelist>
00319          <para>Example: RemoveQueueMember(techsupport,SIP/3000)</para>
00320       </description>
00321       <see-also>
00322          <ref type="application">Queue</ref>
00323          <ref type="application">QueueLog</ref>
00324          <ref type="application">AddQueueMember</ref>
00325          <ref type="application">RemoveQueueMember</ref>
00326          <ref type="application">PauseQueueMember</ref>
00327          <ref type="application">UnpauseQueueMember</ref>
00328          <ref type="function">QUEUE_VARIABLES</ref>
00329          <ref type="function">QUEUE_MEMBER</ref>
00330          <ref type="function">QUEUE_MEMBER_COUNT</ref>
00331          <ref type="function">QUEUE_EXISTS</ref>
00332          <ref type="function">QUEUE_WAITING_COUNT</ref>
00333          <ref type="function">QUEUE_MEMBER_LIST</ref>
00334          <ref type="function">QUEUE_MEMBER_PENALTY</ref>
00335       </see-also>
00336    </application>
00337    <application name="PauseQueueMember" language="en_US">
00338       <synopsis>
00339          Pauses a queue member.
00340       </synopsis>
00341       <syntax>
00342          <parameter name="queuename" />
00343          <parameter name="interface" required="true" />
00344          <parameter name="options" />
00345          <parameter name="reason">
00346             <para>Is used to add extra information to the appropriate queue_log entries and manager events.</para>
00347          </parameter>
00348       </syntax>
00349       <description>
00350          <para>Pauses (blocks calls for) a queue member. The given interface will be paused in the given queue.
00351          This prevents any calls from being sent from the queue to the interface until it is
00352          unpaused with UnpauseQueueMember or the manager interface.  If no queuename is given,
00353          the interface is paused in every queue it is a member of. The application will fail if the
00354          interface is not found.</para>
00355          <para>This application sets the following channel variable upon completion:</para>
00356          <variablelist>
00357             <variable name="PQMSTATUS">
00358                <para>The status of the attempt to pause a queue member as a text string.</para>
00359                <value name="PAUSED" />
00360                <value name="NOTFOUND" />
00361             </variable>
00362          </variablelist>
00363          <para>Example: PauseQueueMember(,SIP/3000)</para>
00364       </description>
00365       <see-also>
00366          <ref type="application">Queue</ref>
00367          <ref type="application">QueueLog</ref>
00368          <ref type="application">AddQueueMember</ref>
00369          <ref type="application">RemoveQueueMember</ref>
00370          <ref type="application">PauseQueueMember</ref>
00371          <ref type="application">UnpauseQueueMember</ref>
00372          <ref type="function">QUEUE_VARIABLES</ref>
00373          <ref type="function">QUEUE_MEMBER</ref>
00374          <ref type="function">QUEUE_MEMBER_COUNT</ref>
00375          <ref type="function">QUEUE_EXISTS</ref>
00376          <ref type="function">QUEUE_WAITING_COUNT</ref>
00377          <ref type="function">QUEUE_MEMBER_LIST</ref>
00378          <ref type="function">QUEUE_MEMBER_PENALTY</ref>
00379       </see-also>
00380    </application>
00381    <application name="UnpauseQueueMember" language="en_US">
00382       <synopsis>
00383          Unpauses a queue member.      
00384       </synopsis>
00385       <syntax>
00386          <parameter name="queuename" />
00387          <parameter name="interface" required="true" />
00388          <parameter name="options" />
00389          <parameter name="reason">
00390             <para>Is used to add extra information to the appropriate queue_log entries and manager events.</para>
00391          </parameter>
00392       </syntax>
00393       <description>
00394          <para>Unpauses (resumes calls to) a queue member. This is the counterpart to <literal>PauseQueueMember()</literal>
00395          and operates exactly the same way, except it unpauses instead of pausing the given interface.</para>
00396          <para>This application sets the following channel variable upon completion:</para>
00397          <variablelist>
00398             <variable name="UPQMSTATUS">
00399                <para>The status of the attempt to unpause a queue member as a text string.</para>
00400                <value name="UNPAUSED" />
00401                <value name="NOTFOUND" />
00402             </variable>
00403          </variablelist>
00404          <para>Example: UnpauseQueueMember(,SIP/3000)</para>
00405       </description>
00406       <see-also>
00407          <ref type="application">Queue</ref>
00408          <ref type="application">QueueLog</ref>
00409          <ref type="application">AddQueueMember</ref>
00410          <ref type="application">RemoveQueueMember</ref>
00411          <ref type="application">PauseQueueMember</ref>
00412          <ref type="application">UnpauseQueueMember</ref>
00413          <ref type="function">QUEUE_VARIABLES</ref>
00414          <ref type="function">QUEUE_MEMBER</ref>
00415          <ref type="function">QUEUE_MEMBER_COUNT</ref>
00416          <ref type="function">QUEUE_EXISTS</ref>
00417          <ref type="function">QUEUE_WAITING_COUNT</ref>
00418          <ref type="function">QUEUE_MEMBER_LIST</ref>
00419          <ref type="function">QUEUE_MEMBER_PENALTY</ref>
00420       </see-also>
00421    </application>
00422    <application name="QueueLog" language="en_US">
00423       <synopsis>
00424          Writes to the queue_log file.
00425       </synopsis>
00426       <syntax>
00427          <parameter name="queuename" required="true" />
00428          <parameter name="uniqueid" required="true" />
00429          <parameter name="agent" required="true" />
00430          <parameter name="event" required="true" />
00431          <parameter name="additionalinfo" />
00432       </syntax>
00433       <description>
00434          <para>Allows you to write your own events into the queue log.</para>
00435          <para>Example: QueueLog(101,${UNIQUEID},${AGENT},WENTONBREAK,600)</para>
00436       </description>
00437       <see-also>
00438          <ref type="application">Queue</ref>
00439          <ref type="application">QueueLog</ref>
00440          <ref type="application">AddQueueMember</ref>
00441          <ref type="application">RemoveQueueMember</ref>
00442          <ref type="application">PauseQueueMember</ref>
00443          <ref type="application">UnpauseQueueMember</ref>
00444          <ref type="function">QUEUE_VARIABLES</ref>
00445          <ref type="function">QUEUE_MEMBER</ref>
00446          <ref type="function">QUEUE_MEMBER_COUNT</ref>
00447          <ref type="function">QUEUE_EXISTS</ref>
00448          <ref type="function">QUEUE_WAITING_COUNT</ref>
00449          <ref type="function">QUEUE_MEMBER_LIST</ref>
00450          <ref type="function">QUEUE_MEMBER_PENALTY</ref>
00451       </see-also>
00452    </application>
00453    <function name="QUEUE_VARIABLES" language="en_US">
00454       <synopsis>
00455          Return Queue information in variables.
00456       </synopsis>
00457       <syntax>
00458          <parameter name="queuename" required="true">
00459             <enumlist>
00460                <enum name="QUEUEMAX">
00461                   <para>Maxmimum number of calls allowed.</para>
00462                </enum>
00463                <enum name="QUEUESTRATEGY">
00464                   <para>The strategy of the queue.</para>
00465                </enum>
00466                <enum name="QUEUECALLS">
00467                   <para>Number of calls currently in the queue.</para>
00468                </enum>
00469                <enum name="QUEUEHOLDTIME">
00470                   <para>Current average hold time.</para>
00471                </enum>
00472                <enum name="QUEUECOMPLETED">
00473                   <para>Number of completed calls for the queue.</para>
00474                </enum>
00475                <enum name="QUEUEABANDONED">
00476                   <para>Number of abandoned calls.</para>
00477                </enum>
00478                <enum name="QUEUESRVLEVEL">
00479                   <para>Queue service level.</para>
00480                </enum>
00481                <enum name="QUEUESRVLEVELPERF">
00482                   <para>Current service level performance.</para>
00483                </enum>
00484             </enumlist>
00485          </parameter>
00486       </syntax>
00487       <description>
00488          <para>Makes the following queue variables available.</para>
00489          <para>Returns <literal>0</literal> if queue is found and setqueuevar is defined, <literal>-1</literal> otherwise.</para>
00490       </description>
00491       <see-also>
00492          <ref type="application">Queue</ref>
00493          <ref type="application">QueueLog</ref>
00494          <ref type="application">AddQueueMember</ref>
00495          <ref type="application">RemoveQueueMember</ref>
00496          <ref type="application">PauseQueueMember</ref>
00497          <ref type="application">UnpauseQueueMember</ref>
00498          <ref type="function">QUEUE_VARIABLES</ref>
00499          <ref type="function">QUEUE_MEMBER</ref>
00500          <ref type="function">QUEUE_MEMBER_COUNT</ref>
00501          <ref type="function">QUEUE_EXISTS</ref>
00502          <ref type="function">QUEUE_WAITING_COUNT</ref>
00503          <ref type="function">QUEUE_MEMBER_LIST</ref>
00504          <ref type="function">QUEUE_MEMBER_PENALTY</ref>
00505       </see-also>
00506    </function>
00507    <function name="QUEUE_MEMBER" language="en_US">
00508       <synopsis>
00509          Count number of members answering a queue.
00510       </synopsis>
00511       <syntax>
00512          <parameter name="queuename" required="true" />
00513          <parameter name="option" required="true">
00514             <enumlist>
00515                <enum name="logged">
00516                   <para>Returns the number of logged-in members for the specified queue.</para>
00517                </enum>
00518                <enum name="free">
00519                   <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>
00520                </enum>
00521                <enum name="ready">
00522                   <para>Returns the number of logged-in members for the specified queue that are immediately available to answer a call.</para>
00523                </enum>
00524                <enum name="count">
00525                   <para>Returns the total number of members for the specified queue.</para>
00526                </enum>
00527             </enumlist>
00528          </parameter>
00529       </syntax>
00530       <description>
00531          <para>Returns the number of members currently associated with the specified <replaceable>queuename</replaceable>.</para>
00532       </description>
00533       <see-also>
00534          <ref type="application">Queue</ref>
00535          <ref type="application">QueueLog</ref>
00536          <ref type="application">AddQueueMember</ref>
00537          <ref type="application">RemoveQueueMember</ref>
00538          <ref type="application">PauseQueueMember</ref>
00539          <ref type="application">UnpauseQueueMember</ref>
00540          <ref type="function">QUEUE_VARIABLES</ref>
00541          <ref type="function">QUEUE_MEMBER</ref>
00542          <ref type="function">QUEUE_MEMBER_COUNT</ref>
00543          <ref type="function">QUEUE_EXISTS</ref>
00544          <ref type="function">QUEUE_WAITING_COUNT</ref>
00545          <ref type="function">QUEUE_MEMBER_LIST</ref>
00546          <ref type="function">QUEUE_MEMBER_PENALTY</ref>
00547       </see-also>
00548    </function>
00549    <function name="QUEUE_MEMBER_COUNT" language="en_US">
00550       <synopsis>
00551          Count number of members answering a queue.
00552       </synopsis>
00553       <syntax>
00554          <parameter name="queuename" required="true" />
00555       </syntax>
00556       <description>
00557          <para>Returns the number of members currently associated with the specified <replaceable>queuename</replaceable>.</para>
00558          <warning><para>This function has been deprecated in favor of the <literal>QUEUE_MEMBER()</literal> function</para></warning>
00559       </description>
00560       <see-also>
00561          <ref type="application">Queue</ref>
00562          <ref type="application">QueueLog</ref>
00563          <ref type="application">AddQueueMember</ref>
00564          <ref type="application">RemoveQueueMember</ref>
00565          <ref type="application">PauseQueueMember</ref>
00566          <ref type="application">UnpauseQueueMember</ref>
00567          <ref type="function">QUEUE_VARIABLES</ref>
00568          <ref type="function">QUEUE_MEMBER</ref>
00569          <ref type="function">QUEUE_MEMBER_COUNT</ref>
00570          <ref type="function">QUEUE_EXISTS</ref>
00571          <ref type="function">QUEUE_WAITING_COUNT</ref>
00572          <ref type="function">QUEUE_MEMBER_LIST</ref>
00573          <ref type="function">QUEUE_MEMBER_PENALTY</ref>
00574       </see-also>
00575    </function>
00576    <function name="QUEUE_EXISTS" language="en_US">
00577       <synopsis>
00578          Check if a named queue exists on this server
00579       </synopsis>
00580       <syntax>
00581          <parameter name="queuename" />
00582       </syntax>
00583       <description>
00584          <para>Returns 1 if the specified queue exists, 0 if it does not</para>
00585       </description>
00586       <see-also>
00587          <ref type="application">Queue</ref>
00588          <ref type="application">QueueLog</ref>
00589          <ref type="application">AddQueueMember</ref>
00590          <ref type="application">RemoveQueueMember</ref>
00591          <ref type="application">PauseQueueMember</ref>
00592          <ref type="application">UnpauseQueueMember</ref>
00593          <ref type="function">QUEUE_VARIABLES</ref>
00594          <ref type="function">QUEUE_MEMBER</ref>
00595          <ref type="function">QUEUE_MEMBER_COUNT</ref>
00596          <ref type="function">QUEUE_EXISTS</ref>
00597          <ref type="function">QUEUE_WAITING_COUNT</ref>
00598          <ref type="function">QUEUE_MEMBER_LIST</ref>
00599          <ref type="function">QUEUE_MEMBER_PENALTY</ref>
00600       </see-also>
00601    </function>
00602    <function name="QUEUE_WAITING_COUNT" language="en_US">
00603       <synopsis>
00604          Count number of calls currently waiting in a queue.
00605       </synopsis>
00606       <syntax>
00607          <parameter name="queuename" />
00608       </syntax>
00609       <description>
00610          <para>Returns the number of callers currently waiting in the specified <replaceable>queuename</replaceable>.</para>
00611       </description>
00612       <see-also>
00613          <ref type="application">Queue</ref>
00614          <ref type="application">QueueLog</ref>
00615          <ref type="application">AddQueueMember</ref>
00616          <ref type="application">RemoveQueueMember</ref>
00617          <ref type="application">PauseQueueMember</ref>
00618          <ref type="application">UnpauseQueueMember</ref>
00619          <ref type="function">QUEUE_VARIABLES</ref>
00620          <ref type="function">QUEUE_MEMBER</ref>
00621          <ref type="function">QUEUE_MEMBER_COUNT</ref>
00622          <ref type="function">QUEUE_EXISTS</ref>
00623          <ref type="function">QUEUE_WAITING_COUNT</ref>
00624          <ref type="function">QUEUE_MEMBER_LIST</ref>
00625          <ref type="function">QUEUE_MEMBER_PENALTY</ref>
00626       </see-also>
00627    </function>
00628    <function name="QUEUE_MEMBER_LIST" language="en_US">
00629       <synopsis>
00630          Returns a list of interfaces on a queue.
00631       </synopsis>
00632       <syntax>
00633          <parameter name="queuename" required="true" />
00634       </syntax>
00635       <description>
00636          <para>Returns a comma-separated list of members associated with the specified <replaceable>queuename</replaceable>.</para>
00637       </description>
00638       <see-also>
00639          <ref type="application">Queue</ref>
00640          <ref type="application">QueueLog</ref>
00641          <ref type="application">AddQueueMember</ref>
00642          <ref type="application">RemoveQueueMember</ref>
00643          <ref type="application">PauseQueueMember</ref>
00644          <ref type="application">UnpauseQueueMember</ref>
00645          <ref type="function">QUEUE_VARIABLES</ref>
00646          <ref type="function">QUEUE_MEMBER</ref>
00647          <ref type="function">QUEUE_MEMBER_COUNT</ref>
00648          <ref type="function">QUEUE_EXISTS</ref>
00649          <ref type="function">QUEUE_WAITING_COUNT</ref>
00650          <ref type="function">QUEUE_MEMBER_LIST</ref>
00651          <ref type="function">QUEUE_MEMBER_PENALTY</ref>
00652       </see-also>
00653    </function>
00654    <function name="QUEUE_MEMBER_PENALTY" language="en_US">
00655       <synopsis>
00656          Gets or sets queue members penalty.
00657       </synopsis>
00658       <syntax>
00659          <parameter name="queuename" required="true" />
00660          <parameter name="interface" required="true" />
00661       </syntax>
00662       <description>
00663          <para>Gets or sets queue members penalty.</para>
00664       </description>
00665       <see-also>
00666          <ref type="application">Queue</ref>
00667          <ref type="application">QueueLog</ref>
00668          <ref type="application">AddQueueMember</ref>
00669          <ref type="application">RemoveQueueMember</ref>
00670          <ref type="application">PauseQueueMember</ref>
00671          <ref type="application">UnpauseQueueMember</ref>
00672          <ref type="function">QUEUE_VARIABLES</ref>
00673          <ref type="function">QUEUE_MEMBER</ref>
00674          <ref type="function">QUEUE_MEMBER_COUNT</ref>
00675          <ref type="function">QUEUE_EXISTS</ref>
00676          <ref type="function">QUEUE_WAITING_COUNT</ref>
00677          <ref type="function">QUEUE_MEMBER_LIST</ref>
00678          <ref type="function">QUEUE_MEMBER_PENALTY</ref>
00679       </see-also>
00680    </function>
00681    <manager name="Queues" language="en_US">
00682       <synopsis>
00683          Queues.
00684       </synopsis>
00685       <syntax>
00686       </syntax>
00687       <description>
00688       </description>
00689    </manager>
00690    <manager name="QueueStatus" language="en_US">
00691       <synopsis>
00692          Show queue status.
00693       </synopsis>
00694       <syntax>
00695          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00696          <parameter name="Queue" />
00697          <parameter name="Member" />
00698       </syntax>
00699       <description>
00700       </description>
00701    </manager>
00702    <manager name="QueueSummary" language="en_US">
00703       <synopsis>
00704          Show queue summary.
00705       </synopsis>
00706       <syntax>
00707          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00708          <parameter name="Queue" />
00709       </syntax>
00710       <description>
00711       </description>
00712    </manager>
00713    <manager name="QueueAdd" language="en_US">
00714       <synopsis>
00715          Add interface to queue.
00716       </synopsis>
00717       <syntax>
00718          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00719          <parameter name="Queue" required="true" />
00720          <parameter name="Interface" required="true" />
00721          <parameter name="Penalty" />
00722          <parameter name="Paused" />
00723          <parameter name="MemberName" />
00724          <parameter name="StateInterface" />
00725       </syntax>
00726       <description>
00727       </description>
00728    </manager>
00729    <manager name="QueueRemove" language="en_US">
00730       <synopsis>
00731          Remove interface from queue.
00732       </synopsis>
00733       <syntax>
00734          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00735          <parameter name="Queue" required="true" />
00736          <parameter name="Interface" required="true" />
00737       </syntax>
00738       <description>
00739       </description>
00740    </manager>
00741    <manager name="QueuePause" language="en_US">
00742       <synopsis>
00743          Makes a queue member temporarily unavailable.
00744       </synopsis>
00745       <syntax>
00746          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00747          <parameter name="Interface" required="true" />
00748          <parameter name="Paused" required="true" />
00749          <parameter name="Queue" />
00750          <parameter name="Reason" />
00751       </syntax>
00752       <description>
00753       </description>
00754    </manager>
00755    <manager name="QueueLog" language="en_US">
00756       <synopsis>
00757          Adds custom entry in queue_log.
00758       </synopsis>
00759       <syntax>
00760          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00761          <parameter name="Queue" required="true" />
00762          <parameter name="Event" required="true" />
00763          <parameter name="Uniqueid" />
00764          <parameter name="Interface" />
00765          <parameter name="Message" />
00766       </syntax>
00767       <description>
00768       </description>
00769    </manager>
00770    <manager name="QueuePenalty" language="en_US">
00771       <synopsis>
00772          Set the penalty for a queue member.
00773       </synopsis>
00774       <syntax>
00775          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00776          <parameter name="Interface" required="true" />
00777          <parameter name="Penalty" required="true" />
00778          <parameter name="Queue" />
00779       </syntax>
00780       <description>
00781       </description>
00782    </manager>
00783    <manager name="QueueRule" language="en_US">
00784       <synopsis>
00785          Queue Rules.
00786       </synopsis>
00787       <syntax>
00788          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00789          <parameter name="Rule" />
00790       </syntax>
00791       <description>
00792       </description>
00793    </manager>
00794    <manager name="QueueReload" language="en_US">
00795       <synopsis>
00796          Reload a queue, queues, or any sub-section of a queue or queues.
00797       </synopsis>
00798       <syntax>
00799          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00800          <parameter name="Queue" />
00801          <parameter name="Members">
00802             <enumlist>
00803                <enum name="yes" />
00804                <enum name="no" />
00805             </enumlist>
00806          </parameter>
00807          <parameter name="Rules">
00808             <enumlist>
00809                <enum name="yes" />
00810                <enum name="no" />
00811             </enumlist>
00812          </parameter>
00813          <parameter name="Parameters">
00814             <enumlist>
00815                <enum name="yes" />
00816                <enum name="no" />
00817             </enumlist>
00818          </parameter>
00819       </syntax>
00820       <description>
00821       </description>
00822    </manager>
00823    <manager name="QueueReset" language="en_US">
00824       <synopsis>
00825          Reset queue statistics.
00826       </synopsis>
00827       <syntax>
00828          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00829          <parameter name="Queue" />
00830       </syntax>
00831       <description>
00832       </description>
00833    </manager>
00834  ***/
00835 
00836 enum {
00837    QUEUE_STRATEGY_RINGALL = 0,
00838    QUEUE_STRATEGY_LEASTRECENT,
00839    QUEUE_STRATEGY_FEWESTCALLS,
00840    QUEUE_STRATEGY_RANDOM,
00841    QUEUE_STRATEGY_RRMEMORY,
00842    QUEUE_STRATEGY_LINEAR,
00843    QUEUE_STRATEGY_WRANDOM,
00844    QUEUE_STRATEGY_RRORDERED,
00845 };
00846 
00847 enum {
00848      QUEUE_AUTOPAUSE_OFF = 0,
00849      QUEUE_AUTOPAUSE_ON,
00850      QUEUE_AUTOPAUSE_ALL
00851 };
00852 
00853 enum queue_reload_mask {
00854    QUEUE_RELOAD_PARAMETERS = (1 << 0),
00855    QUEUE_RELOAD_MEMBER = (1 << 1),
00856    QUEUE_RELOAD_RULES = (1 << 2),
00857    QUEUE_RESET_STATS = (1 << 3),
00858 };
00859 
00860 static const struct strategy {
00861    int strategy;
00862    const char *name;
00863 } strategies[] = {
00864    { QUEUE_STRATEGY_RINGALL, "ringall" },
00865    { QUEUE_STRATEGY_LEASTRECENT, "leastrecent" },
00866    { QUEUE_STRATEGY_FEWESTCALLS, "fewestcalls" },
00867    { QUEUE_STRATEGY_RANDOM, "random" },
00868    { QUEUE_STRATEGY_RRMEMORY, "rrmemory" },
00869    { QUEUE_STRATEGY_RRMEMORY, "roundrobin" },
00870    { QUEUE_STRATEGY_LINEAR, "linear" },
00871    { QUEUE_STRATEGY_WRANDOM, "wrandom"},
00872    { QUEUE_STRATEGY_RRORDERED, "rrordered"},
00873 };
00874 
00875 static const struct autopause {
00876    int autopause;
00877    const char *name;
00878 } autopausesmodes [] = {
00879    { QUEUE_AUTOPAUSE_OFF,"no" },
00880    { QUEUE_AUTOPAUSE_ON, "yes" },
00881    { QUEUE_AUTOPAUSE_ALL,"all" },
00882 };
00883 
00884 
00885 static struct ast_taskprocessor *devicestate_tps;
00886 
00887 #define DEFAULT_RETRY      5
00888 #define DEFAULT_TIMEOUT    15
00889 #define RECHECK         1     /*!< Recheck every second to see we we're at the top yet */
00890 #define MAX_PERIODIC_ANNOUNCEMENTS 10           /*!< The maximum periodic announcements we can have */
00891 #define DEFAULT_MIN_ANNOUNCE_FREQUENCY 15       /*!< The minimum number of seconds between position announcements \
00892                                                      The default value of 15 provides backwards compatibility */
00893 #define MAX_QUEUE_BUCKETS 53
00894 
00895 #define  RES_OKAY 0     /*!< Action completed */
00896 #define  RES_EXISTS  (-1)     /*!< Entry already exists */
00897 #define  RES_OUTOFMEMORY   (-2)     /*!< Out of memory */
00898 #define  RES_NOSUCHQUEUE   (-3)     /*!< No such queue */
00899 #define RES_NOT_DYNAMIC (-4)     /*!< Member is not dynamic */
00900 
00901 static char *app = "Queue";
00902 
00903 static char *app_aqm = "AddQueueMember" ;
00904 
00905 static char *app_rqm = "RemoveQueueMember" ;
00906 
00907 static char *app_pqm = "PauseQueueMember" ;
00908 
00909 static char *app_upqm = "UnpauseQueueMember" ;
00910 
00911 static char *app_ql = "QueueLog" ;
00912 
00913 /*! \brief Persistent Members astdb family */
00914 static const char * const pm_family = "Queue/PersistentMembers";
00915 
00916 /*! \brief queues.conf [general] option */
00917 static int queue_persistent_members = 0;
00918 
00919 /*! \brief queues.conf per-queue weight option */
00920 static int use_weight = 0;
00921 
00922 /*! \brief queues.conf [general] option */
00923 static int autofill_default = 1;
00924 
00925 /*! \brief queues.conf [general] option */
00926 static int montype_default = 0;
00927 
00928 /*! \brief queues.conf [general] option */
00929 static int shared_lastcall = 1;
00930 
00931 /*! \brief Subscription to device state change events */
00932 static struct ast_event_sub *device_state_sub;
00933 
00934 /*! \brief queues.conf [general] option */
00935 static int update_cdr = 0;
00936 
00937 enum queue_result {
00938    QUEUE_UNKNOWN = 0,
00939    QUEUE_TIMEOUT = 1,
00940    QUEUE_JOINEMPTY = 2,
00941    QUEUE_LEAVEEMPTY = 3,
00942    QUEUE_JOINUNAVAIL = 4,
00943    QUEUE_LEAVEUNAVAIL = 5,
00944    QUEUE_FULL = 6,
00945    QUEUE_CONTINUE = 7,
00946 };
00947 
00948 static const struct {
00949    enum queue_result id;
00950    char *text;
00951 } queue_results[] = {
00952    { QUEUE_UNKNOWN, "UNKNOWN" },
00953    { QUEUE_TIMEOUT, "TIMEOUT" },
00954    { QUEUE_JOINEMPTY,"JOINEMPTY" },
00955    { QUEUE_LEAVEEMPTY, "LEAVEEMPTY" },
00956    { QUEUE_JOINUNAVAIL, "JOINUNAVAIL" },
00957    { QUEUE_LEAVEUNAVAIL, "LEAVEUNAVAIL" },
00958    { QUEUE_FULL, "FULL" },
00959    { QUEUE_CONTINUE, "CONTINUE" },
00960 };
00961 
00962 enum queue_timeout_priority {
00963    TIMEOUT_PRIORITY_APP,
00964    TIMEOUT_PRIORITY_CONF,
00965 };
00966 
00967 /*! \brief We define a custom "local user" structure because we
00968  *  use it not only for keeping track of what is in use but
00969  *  also for keeping track of who we're dialing.
00970  *
00971  *  There are two "links" defined in this structure, q_next and call_next.
00972  *  q_next links ALL defined callattempt structures into a linked list. call_next is
00973  *  a link which allows for a subset of the callattempts to be traversed. This subset
00974  *  is used in wait_for_answer so that irrelevant callattempts are not traversed. This
00975  *  also is helpful so that queue logs are always accurate in the case where a call to 
00976  *  a member times out, especially if using the ringall strategy. 
00977 */
00978 
00979 struct callattempt {
00980    struct callattempt *q_next;
00981    struct callattempt *call_next;
00982    struct ast_channel *chan;
00983    char interface[256];
00984    int metric;
00985    time_t lastcall;
00986    struct call_queue *lastqueue;
00987    struct member *member;
00988    /*! Saved connected party info from an AST_CONTROL_CONNECTED_LINE. */
00989    struct ast_party_connected_line connected;
00990    /*! TRUE if an AST_CONTROL_CONNECTED_LINE update was saved to the connected element. */
00991    unsigned int pending_connected_update:1;
00992    /*! TRUE if the connected line update is blocked. */
00993    unsigned int block_connected_update:1;
00994    /*! TRUE if caller id is not available for connected line */
00995    unsigned int dial_callerid_absent:1;
00996    /*! TRUE if the call is still active */
00997    unsigned int stillgoing:1;
00998    struct ast_aoc_decoded *aoc_s_rate_list;
00999 };
01000 
01001 
01002 struct queue_ent {
01003    struct call_queue *parent;             /*!< What queue is our parent */
01004    char moh[80];                          /*!< Name of musiconhold to be used */
01005    char announce[PATH_MAX];               /*!< Announcement to play for member when call is answered */
01006    char context[AST_MAX_CONTEXT];         /*!< Context when user exits queue */
01007    char digits[AST_MAX_EXTENSION];        /*!< Digits entered while in queue */
01008    int valid_digits;                      /*!< Digits entered correspond to valid extension. Exited */
01009    int pos;                               /*!< Where we are in the queue */
01010    int prio;                              /*!< Our priority */
01011    int last_pos_said;                     /*!< Last position we told the user */
01012    int ring_when_ringing;                 /*!< Should we only use ring indication when a channel is ringing? */
01013    time_t last_periodic_announce_time;    /*!< The last time we played a periodic announcement */
01014    int last_periodic_announce_sound;      /*!< The last periodic announcement we made */
01015    time_t last_pos;                       /*!< Last time we told the user their position */
01016    int opos;                              /*!< Where we started in the queue */
01017    int handled;                           /*!< Whether our call was handled */
01018    int pending;                           /*!< Non-zero if we are attempting to call a member */
01019    int max_penalty;                       /*!< Limit the members that can take this call to this penalty or lower */
01020    int min_penalty;                       /*!< Limit the members that can take this call to this penalty or higher */
01021    int linpos;                            /*!< If using linear strategy, what position are we at? */
01022    int linwrapped;                        /*!< Is the linpos wrapped? */
01023    time_t start;                          /*!< When we started holding */
01024    time_t expire;                         /*!< When this entry should expire (time out of queue) */
01025    int cancel_answered_elsewhere;          /*!< Whether we should force the CAE flag on this call (C) option*/
01026    struct ast_channel *chan;              /*!< Our channel */
01027    AST_LIST_HEAD_NOLOCK(,penalty_rule) qe_rules; /*!< Local copy of the queue's penalty rules */
01028    struct penalty_rule *pr;               /*!< Pointer to the next penalty rule to implement */
01029    struct queue_ent *next;                /*!< The next queue entry */
01030 };
01031 
01032 struct member {
01033    char interface[80];                  /*!< Technology/Location to dial to reach this member*/
01034    char state_exten[AST_MAX_EXTENSION]; /*!< Extension to get state from (if using hint) */
01035    char state_context[AST_MAX_CONTEXT]; /*!< Context to use when getting state (if using hint) */
01036    char state_interface[80];            /*!< Technology/Location from which to read devicestate changes */
01037    char membername[80];                 /*!< Member name to use in queue logs */
01038    int penalty;                         /*!< Are we a last resort? */
01039    int calls;                           /*!< Number of calls serviced by this member */
01040    int dynamic;                         /*!< Are we dynamically added? */
01041    int realtime;                        /*!< Is this member realtime? */
01042    int status;                          /*!< Status of queue member */
01043    int paused;                          /*!< Are we paused (not accepting calls)? */
01044    int queuepos;                        /*!< In what order (pertains to certain strategies) should this member be called? */
01045    time_t lastcall;                     /*!< When last successful call was hungup */
01046    struct call_queue *lastqueue;      /*!< Last queue we received a call */
01047    unsigned int dead:1;                 /*!< Used to detect members deleted in realtime */
01048    unsigned int delme:1;                /*!< Flag to delete entry on reload */
01049    unsigned int call_pending:1;         /*!< TRUE if the Q is attempting to place a call to the member. */
01050    char rt_uniqueid[80];                /*!< Unique id of realtime member entry */
01051 };
01052 
01053 enum empty_conditions {
01054    QUEUE_EMPTY_PENALTY = (1 << 0),
01055    QUEUE_EMPTY_PAUSED = (1 << 1),
01056    QUEUE_EMPTY_INUSE = (1 << 2),
01057    QUEUE_EMPTY_RINGING = (1 << 3),
01058    QUEUE_EMPTY_UNAVAILABLE = (1 << 4),
01059    QUEUE_EMPTY_INVALID = (1 << 5),
01060    QUEUE_EMPTY_UNKNOWN = (1 << 6),
01061    QUEUE_EMPTY_WRAPUP = (1 << 7),
01062 };
01063 
01064 /* values used in multi-bit flags in call_queue */
01065 #define ANNOUNCEHOLDTIME_ALWAYS 1
01066 #define ANNOUNCEHOLDTIME_ONCE 2
01067 #define QUEUE_EVENT_VARIABLES 3
01068 
01069 struct penalty_rule {
01070    int time;                           /*!< Number of seconds that need to pass before applying this rule */
01071    int max_value;                      /*!< The amount specified in the penalty rule for max penalty */
01072    int min_value;                      /*!< The amount specified in the penalty rule for min penalty */
01073    int max_relative;                   /*!< Is the max adjustment relative? 1 for relative, 0 for absolute */
01074    int min_relative;                   /*!< Is the min adjustment relative? 1 for relative, 0 for absolute */
01075    AST_LIST_ENTRY(penalty_rule) list;  /*!< Next penalty_rule */
01076 };
01077 
01078 #define ANNOUNCEPOSITION_YES 1 /*!< We announce position */
01079 #define ANNOUNCEPOSITION_NO 2 /*!< We don't announce position */
01080 #define ANNOUNCEPOSITION_MORE_THAN 3 /*!< We say "Currently there are more than <limit>" */
01081 #define ANNOUNCEPOSITION_LIMIT 4 /*!< We not announce position more than <limit> */
01082 
01083 struct call_queue {
01084    AST_DECLARE_STRING_FIELDS(
01085       /*! Queue name */
01086       AST_STRING_FIELD(name);
01087       /*! Music on Hold class */
01088       AST_STRING_FIELD(moh);
01089       /*! Announcement to play when call is answered */
01090       AST_STRING_FIELD(announce);
01091       /*! Exit context */
01092       AST_STRING_FIELD(context);
01093       /*! Macro to run upon member connection */
01094       AST_STRING_FIELD(membermacro);
01095       /*! Gosub to run upon member connection */
01096       AST_STRING_FIELD(membergosub);
01097       /*! Default rule to use if none specified in call to Queue() */
01098       AST_STRING_FIELD(defaultrule);
01099       /*! Sound file: "Your call is now first in line" (def. queue-youarenext) */
01100       AST_STRING_FIELD(sound_next);
01101       /*! Sound file: "There are currently" (def. queue-thereare) */
01102       AST_STRING_FIELD(sound_thereare);
01103       /*! Sound file: "calls waiting to speak to a representative." (def. queue-callswaiting) */
01104       AST_STRING_FIELD(sound_calls);
01105       /*! Sound file: "Currently there are more than" (def. queue-quantity1) */
01106       AST_STRING_FIELD(queue_quantity1);
01107       /*! Sound file: "callers waiting to speak with a representative" (def. queue-quantity2) */
01108       AST_STRING_FIELD(queue_quantity2);
01109       /*! Sound file: "The current estimated total holdtime is" (def. queue-holdtime) */
01110       AST_STRING_FIELD(sound_holdtime);
01111       /*! Sound file: "minutes." (def. queue-minutes) */
01112       AST_STRING_FIELD(sound_minutes);
01113       /*! Sound file: "minute." (def. queue-minute) */
01114       AST_STRING_FIELD(sound_minute);
01115       /*! Sound file: "seconds." (def. queue-seconds) */
01116       AST_STRING_FIELD(sound_seconds);
01117       /*! Sound file: "Thank you for your patience." (def. queue-thankyou) */
01118       AST_STRING_FIELD(sound_thanks);
01119       /*! Sound file: Custom announce for caller, no default */
01120       AST_STRING_FIELD(sound_callerannounce);
01121       /*! Sound file: "Hold time" (def. queue-reporthold) */
01122       AST_STRING_FIELD(sound_reporthold);
01123    );
01124    /*! Sound files: Custom announce, no default */
01125    struct ast_str *sound_periodicannounce[MAX_PERIODIC_ANNOUNCEMENTS];
01126    unsigned int dead:1;
01127    unsigned int eventwhencalled:2;
01128    unsigned int ringinuse:1;
01129    unsigned int setinterfacevar:1;
01130    unsigned int setqueuevar:1;
01131    unsigned int setqueueentryvar:1;
01132    unsigned int reportholdtime:1;
01133    unsigned int wrapped:1;
01134    unsigned int timeoutrestart:1;
01135    unsigned int announceholdtime:2;
01136    unsigned int announceposition:3;
01137    int strategy:4;
01138    unsigned int maskmemberstatus:1;
01139    unsigned int realtime:1;
01140    unsigned int found:1;
01141    unsigned int relativeperiodicannounce:1;
01142    enum empty_conditions joinempty;
01143    enum empty_conditions leavewhenempty;
01144    int announcepositionlimit;          /*!< How many positions we announce? */
01145    int announcefrequency;              /*!< How often to announce their position */
01146    int minannouncefrequency;           /*!< The minimum number of seconds between position announcements (def. 15) */
01147    int periodicannouncefrequency;      /*!< How often to play periodic announcement */
01148    int numperiodicannounce;            /*!< The number of periodic announcements configured */
01149    int randomperiodicannounce;         /*!< Are periodic announcments randomly chosen */
01150    int roundingseconds;                /*!< How many seconds do we round to? */
01151    int holdtime;                       /*!< Current avg holdtime, based on an exponential average */
01152    int talktime;                       /*!< Current avg talktime, based on the same exponential average */
01153    int callscompleted;                 /*!< Number of queue calls completed */
01154    int callsabandoned;                 /*!< Number of queue calls abandoned */
01155    int servicelevel;                   /*!< seconds setting for servicelevel*/
01156    int callscompletedinsl;             /*!< Number of calls answered with servicelevel*/
01157    char monfmt[8];                     /*!< Format to use when recording calls */
01158    int montype;                        /*!< Monitor type  Monitor vs. MixMonitor */
01159    int count;                          /*!< How many entries */
01160    int maxlen;                         /*!< Max number of entries */
01161    int wrapuptime;                     /*!< Wrapup Time */
01162    int penaltymemberslimit;            /*!< Disregard penalty when queue has fewer than this many members */
01163 
01164    int retry;                          /*!< Retry calling everyone after this amount of time */
01165    int timeout;                        /*!< How long to wait for an answer */
01166    int weight;                         /*!< Respective weight */
01167    int autopause;                      /*!< Auto pause queue members if they fail to answer */
01168    int timeoutpriority;                /*!< Do we allow a fraction of the timeout to occur for a ring? */
01169 
01170    /* Queue strategy things */
01171    int rrpos;                          /*!< Round Robin - position */
01172    int memberdelay;                    /*!< Seconds to delay connecting member to caller */
01173    int autofill;                       /*!< Ignore the head call status and ring an available agent */
01174    
01175    struct ao2_container *members;             /*!< Head of the list of members */
01176    struct queue_ent *head;             /*!< Head of the list of callers */
01177    AST_LIST_ENTRY(call_queue) list;    /*!< Next call queue */
01178    AST_LIST_HEAD_NOLOCK(, penalty_rule) rules; /*!< The list of penalty rules to invoke */
01179 };
01180 
01181 struct rule_list {
01182    char name[80];
01183    AST_LIST_HEAD_NOLOCK(,penalty_rule) rules;
01184    AST_LIST_ENTRY(rule_list) list;
01185 };
01186 
01187 static AST_LIST_HEAD_STATIC(rule_lists, rule_list);
01188 
01189 static struct ao2_container *queues;
01190 
01191 static void update_realtime_members(struct call_queue *q);
01192 static int set_member_paused(const char *queuename, const char *interface, const char *reason, int paused);
01193 
01194 static void queue_transfer_fixup(void *data, struct ast_channel *old_chan, struct ast_channel *new_chan); 
01195 /*! \brief sets the QUEUESTATUS channel variable */
01196 static void set_queue_result(struct ast_channel *chan, enum queue_result res)
01197 {
01198    int i;
01199 
01200    for (i = 0; i < ARRAY_LEN(queue_results); i++) {
01201       if (queue_results[i].id == res) {
01202          pbx_builtin_setvar_helper(chan, "QUEUESTATUS", queue_results[i].text);
01203          return;
01204       }
01205    }
01206 }
01207 
01208 static const char *int2strat(int strategy)
01209 {
01210    int x;
01211 
01212    for (x = 0; x < ARRAY_LEN(strategies); x++) {
01213       if (strategy == strategies[x].strategy)
01214          return strategies[x].name;
01215    }
01216 
01217    return "<unknown>";
01218 }
01219 
01220 static int strat2int(const char *strategy)
01221 {
01222    int x;
01223 
01224    for (x = 0; x < ARRAY_LEN(strategies); x++) {
01225       if (!strcasecmp(strategy, strategies[x].name))
01226          return strategies[x].strategy;
01227    }
01228 
01229    return -1;
01230 }
01231 
01232 static int autopause2int(const char *autopause)
01233 {
01234    int x;
01235    /*This 'double check' that default value is OFF */
01236    if (ast_strlen_zero(autopause))
01237       return QUEUE_AUTOPAUSE_OFF;
01238 
01239    /*This 'double check' is to ensure old values works */
01240    if(ast_true(autopause))
01241       return QUEUE_AUTOPAUSE_ON;
01242 
01243    for (x = 0; x < ARRAY_LEN(autopausesmodes); x++) {
01244       if (!strcasecmp(autopause, autopausesmodes[x].name))
01245          return autopausesmodes[x].autopause;
01246    }
01247 
01248    /*This 'double check' that default value is OFF */
01249    return QUEUE_AUTOPAUSE_OFF;
01250 }
01251 
01252 static int queue_hash_cb(const void *obj, const int flags)
01253 {
01254    const struct call_queue *q = obj;
01255 
01256    return ast_str_case_hash(q->name);
01257 }
01258 
01259 static int queue_cmp_cb(void *obj, void *arg, int flags)
01260 {
01261    struct call_queue *q = obj, *q2 = arg;
01262    return !strcasecmp(q->name, q2->name) ? CMP_MATCH | CMP_STOP : 0;
01263 }
01264 
01265 /*! \internal
01266  * \brief ao2_callback, Decreases queuepos of all followers with a queuepos greater than arg.
01267  * \param obj the member being acted on
01268  * \param arg pointer to an integer containing the position value that was removed and requires reduction for anything above
01269  */
01270 static int queue_member_decrement_followers(void *obj, void *arg, int flag)
01271 {
01272    struct member *mem = obj;
01273    int *decrement_followers_after = arg;
01274 
01275    if (mem->queuepos > *decrement_followers_after) {
01276       mem->queuepos--;
01277    }
01278 
01279    return 0;
01280 }
01281 
01282 /*! \internal
01283  * \brief ao2_callback, finds members in a queue marked for deletion and in a cascading fashion runs queue_member_decrement_followers
01284  *        on them. This callback should always be ran before performing mass unlinking of delmarked members from queues.
01285  * \param obj member being acted on
01286  * \param arg pointer to the queue members are being removed from
01287  */
01288 static int queue_delme_members_decrement_followers(void *obj, void *arg, int flag)
01289 {
01290    struct member *mem = obj;
01291    struct call_queue *queue = arg;
01292    int rrpos = mem->queuepos;
01293 
01294    if (mem->delme) {
01295       ao2_callback(queue->members, OBJ_NODATA | OBJ_MULTIPLE, queue_member_decrement_followers, &rrpos);
01296    }
01297 
01298    return 0;
01299 }
01300 
01301 /*! \internal
01302  * \brief Use this to decrement followers during removal of a member
01303  * \param queue which queue the member is being removed from
01304  * \param mem which member is being removed from the queue
01305  */
01306 static void queue_member_follower_removal(struct call_queue *queue, struct member *mem)
01307 {
01308    int pos = mem->queuepos;
01309 
01310    /* 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
01311     * who would have been next otherwise. */
01312    if (pos < queue->rrpos) {
01313       queue->rrpos--;
01314    }
01315 
01316    ao2_callback(queue->members, OBJ_NODATA | OBJ_MULTIPLE, queue_member_decrement_followers, &pos);
01317 }
01318 
01319 #ifdef REF_DEBUG_ONLY_QUEUES
01320 #define queue_ref(a) __ao2_ref_debug(a,1,"",__FILE__,__LINE__,__PRETTY_FUNCTION__)
01321 #define queue_unref(a)  __ao2_ref_debug(a,-1,"",__FILE__,__LINE__,__PRETTY_FUNCTION__)
01322 #define queue_t_ref(a,b)   __ao2_ref_debug(a,1,b,__FILE__,__LINE__,__PRETTY_FUNCTION__)
01323 #define queue_t_unref(a,b) __ao2_ref_debug(a,-1,b,__FILE__,__LINE__,__PRETTY_FUNCTION__)
01324 #define queues_t_link(c,q,tag)   __ao2_link_debug(c,q,tag,__FILE__,__LINE__,__PRETTY_FUNCTION__)
01325 #define queues_t_unlink(c,q,tag) __ao2_unlink_debug(c,q,tag,__FILE__,__LINE__,__PRETTY_FUNCTION__)
01326 #else
01327 #define queue_t_ref(a,b)   queue_ref(a)
01328 #define queue_t_unref(a,b) queue_unref(a)
01329 #define queues_t_link(c,q,tag)   ao2_t_link(c,q,tag)
01330 #define queues_t_unlink(c,q,tag) ao2_t_unlink(c,q,tag)
01331 static inline struct call_queue *queue_ref(struct call_queue *q)
01332 {
01333    ao2_ref(q, 1);
01334    return q;
01335 }
01336 
01337 static inline struct call_queue *queue_unref(struct call_queue *q)
01338 {
01339    ao2_ref(q, -1);
01340    return NULL;
01341 }
01342 #endif
01343 
01344 /*! \brief Set variables of queue */
01345 static void set_queue_variables(struct call_queue *q, struct ast_channel *chan)
01346 {
01347    char interfacevar[256]="";
01348    float sl = 0;
01349 
01350    ao2_lock(q);
01351 
01352    if (q->setqueuevar) {
01353       sl = 0;
01354       if (q->callscompleted > 0) 
01355          sl = 100 * ((float) q->callscompletedinsl / (float) q->callscompleted);
01356 
01357       snprintf(interfacevar, sizeof(interfacevar),
01358          "QUEUENAME=%s,QUEUEMAX=%d,QUEUESTRATEGY=%s,QUEUECALLS=%d,QUEUEHOLDTIME=%d,QUEUETALKTIME=%d,QUEUECOMPLETED=%d,QUEUEABANDONED=%d,QUEUESRVLEVEL=%d,QUEUESRVLEVELPERF=%2.1f",
01359          q->name, q->maxlen, int2strat(q->strategy), q->count, q->holdtime, q->talktime, q->callscompleted, q->callsabandoned,  q->servicelevel, sl);
01360 
01361       ao2_unlock(q);
01362    
01363       pbx_builtin_setvar_multiple(chan, interfacevar); 
01364    } else {
01365       ao2_unlock(q);
01366    }
01367 }
01368 
01369 /*! \brief Insert the 'new' entry after the 'prev' entry of queue 'q' */
01370 static inline void insert_entry(struct call_queue *q, struct queue_ent *prev, struct queue_ent *new, int *pos)
01371 {
01372    struct queue_ent *cur;
01373 
01374    if (!q || !new)
01375       return;
01376    if (prev) {
01377       cur = prev->next;
01378       prev->next = new;
01379    } else {
01380       cur = q->head;
01381       q->head = new;
01382    }
01383    new->next = cur;
01384 
01385    /* every queue_ent must have a reference to it's parent call_queue, this
01386     * reference does not go away until the end of the queue_ent's life, meaning
01387     * that even when the queue_ent leaves the call_queue this ref must remain. */
01388    queue_ref(q);
01389    new->parent = q;
01390    new->pos = ++(*pos);
01391    new->opos = *pos;
01392 }
01393 
01394 /*! \brief Check if members are available
01395  *
01396  * This function checks to see if members are available to be called. If any member
01397  * is available, the function immediately returns 0. If no members are available,
01398  * then -1 is returned.
01399  */
01400 static int get_member_status(struct call_queue *q, int max_penalty, int min_penalty, enum empty_conditions conditions)
01401 {
01402    struct member *member;
01403    struct ao2_iterator mem_iter;
01404 
01405    ao2_lock(q);
01406    mem_iter = ao2_iterator_init(q->members, 0);
01407    for (; (member = ao2_iterator_next(&mem_iter)); ao2_ref(member, -1)) {
01408       if ((max_penalty && (member->penalty > max_penalty)) || (min_penalty && (member->penalty < min_penalty))) {
01409          if (conditions & QUEUE_EMPTY_PENALTY) {
01410             ast_debug(4, "%s is unavailable because his penalty is not between %d and %d\n", member->membername, min_penalty, max_penalty);
01411             continue;
01412          }
01413       }
01414 
01415       switch (member->status) {
01416       case AST_DEVICE_INVALID:
01417          if (conditions & QUEUE_EMPTY_INVALID) {
01418             ast_debug(4, "%s is unavailable because his device state is 'invalid'\n", member->membername);
01419             break;
01420          }
01421          goto default_case;
01422       case AST_DEVICE_UNAVAILABLE:
01423          if (conditions & QUEUE_EMPTY_UNAVAILABLE) {
01424             ast_debug(4, "%s is unavailable because his device state is 'unavailable'\n", member->membername);
01425             break;
01426          }
01427          goto default_case;
01428       case AST_DEVICE_INUSE:
01429          if (conditions & QUEUE_EMPTY_INUSE) {
01430             ast_debug(4, "%s is unavailable because his device state is 'inuse'\n", member->membername);
01431             break;
01432          }
01433          goto default_case;
01434       case AST_DEVICE_RINGING:
01435          if (conditions & QUEUE_EMPTY_RINGING) {
01436             ast_debug(4, "%s is unavailable because his device state is 'ringing'\n", member->membername);
01437             break;
01438          }
01439          goto default_case;
01440       case AST_DEVICE_UNKNOWN:
01441          if (conditions & QUEUE_EMPTY_UNKNOWN) {
01442             ast_debug(4, "%s is unavailable because his device state is 'unknown'\n", member->membername);
01443             break;
01444          }
01445          /* Fall-through */
01446       default:
01447       default_case:
01448          if (member->paused && (conditions & QUEUE_EMPTY_PAUSED)) {
01449             ast_debug(4, "%s is unavailable because he is paused'\n", member->membername);
01450             break;
01451          } else if ((conditions & QUEUE_EMPTY_WRAPUP) && member->lastcall && q->wrapuptime && (time(NULL) - q->wrapuptime < member->lastcall)) {
01452             ast_debug(4, "%s is unavailable because it has only been %d seconds since his last call (wrapup time is %d)\n", member->membername, (int) (time(NULL) - member->lastcall), q->wrapuptime);
01453             break;
01454          } else {
01455             ao2_ref(member, -1);
01456             ao2_iterator_destroy(&mem_iter);
01457             ao2_unlock(q);
01458             ast_debug(4, "%s is available.\n", member->membername);
01459             return 0;
01460          }
01461          break;
01462       }
01463    }
01464    ao2_iterator_destroy(&mem_iter);
01465 
01466    ao2_unlock(q);
01467    return -1;
01468 }
01469 
01470 struct statechange {
01471    AST_LIST_ENTRY(statechange) entry;
01472    int state;
01473    char dev[0];
01474 };
01475 
01476 /*! \brief set a member's status based on device state of that member's state_interface.
01477  *  
01478  * Lock interface list find sc, iterate through each queues queue_member list for member to
01479  * update state inside queues
01480 */
01481 static int update_status(struct call_queue *q, struct member *m, const int status)
01482 {
01483    m->status = status;
01484 
01485    if (q->maskmemberstatus)
01486       return 0;
01487 
01488    manager_event(EVENT_FLAG_AGENT, "QueueMemberStatus",
01489       "Queue: %s\r\n"
01490       "Location: %s\r\n"
01491       "MemberName: %s\r\n"
01492       "Membership: %s\r\n"
01493       "Penalty: %d\r\n"
01494       "CallsTaken: %d\r\n"
01495       "LastCall: %d\r\n"
01496       "Status: %d\r\n"
01497       "Paused: %d\r\n",
01498       q->name, m->interface, m->membername, m->dynamic ? "dynamic" : m->realtime ? "realtime" : "static",
01499       m->penalty, m->calls, (int)m->lastcall, m->status, m->paused
01500    );
01501 
01502    return 0;
01503 }
01504 
01505 /*! \brief set a member's status based on device state of that member's interface*/
01506 static int handle_statechange(void *datap)
01507 {
01508    struct statechange *sc = datap;
01509    struct ao2_iterator miter, qiter;
01510    struct member *m;
01511    struct call_queue *q;
01512    char interface[80], *slash_pos;
01513    int found = 0;
01514 
01515    qiter = ao2_iterator_init(queues, 0);
01516    while ((q = ao2_t_iterator_next(&qiter, "Iterate over queues"))) {
01517       ao2_lock(q);
01518 
01519       miter = ao2_iterator_init(q->members, 0);
01520       for (; (m = ao2_iterator_next(&miter)); ao2_ref(m, -1)) {
01521          ast_copy_string(interface, m->state_interface, sizeof(interface));
01522 
01523          if ((slash_pos = strchr(interface, '/')))
01524             if (!strncasecmp(interface, "Local/", 6) && (slash_pos = strchr(slash_pos + 1, '/')))
01525                *slash_pos = '\0';
01526 
01527          if (!strcasecmp(interface, sc->dev)) {
01528             found = 1;
01529             update_status(q, m, sc->state);
01530             ao2_ref(m, -1);
01531             break;
01532          }
01533       }
01534       ao2_iterator_destroy(&miter);
01535 
01536       ao2_unlock(q);
01537       queue_t_unref(q, "Done with iterator");
01538    }
01539    ao2_iterator_destroy(&qiter);
01540 
01541    if (found)
01542       ast_debug(1, "Device '%s' changed to state '%d' (%s)\n", sc->dev, sc->state, ast_devstate2str(sc->state));
01543    else
01544       ast_debug(3, "Device '%s' changed to state '%d' (%s) but we don't care because they're not a member of any queue.\n", sc->dev, sc->state, ast_devstate2str(sc->state));
01545 
01546    ast_free(sc);
01547    return 0;
01548 }
01549 
01550 static void device_state_cb(const struct ast_event *event, void *unused)
01551 {
01552    enum ast_device_state state;
01553    const char *device;
01554    struct statechange *sc;
01555    size_t datapsize;
01556 
01557    state = ast_event_get_ie_uint(event, AST_EVENT_IE_STATE);
01558    device = ast_event_get_ie_str(event, AST_EVENT_IE_DEVICE);
01559 
01560    if (ast_strlen_zero(device)) {
01561       ast_log(LOG_ERROR, "Received invalid event that had no device IE\n");
01562       return;
01563    }
01564    datapsize = sizeof(*sc) + strlen(device) + 1;
01565    if (!(sc = ast_calloc(1, datapsize))) {
01566       ast_log(LOG_ERROR, "failed to calloc a state change struct\n");
01567       return;
01568    }
01569    sc->state = state;
01570    strcpy(sc->dev, device);
01571    if (ast_taskprocessor_push(devicestate_tps, handle_statechange, sc) < 0) {
01572       ast_free(sc);
01573    }
01574 }
01575 
01576 /*! \brief Helper function which converts from extension state to device state values */
01577 static int extensionstate2devicestate(int state)
01578 {
01579    switch (state) {
01580    case AST_EXTENSION_NOT_INUSE:
01581       state = AST_DEVICE_NOT_INUSE;
01582       break;
01583    case AST_EXTENSION_INUSE:
01584       state = AST_DEVICE_INUSE;
01585       break;
01586    case AST_EXTENSION_BUSY:
01587       state = AST_DEVICE_BUSY;
01588       break;
01589    case AST_EXTENSION_RINGING:
01590       state = AST_DEVICE_RINGING;
01591       break;
01592    case AST_EXTENSION_ONHOLD:
01593       state = AST_DEVICE_ONHOLD;
01594       break;
01595    case AST_EXTENSION_UNAVAILABLE:
01596       state = AST_DEVICE_UNAVAILABLE;
01597       break;
01598    case AST_EXTENSION_REMOVED:
01599    case AST_EXTENSION_DEACTIVATED:
01600    default:
01601       state = AST_DEVICE_INVALID;
01602       break;
01603    }
01604 
01605    return state;
01606 }
01607 
01608 static int extension_state_cb(char *context, char *exten, enum ast_extension_states state, void *data)
01609 {
01610    struct ao2_iterator miter, qiter;
01611    struct member *m;
01612    struct call_queue *q;
01613    int found = 0, device_state = extensionstate2devicestate(state);
01614 
01615    qiter = ao2_iterator_init(queues, 0);
01616    while ((q = ao2_t_iterator_next(&qiter, "Iterate through queues"))) {
01617       ao2_lock(q);
01618 
01619       miter = ao2_iterator_init(q->members, 0);
01620       for (; (m = ao2_iterator_next(&miter)); ao2_ref(m, -1)) {
01621          if (!strcmp(m->state_context, context) && !strcmp(m->state_exten, exten)) {
01622             update_status(q, m, device_state);
01623             ao2_ref(m, -1);
01624             found = 1;
01625             break;
01626          }
01627       }
01628       ao2_iterator_destroy(&miter);
01629 
01630       ao2_unlock(q);
01631       queue_t_unref(q, "Done with iterator");
01632    }
01633    ao2_iterator_destroy(&qiter);
01634 
01635         if (found) {
01636       ast_debug(1, "Extension '%s@%s' changed to state '%d' (%s)\n", exten, context, device_state, ast_devstate2str(device_state));
01637    } else {
01638       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",
01639            exten, context, device_state, ast_devstate2str(device_state));
01640    }
01641 
01642    return 0;
01643 }
01644 
01645 /*! \brief Return the current state of a member */
01646 static int get_queue_member_status(struct member *cur)
01647 {
01648    return ast_strlen_zero(cur->state_exten) ? ast_device_state(cur->state_interface) : extensionstate2devicestate(ast_extension_state(NULL, cur->state_context, cur->state_exten));
01649 }
01650 
01651 /*! \brief allocate space for new queue member and set fields based on parameters passed */
01652 static struct member *create_queue_member(const char *interface, const char *membername, int penalty, int paused, const char *state_interface)
01653 {
01654    struct member *cur;
01655    
01656    if ((cur = ao2_alloc(sizeof(*cur), NULL))) {
01657       cur->penalty = penalty;
01658       cur->paused = paused;
01659       ast_copy_string(cur->interface, interface, sizeof(cur->interface));
01660       if (!ast_strlen_zero(state_interface))
01661          ast_copy_string(cur->state_interface, state_interface, sizeof(cur->state_interface));
01662       else
01663          ast_copy_string(cur->state_interface, interface, sizeof(cur->state_interface));
01664       if (!ast_strlen_zero(membername))
01665          ast_copy_string(cur->membername, membername, sizeof(cur->membername));
01666       else
01667          ast_copy_string(cur->membername, interface, sizeof(cur->membername));
01668       if (!strchr(cur->interface, '/'))
01669          ast_log(LOG_WARNING, "No location at interface '%s'\n", interface);
01670       if (!strncmp(cur->state_interface, "hint:", 5)) {
01671          char *tmp = ast_strdupa(cur->state_interface), *context = tmp;
01672          char *exten = strsep(&context, "@") + 5;
01673 
01674          ast_copy_string(cur->state_exten, exten, sizeof(cur->state_exten));
01675          ast_copy_string(cur->state_context, S_OR(context, "default"), sizeof(cur->state_context));
01676       }
01677       cur->status = get_queue_member_status(cur);
01678    }
01679 
01680    return cur;
01681 }
01682 
01683 
01684 static int compress_char(const char c)
01685 {
01686    if (c < 32)
01687       return 0;
01688    else if (c > 96)
01689       return c - 64;
01690    else
01691       return c - 32;
01692 }
01693 
01694 static int member_hash_fn(const void *obj, const int flags)
01695 {
01696    const struct member *mem = obj;
01697    const char *chname = strchr(mem->interface, '/');
01698    int ret = 0, i;
01699    if (!chname)
01700       chname = mem->interface;
01701    for (i = 0; i < 5 && chname[i]; i++)
01702       ret += compress_char(chname[i]) << (i * 6);
01703    return ret;
01704 }
01705 
01706 static int member_cmp_fn(void *obj1, void *obj2, int flags)
01707 {
01708    struct member *mem1 = obj1, *mem2 = obj2;
01709    return strcasecmp(mem1->interface, mem2->interface) ? 0 : CMP_MATCH | CMP_STOP;
01710 }
01711 
01712 /*! 
01713  * \brief Initialize Queue default values.
01714  * \note the queue's lock  must be held before executing this function
01715 */
01716 static void init_queue(struct call_queue *q)
01717 {
01718    int i;
01719    struct penalty_rule *pr_iter;
01720 
01721    q->dead = 0;
01722    q->retry = DEFAULT_RETRY;
01723    q->timeout = DEFAULT_TIMEOUT;
01724    q->maxlen = 0;
01725    q->announcefrequency = 0;
01726    q->minannouncefrequency = DEFAULT_MIN_ANNOUNCE_FREQUENCY;
01727    q->announceholdtime = 1;
01728    q->announcepositionlimit = 10; /* Default 10 positions */
01729    q->announceposition = ANNOUNCEPOSITION_YES; /* Default yes */
01730    q->roundingseconds = 0; /* Default - don't announce seconds */
01731    q->servicelevel = 0;
01732    q->ringinuse = 1;
01733    q->setinterfacevar = 0;
01734    q->setqueuevar = 0;
01735    q->setqueueentryvar = 0;
01736    q->autofill = autofill_default;
01737    q->montype = montype_default;
01738    q->monfmt[0] = '\0';
01739    q->reportholdtime = 0;
01740    q->wrapuptime = 0;
01741    q->penaltymemberslimit = 0;
01742    q->joinempty = 0;
01743    q->leavewhenempty = 0;
01744    q->memberdelay = 0;
01745    q->maskmemberstatus = 0;
01746    q->eventwhencalled = 0;
01747    q->weight = 0;
01748    q->timeoutrestart = 0;
01749    q->periodicannouncefrequency = 0;
01750    q->randomperiodicannounce = 0;
01751    q->numperiodicannounce = 0;
01752    q->autopause = QUEUE_AUTOPAUSE_OFF;
01753    q->timeoutpriority = TIMEOUT_PRIORITY_APP;
01754    if (!q->members) {
01755       if (q->strategy == QUEUE_STRATEGY_LINEAR || q->strategy == QUEUE_STRATEGY_RRORDERED)
01756          /* linear strategy depends on order, so we have to place all members in a single bucket */
01757          q->members = ao2_container_alloc(1, member_hash_fn, member_cmp_fn);
01758       else
01759          q->members = ao2_container_alloc(37, member_hash_fn, member_cmp_fn);
01760    }
01761    q->found = 1;
01762 
01763    ast_string_field_set(q, sound_next, "queue-youarenext");
01764    ast_string_field_set(q, sound_thereare, "queue-thereare");
01765    ast_string_field_set(q, sound_calls, "queue-callswaiting");
01766    ast_string_field_set(q, queue_quantity1, "queue-quantity1");
01767    ast_string_field_set(q, queue_quantity2, "queue-quantity2");
01768    ast_string_field_set(q, sound_holdtime, "queue-holdtime");
01769    ast_string_field_set(q, sound_minutes, "queue-minutes");
01770    ast_string_field_set(q, sound_minute, "queue-minute");
01771    ast_string_field_set(q, sound_seconds, "queue-seconds");
01772    ast_string_field_set(q, sound_thanks, "queue-thankyou");
01773    ast_string_field_set(q, sound_reporthold, "queue-reporthold");
01774 
01775    if (!q->sound_periodicannounce[0]) {
01776       q->sound_periodicannounce[0] = ast_str_create(32);
01777    }
01778 
01779    if (q->sound_periodicannounce[0]) {
01780       ast_str_set(&q->sound_periodicannounce[0], 0, "queue-periodic-announce");
01781    }
01782 
01783    for (i = 1; i < MAX_PERIODIC_ANNOUNCEMENTS; i++) {
01784       if (q->sound_periodicannounce[i])
01785          ast_str_set(&q->sound_periodicannounce[i], 0, "%s", "");
01786    }
01787 
01788    while ((pr_iter = AST_LIST_REMOVE_HEAD(&q->rules,list)))
01789       ast_free(pr_iter);
01790 }
01791 
01792 static void clear_queue(struct call_queue *q)
01793 {
01794    q->holdtime = 0;
01795    q->callscompleted = 0;
01796    q->callsabandoned = 0;
01797    q->callscompletedinsl = 0;
01798    q->talktime = 0;
01799 
01800    if (q->members) {
01801       struct member *mem;
01802       struct ao2_iterator mem_iter = ao2_iterator_init(q->members, 0);
01803       while ((mem = ao2_iterator_next(&mem_iter))) {
01804          mem->calls = 0;
01805          mem->lastcall = 0;
01806          ao2_ref(mem, -1);
01807       }
01808       ao2_iterator_destroy(&mem_iter);
01809    }
01810 }
01811 
01812 /*! 
01813  * \brief Change queue penalty by adding rule.
01814  *
01815  * Check rule for errors with time or fomatting, see if rule is relative to rest 
01816  * of queue, iterate list of rules to find correct insertion point, insert and return.
01817  * \retval -1 on failure
01818  * \retval 0 on success 
01819  * \note Call this with the rule_lists locked 
01820 */
01821 static int insert_penaltychange(const char *list_name, const char *content, const int linenum)
01822 {
01823    char *timestr, *maxstr, *minstr, *contentdup;
01824    struct penalty_rule *rule = NULL, *rule_iter;
01825    struct rule_list *rl_iter;
01826    int penaltychangetime, inserted = 0;
01827 
01828    if (!(rule = ast_calloc(1, sizeof(*rule)))) {
01829       return -1;
01830    }
01831 
01832    contentdup = ast_strdupa(content);
01833    
01834    if (!(maxstr = strchr(contentdup, ','))) {
01835       ast_log(LOG_WARNING, "Improperly formatted penaltychange rule at line %d. Ignoring.\n", linenum);
01836       ast_free(rule);
01837       return -1;
01838    }
01839 
01840    *maxstr++ = '\0';
01841    timestr = contentdup;
01842 
01843    if ((penaltychangetime = atoi(timestr)) < 0) {
01844       ast_log(LOG_WARNING, "Improper time parameter specified for penaltychange rule at line %d. Ignoring.\n", linenum);
01845       ast_free(rule);
01846       return -1;
01847    }
01848 
01849    rule->time = penaltychangetime;
01850 
01851    if ((minstr = strchr(maxstr,',')))
01852       *minstr++ = '\0';
01853    
01854    /* The last check will evaluate true if either no penalty change is indicated for a given rule
01855     * OR if a min penalty change is indicated but no max penalty change is */
01856    if (*maxstr == '+' || *maxstr == '-' || *maxstr == '\0') {
01857       rule->max_relative = 1;
01858    }
01859 
01860    rule->max_value = atoi(maxstr);
01861 
01862    if (!ast_strlen_zero(minstr)) {
01863       if (*minstr == '+' || *minstr == '-')
01864          rule->min_relative = 1;
01865       rule->min_value = atoi(minstr);
01866    } else /*there was no minimum specified, so assume this means no change*/
01867       rule->min_relative = 1;
01868 
01869    /*We have the rule made, now we need to insert it where it belongs*/
01870    AST_LIST_TRAVERSE(&rule_lists, rl_iter, list){
01871       if (strcasecmp(rl_iter->name, list_name))
01872          continue;
01873 
01874       AST_LIST_TRAVERSE_SAFE_BEGIN(&rl_iter->rules, rule_iter, list) {
01875          if (rule->time < rule_iter->time) {
01876             AST_LIST_INSERT_BEFORE_CURRENT(rule, list);
01877             inserted = 1;
01878             break;
01879          }
01880       }
01881       AST_LIST_TRAVERSE_SAFE_END;
01882    
01883       if (!inserted) {
01884          AST_LIST_INSERT_TAIL(&rl_iter->rules, rule, list);
01885          inserted = 1;
01886       }
01887 
01888       break;
01889    }
01890 
01891    if (!inserted) {
01892       ast_log(LOG_WARNING, "Unknown rule list name %s; ignoring.\n", list_name);
01893       ast_free(rule);
01894       return -1;
01895    }
01896    return 0;
01897 }
01898 
01899 static void parse_empty_options(const char *value, enum empty_conditions *empty, int joinempty)
01900 {
01901    char *value_copy = ast_strdupa(value);
01902    char *option = NULL;
01903    while ((option = strsep(&value_copy, ","))) {
01904       if (!strcasecmp(option, "paused")) {
01905          *empty |= QUEUE_EMPTY_PAUSED;
01906       } else if (!strcasecmp(option, "penalty")) {
01907          *empty |= QUEUE_EMPTY_PENALTY;
01908       } else if (!strcasecmp(option, "inuse")) {
01909          *empty |= QUEUE_EMPTY_INUSE;
01910       } else if (!strcasecmp(option, "ringing")) {
01911          *empty |= QUEUE_EMPTY_RINGING;
01912       } else if (!strcasecmp(option, "invalid")) {
01913          *empty |= QUEUE_EMPTY_INVALID;
01914       } else if (!strcasecmp(option, "wrapup")) {
01915          *empty |= QUEUE_EMPTY_WRAPUP;
01916       } else if (!strcasecmp(option, "unavailable")) {
01917          *empty |= QUEUE_EMPTY_UNAVAILABLE;
01918       } else if (!strcasecmp(option, "unknown")) {
01919          *empty |= QUEUE_EMPTY_UNKNOWN;
01920       } else if (!strcasecmp(option, "loose")) {
01921          *empty = (QUEUE_EMPTY_PENALTY | QUEUE_EMPTY_INVALID);
01922       } else if (!strcasecmp(option, "strict")) {
01923          *empty = (QUEUE_EMPTY_PENALTY | QUEUE_EMPTY_INVALID | QUEUE_EMPTY_PAUSED | QUEUE_EMPTY_UNAVAILABLE);
01924       } else if ((ast_false(option) && joinempty) || (ast_true(option) && !joinempty)) {
01925          *empty = (QUEUE_EMPTY_PENALTY | QUEUE_EMPTY_INVALID | QUEUE_EMPTY_PAUSED);
01926       } else if ((ast_false(option) && !joinempty) || (ast_true(option) && joinempty)) {
01927          *empty = 0;
01928       } else {
01929          ast_log(LOG_WARNING, "Unknown option %s for '%s'\n", option, joinempty ? "joinempty" : "leavewhenempty");
01930       }
01931    }
01932 }
01933 
01934 /*! \brief Configure a queue parameter.
01935  * 
01936  * The failunknown flag is set for config files (and static realtime) to show
01937  * errors for unknown parameters. It is cleared for dynamic realtime to allow
01938  *  extra fields in the tables.
01939  * \note For error reporting, line number is passed for .conf static configuration,
01940  * for Realtime queues, linenum is -1.
01941 */
01942 static void queue_set_param(struct call_queue *q, const char *param, const char *val, int linenum, int failunknown)
01943 {
01944    if (!strcasecmp(param, "musicclass") || 
01945       !strcasecmp(param, "music") || !strcasecmp(param, "musiconhold")) {
01946       ast_string_field_set(q, moh, val);
01947    } else if (!strcasecmp(param, "announce")) {
01948       ast_string_field_set(q, announce, val);
01949    } else if (!strcasecmp(param, "context")) {
01950       ast_string_field_set(q, context, val);
01951    } else if (!strcasecmp(param, "timeout")) {
01952       q->timeout = atoi(val);
01953       if (q->timeout < 0)
01954          q->timeout = DEFAULT_TIMEOUT;
01955    } else if (!strcasecmp(param, "ringinuse")) {
01956       q->ringinuse = ast_true(val);
01957    } else if (!strcasecmp(param, "setinterfacevar")) {
01958       q->setinterfacevar = ast_true(val);
01959    } else if (!strcasecmp(param, "setqueuevar")) {
01960       q->setqueuevar = ast_true(val);
01961    } else if (!strcasecmp(param, "setqueueentryvar")) {
01962       q->setqueueentryvar = ast_true(val);
01963    } else if (!strcasecmp(param, "monitor-format")) {
01964       ast_copy_string(q->monfmt, val, sizeof(q->monfmt));
01965    } else if (!strcasecmp(param, "membermacro")) {
01966       ast_string_field_set(q, membermacro, val);
01967    } else if (!strcasecmp(param, "membergosub")) {
01968       ast_string_field_set(q, membergosub, val);
01969    } else if (!strcasecmp(param, "queue-youarenext")) {
01970       ast_string_field_set(q, sound_next, val);
01971    } else if (!strcasecmp(param, "queue-thereare")) {
01972       ast_string_field_set(q, sound_thereare, val);
01973    } else if (!strcasecmp(param, "queue-callswaiting")) {
01974       ast_string_field_set(q, sound_calls, val);
01975    } else if (!strcasecmp(param, "queue-quantity1")) {
01976       ast_string_field_set(q, queue_quantity1, val);
01977    } else if (!strcasecmp(param, "queue-quantity2")) {
01978       ast_string_field_set(q, queue_quantity2, val);
01979    } else if (!strcasecmp(param, "queue-holdtime")) {
01980       ast_string_field_set(q, sound_holdtime, val);
01981    } else if (!strcasecmp(param, "queue-minutes")) {
01982       ast_string_field_set(q, sound_minutes, val);
01983    } else if (!strcasecmp(param, "queue-minute")) {
01984       ast_string_field_set(q, sound_minute, val);
01985    } else if (!strcasecmp(param, "queue-seconds")) {
01986       ast_string_field_set(q, sound_seconds, val);
01987    } else if (!strcasecmp(param, "queue-thankyou")) {
01988       ast_string_field_set(q, sound_thanks, val);
01989    } else if (!strcasecmp(param, "queue-callerannounce")) {
01990       ast_string_field_set(q, sound_callerannounce, val);
01991    } else if (!strcasecmp(param, "queue-reporthold")) {
01992       ast_string_field_set(q, sound_reporthold, val);
01993    } else if (!strcasecmp(param, "announce-frequency")) {
01994       q->announcefrequency = atoi(val);
01995    } else if (!strcasecmp(param, "min-announce-frequency")) {
01996       q->minannouncefrequency = atoi(val);
01997       ast_debug(1, "%s=%s for queue '%s'\n", param, val, q->name);
01998    } else if (!strcasecmp(param, "announce-round-seconds")) {
01999       q->roundingseconds = atoi(val);
02000       /* Rounding to any other values just doesn't make sense... */
02001       if (!(q->roundingseconds == 0 || q->roundingseconds == 5 || q->roundingseconds == 10
02002          || q->roundingseconds == 15 || q->roundingseconds == 20 || q->roundingseconds == 30)) {
02003          if (linenum >= 0) {
02004             ast_log(LOG_WARNING, "'%s' isn't a valid value for %s "
02005                "using 0 instead for queue '%s' at line %d of queues.conf\n",
02006                val, param, q->name, linenum);
02007          } else {
02008             ast_log(LOG_WARNING, "'%s' isn't a valid value for %s "
02009                "using 0 instead for queue '%s'\n", val, param, q->name);
02010          }
02011          q->roundingseconds=0;
02012       }
02013    } else if (!strcasecmp(param, "announce-holdtime")) {
02014       if (!strcasecmp(val, "once"))
02015          q->announceholdtime = ANNOUNCEHOLDTIME_ONCE;
02016       else if (ast_true(val))
02017          q->announceholdtime = ANNOUNCEHOLDTIME_ALWAYS;
02018       else
02019          q->announceholdtime = 0;
02020    } else if (!strcasecmp(param, "announce-position")) {
02021       if (!strcasecmp(val, "limit"))
02022          q->announceposition = ANNOUNCEPOSITION_LIMIT;
02023       else if (!strcasecmp(val, "more"))
02024          q->announceposition = ANNOUNCEPOSITION_MORE_THAN;
02025       else if (ast_true(val))
02026          q->announceposition = ANNOUNCEPOSITION_YES;
02027       else
02028          q->announceposition = ANNOUNCEPOSITION_NO;
02029    } else if (!strcasecmp(param, "announce-position-limit")) {
02030       q->announcepositionlimit = atoi(val);
02031    } else if (!strcasecmp(param, "periodic-announce")) {
02032       if (strchr(val, ',')) {
02033          char *s, *buf = ast_strdupa(val);
02034          unsigned int i = 0;
02035 
02036          while ((s = strsep(&buf, ",|"))) {
02037             if (!q->sound_periodicannounce[i])
02038                q->sound_periodicannounce[i] = ast_str_create(16);
02039             ast_str_set(&q->sound_periodicannounce[i], 0, "%s", s);
02040             i++;
02041             if (i == MAX_PERIODIC_ANNOUNCEMENTS)
02042                break;
02043          }
02044          q->numperiodicannounce = i;
02045       } else {
02046          ast_str_set(&q->sound_periodicannounce[0], 0, "%s", val);
02047          q->numperiodicannounce = 1;
02048       }
02049    } else if (!strcasecmp(param, "periodic-announce-frequency")) {
02050       q->periodicannouncefrequency = atoi(val);
02051    } else if (!strcasecmp(param, "relative-periodic-announce")) {
02052       q->relativeperiodicannounce = ast_true(val);
02053    } else if (!strcasecmp(param, "random-periodic-announce")) {
02054       q->randomperiodicannounce = ast_true(val);
02055    } else if (!strcasecmp(param, "retry")) {
02056       q->retry = atoi(val);
02057       if (q->retry <= 0)
02058          q->retry = DEFAULT_RETRY;
02059    } else if (!strcasecmp(param, "wrapuptime")) {
02060       q->wrapuptime = atoi(val);
02061    } else if (!strcasecmp(param, "penaltymemberslimit")) {
02062       if ((sscanf(val, "%10d", &q->penaltymemberslimit) != 1)) {
02063          q->penaltymemberslimit = 0;
02064       }
02065    } else if (!strcasecmp(param, "autofill")) {
02066       q->autofill = ast_true(val);
02067    } else if (!strcasecmp(param, "monitor-type")) {
02068       if (!strcasecmp(val, "mixmonitor"))
02069          q->montype = 1;
02070    } else if (!strcasecmp(param, "autopause")) {
02071       q->autopause = autopause2int(val);
02072    } else if (!strcasecmp(param, "maxlen")) {
02073       q->maxlen = atoi(val);
02074       if (q->maxlen < 0)
02075          q->maxlen = 0;
02076    } else if (!strcasecmp(param, "servicelevel")) {
02077       q->servicelevel= atoi(val);
02078    } else if (!strcasecmp(param, "strategy")) {
02079       int strategy;
02080 
02081       /* We are a static queue and already have set this, no need to do it again */
02082       if (failunknown) {
02083          return;
02084       }
02085       strategy = strat2int(val);
02086       if (strategy < 0) {
02087          ast_log(LOG_WARNING, "'%s' isn't a valid strategy for queue '%s', using ringall instead\n",
02088             val, q->name);
02089          q->strategy = QUEUE_STRATEGY_RINGALL;
02090       }
02091       if (strategy == q->strategy) {
02092          return;
02093       }
02094       if (strategy == QUEUE_STRATEGY_LINEAR) {
02095          ast_log(LOG_WARNING, "Changing to the linear strategy currently requires asterisk to be restarted.\n");
02096          return;
02097       }
02098       q->strategy = strategy;
02099    } else if (!strcasecmp(param, "joinempty")) {
02100       parse_empty_options(val, &q->joinempty, 1);
02101    } else if (!strcasecmp(param, "leavewhenempty")) {
02102       parse_empty_options(val, &q->leavewhenempty, 0);
02103    } else if (!strcasecmp(param, "eventmemberstatus")) {
02104       q->maskmemberstatus = !ast_true(val);
02105    } else if (!strcasecmp(param, "eventwhencalled")) {
02106       if (!strcasecmp(val, "vars")) {
02107          q->eventwhencalled = QUEUE_EVENT_VARIABLES;
02108       } else {
02109          q->eventwhencalled = ast_true(val) ? 1 : 0;
02110       }
02111    } else if (!strcasecmp(param, "reportholdtime")) {
02112       q->reportholdtime = ast_true(val);
02113    } else if (!strcasecmp(param, "memberdelay")) {
02114       q->memberdelay = atoi(val);
02115    } else if (!strcasecmp(param, "weight")) {
02116       q->weight = atoi(val);
02117    } else if (!strcasecmp(param, "timeoutrestart")) {
02118       q->timeoutrestart = ast_true(val);
02119    } else if (!strcasecmp(param, "defaultrule")) {
02120       ast_string_field_set(q, defaultrule, val);
02121    } else if (!strcasecmp(param, "timeoutpriority")) {
02122       if (!strcasecmp(val, "conf")) {
02123          q->timeoutpriority = TIMEOUT_PRIORITY_CONF;
02124       } else {
02125          q->timeoutpriority = TIMEOUT_PRIORITY_APP;
02126       }
02127    } else if (failunknown) {
02128       if (linenum >= 0) {
02129          ast_log(LOG_WARNING, "Unknown keyword in queue '%s': %s at line %d of queues.conf\n",
02130             q->name, param, linenum);
02131       } else {
02132          ast_log(LOG_WARNING, "Unknown keyword in queue '%s': %s\n", q->name, param);
02133       }
02134    }
02135 }
02136 
02137 /*! \internal
02138  * \brief If adding a single new member to a queue, use this function instead of ao2_linking.
02139  *        This adds round robin queue position data for a fresh member as well as links it.
02140  * \param queue Which queue the member is being added to
02141  * \param mem Which member is being added to the queue
02142  */
02143 static void member_add_to_queue(struct call_queue *queue, struct member *mem)
02144 {
02145    ao2_lock(queue->members);
02146    mem->queuepos = ao2_container_count(queue->members);
02147    ao2_link(queue->members, mem);
02148    ao2_unlock(queue->members);
02149 }
02150 
02151 /*! \internal
02152  * \brief If removing a single member from a queue, use this function instead of ao2_unlinking.
02153  *        This will perform round robin queue position reordering for the remaining members.
02154  * \param queue Which queue the member is being removed from
02155  * \param member Which member is being removed from the queue
02156  */
02157 static void member_remove_from_queue(struct call_queue *queue, struct member *mem)
02158 {
02159    ao2_lock(queue->members);
02160    queue_member_follower_removal(queue, mem);
02161    ao2_unlink(queue->members, mem);
02162    ao2_unlock(queue->members);
02163 }
02164 
02165 /*!
02166  * \brief Find rt member record to update otherwise create one.
02167  *
02168  * Search for member in queue, if found update penalty/paused state,
02169  * if no member exists create one flag it as a RT member and add to queue member list. 
02170 */
02171 static void rt_handle_member_record(struct call_queue *q, char *interface, const char *rt_uniqueid, const char *membername, const char *penalty_str, const char *paused_str, const char* state_interface)
02172 {
02173    struct member *m;
02174    struct ao2_iterator mem_iter;
02175    int penalty = 0;
02176    int paused  = 0;
02177    int found = 0;
02178 
02179    if (ast_strlen_zero(rt_uniqueid)) {
02180       ast_log(LOG_WARNING, "Realtime field uniqueid is empty for member %s\n", S_OR(membername, "NULL"));
02181       return;
02182    }
02183 
02184    if (penalty_str) {
02185       penalty = atoi(penalty_str);
02186       if (penalty < 0)
02187          penalty = 0;
02188    }
02189 
02190    if (paused_str) {
02191       paused = atoi(paused_str);
02192       if (paused < 0)
02193          paused = 0;
02194    }
02195 
02196    /* Find member by realtime uniqueid and update */
02197    mem_iter = ao2_iterator_init(q->members, 0);
02198    while ((m = ao2_iterator_next(&mem_iter))) {
02199       if (!strcasecmp(m->rt_uniqueid, rt_uniqueid)) {
02200          m->dead = 0;   /* Do not delete this one. */
02201          ast_copy_string(m->rt_uniqueid, rt_uniqueid, sizeof(m->rt_uniqueid));
02202          if (paused_str)
02203             m->paused = paused;
02204          if (strcasecmp(state_interface, m->state_interface)) {
02205             ast_copy_string(m->state_interface, state_interface, sizeof(m->state_interface));
02206          }     
02207          m->penalty = penalty;
02208          found = 1;
02209          ao2_ref(m, -1);
02210          break;
02211       }
02212       ao2_ref(m, -1);
02213    }
02214    ao2_iterator_destroy(&mem_iter);
02215 
02216    /* Create a new member */
02217    if (!found) {
02218       if ((m = create_queue_member(interface, membername, penalty, paused, state_interface))) {
02219          m->dead = 0;
02220          m->realtime = 1;
02221          ast_copy_string(m->rt_uniqueid, rt_uniqueid, sizeof(m->rt_uniqueid));
02222          ast_queue_log(q->name, "REALTIME", m->interface, "ADDMEMBER", "%s", paused ? "PAUSED" : "");
02223          member_add_to_queue(q, m);
02224          ao2_ref(m, -1);
02225          m = NULL;
02226       }
02227    }
02228 }
02229 
02230 /*! \brief Iterate through queue's member list and delete them */
02231 static void free_members(struct call_queue *q, int all)
02232 {
02233    /* Free non-dynamic members */
02234    struct member *cur;
02235    struct ao2_iterator mem_iter = ao2_iterator_init(q->members, 0);
02236 
02237    while ((cur = ao2_iterator_next(&mem_iter))) {
02238       if (all || !cur->dynamic) {
02239          member_remove_from_queue(q, cur);
02240       }
02241       ao2_ref(cur, -1);
02242    }
02243    ao2_iterator_destroy(&mem_iter);
02244 }
02245 
02246 /*! \brief Free queue's member list then its string fields */
02247 static void destroy_queue(void *obj)
02248 {
02249    struct call_queue *q = obj;
02250    int i;
02251 
02252    free_members(q, 1);
02253    ast_string_field_free_memory(q);
02254    for (i = 0; i < MAX_PERIODIC_ANNOUNCEMENTS; i++) {
02255       if (q->sound_periodicannounce[i])
02256          free(q->sound_periodicannounce[i]);
02257    }
02258    ao2_ref(q->members, -1);
02259 }
02260 
02261 static struct call_queue *alloc_queue(const char *queuename)
02262 {
02263    struct call_queue *q;
02264 
02265    if ((q = ao2_t_alloc(sizeof(*q), destroy_queue, "Allocate queue"))) {
02266       if (ast_string_field_init(q, 64)) {
02267          queue_t_unref(q, "String field allocation failed");
02268          return NULL;
02269       }
02270       ast_string_field_set(q, name, queuename);
02271    }
02272    return q;
02273 }
02274 
02275 /*!
02276  * \brief Reload a single queue via realtime.
02277  *
02278  * Check for statically defined queue first, check if deleted RT queue,
02279  * check for new RT queue, if queue vars are not defined init them with defaults.
02280  * reload RT queue vars, set RT queue members dead and reload them, return finished queue.
02281  * \retval the queue, 
02282  * \retval NULL if it doesn't exist.
02283  * \note Should be called with the "queues" container locked. 
02284 */
02285 static struct call_queue *find_queue_by_name_rt(const char *queuename, struct ast_variable *queue_vars, struct ast_config *member_config)
02286 {
02287    struct ast_variable *v;
02288    struct call_queue *q, tmpq = {
02289       .name = queuename,   
02290    };
02291    struct member *m;
02292    struct ao2_iterator mem_iter;
02293    char *interface = NULL;
02294    const char *tmp_name;
02295    char *tmp;
02296    char tmpbuf[64];  /* Must be longer than the longest queue param name. */
02297 
02298    /* Static queues override realtime. */
02299    if ((q = ao2_t_find(queues, &tmpq, OBJ_POINTER, "Check if static queue exists"))) {
02300       ao2_lock(q);
02301       if (!q->realtime) {
02302          if (q->dead) {
02303             ao2_unlock(q);
02304             queue_t_unref(q, "Queue is dead; can't return it");
02305             return NULL;
02306          } else {
02307             ast_log(LOG_WARNING, "Static queue '%s' already exists. Not loading from realtime\n", q->name);
02308             ao2_unlock(q);
02309             return q;
02310          }
02311       }
02312    } else if (!member_config)
02313       /* Not found in the list, and it's not realtime ... */
02314       return NULL;
02315 
02316    /* Check if queue is defined in realtime. */
02317    if (!queue_vars) {
02318       /* Delete queue from in-core list if it has been deleted in realtime. */
02319       if (q) {
02320          /*! \note Hmm, can't seem to distinguish a DB failure from a not
02321             found condition... So we might delete an in-core queue
02322             in case of DB failure. */
02323          ast_debug(1, "Queue %s not found in realtime.\n", queuename);
02324 
02325          q->dead = 1;
02326          /* Delete if unused (else will be deleted when last caller leaves). */
02327          queues_t_unlink(queues, q, "Unused; removing from container");
02328          ao2_unlock(q);
02329          queue_t_unref(q, "Queue is dead; can't return it");
02330       }
02331       return NULL;
02332    }
02333 
02334    /* Create a new queue if an in-core entry does not exist yet. */
02335    if (!q) {
02336       struct ast_variable *tmpvar = NULL;
02337       if (!(q = alloc_queue(queuename)))
02338          return NULL;
02339       ao2_lock(q);
02340       clear_queue(q);
02341       q->realtime = 1;
02342       /*Before we initialize the queue, we need to set the strategy, so that linear strategy
02343        * will allocate the members properly
02344        */
02345       for (tmpvar = queue_vars; tmpvar; tmpvar = tmpvar->next) {
02346          if (!strcasecmp(tmpvar->name, "strategy")) {
02347             q->strategy = strat2int(tmpvar->value);
02348             if (q->strategy < 0) {
02349                ast_log(LOG_WARNING, "'%s' isn't a valid strategy for queue '%s', using ringall instead\n",
02350                tmpvar->value, q->name);
02351                q->strategy = QUEUE_STRATEGY_RINGALL;
02352             }
02353             break;
02354          }
02355       }
02356       /* We traversed all variables and didn't find a strategy */
02357       if (!tmpvar)
02358          q->strategy = QUEUE_STRATEGY_RINGALL;
02359       queues_t_link(queues, q, "Add queue to container");
02360    }
02361    init_queue(q);    /* Ensure defaults for all parameters not set explicitly. */
02362 
02363    memset(tmpbuf, 0, sizeof(tmpbuf));
02364    for (v = queue_vars; v; v = v->next) {
02365       /* Convert to dashes `-' from underscores `_' as the latter are more SQL friendly. */
02366       if (strchr(v->name, '_')) {
02367          ast_copy_string(tmpbuf, v->name, sizeof(tmpbuf));
02368          tmp_name = tmpbuf;
02369          tmp = tmpbuf;
02370          while ((tmp = strchr(tmp, '_')))
02371             *tmp++ = '-';
02372       } else
02373          tmp_name = v->name;
02374 
02375       /* NULL values don't get returned from realtime; blank values should
02376        * still get set.  If someone doesn't want a value to be set, they
02377        * should set the realtime column to NULL, not blank. */
02378       queue_set_param(q, tmp_name, v->value, -1, 0);
02379    }
02380 
02381    /* Temporarily set realtime members dead so we can detect deleted ones. */
02382    mem_iter = ao2_iterator_init(q->members, 0);
02383    while ((m = ao2_iterator_next(&mem_iter))) {
02384       if (m->realtime)
02385          m->dead = 1;
02386       ao2_ref(m, -1);
02387    }
02388    ao2_iterator_destroy(&mem_iter);
02389 
02390    while ((interface = ast_category_browse(member_config, interface))) {
02391       rt_handle_member_record(q, interface,
02392          ast_variable_retrieve(member_config, interface, "uniqueid"),
02393          S_OR(ast_variable_retrieve(member_config, interface, "membername"),interface),
02394          ast_variable_retrieve(member_config, interface, "penalty"),
02395          ast_variable_retrieve(member_config, interface, "paused"),
02396          S_OR(ast_variable_retrieve(member_config, interface, "state_interface"),interface));
02397    }
02398 
02399    /* Delete all realtime members that have been deleted in DB. */
02400    mem_iter = ao2_iterator_init(q->members, 0);
02401    while ((m = ao2_iterator_next(&mem_iter))) {
02402       if (m->dead) {
02403          ast_queue_log(q->name, "REALTIME", m->interface, "REMOVEMEMBER", "%s", "");
02404          member_remove_from_queue(q, m);
02405       }
02406       ao2_ref(m, -1);
02407    }
02408    ao2_iterator_destroy(&mem_iter);
02409 
02410    ao2_unlock(q);
02411 
02412    return q;
02413 }
02414 
02415 /*! \note Returns a reference to the loaded realtime queue. */
02416 static struct call_queue *load_realtime_queue(const char *queuename)
02417 {
02418    struct ast_variable *queue_vars;
02419    struct ast_config *member_config = NULL;
02420    struct call_queue *q = NULL, tmpq = {
02421       .name = queuename,   
02422    };
02423    int prev_weight = 0;
02424 
02425    /* Find the queue in the in-core list first. */
02426    q = ao2_t_find(queues, &tmpq, OBJ_POINTER, "Look for queue in memory first");
02427 
02428    if (!q || q->realtime) {
02429       /*! \note Load from realtime before taking the "queues" container lock, to avoid blocking all
02430          queue operations while waiting for the DB.
02431 
02432          This will be two separate database transactions, so we might
02433          see queue parameters as they were before another process
02434          changed the queue and member list as it was after the change.
02435          Thus we might see an empty member list when a queue is
02436          deleted. In practise, this is unlikely to cause a problem. */
02437 
02438       queue_vars = ast_load_realtime("queues", "name", queuename, SENTINEL);
02439       if (queue_vars) {
02440          member_config = ast_load_realtime_multientry("queue_members", "interface LIKE", "%", "queue_name", queuename, SENTINEL);
02441          if (!member_config) {
02442             ast_debug(1, "No queue_members defined in config extconfig.conf\n");
02443             member_config = ast_config_new();
02444          }
02445       }
02446       if (q) {
02447          prev_weight = q->weight ? 1 : 0;
02448          queue_t_unref(q, "Need to find realtime queue");
02449       }
02450 
02451       q = find_queue_by_name_rt(queuename, queue_vars, member_config);
02452       ast_config_destroy(member_config);
02453       ast_variables_destroy(queue_vars);
02454 
02455       /* update the use_weight value if the queue's has gained or lost a weight */
02456       if (q) {
02457          if (!q->weight && prev_weight) {
02458             ast_atomic_fetchadd_int(&use_weight, -1);
02459          }
02460          if (q->weight && !prev_weight) {
02461             ast_atomic_fetchadd_int(&use_weight, +1);
02462          }
02463       }
02464       /* Other cases will end up with the proper value for use_weight */
02465    } else {
02466       update_realtime_members(q);
02467    }
02468    return q;
02469 }
02470 
02471 static int update_realtime_member_field(struct member *mem, const char *queue_name, const char *field, const char *value)
02472 {
02473    int ret = -1;
02474 
02475    if (ast_strlen_zero(mem->rt_uniqueid))
02476       return ret;
02477 
02478    if ((ast_update_realtime("queue_members", "uniqueid", mem->rt_uniqueid, field, value, SENTINEL)) > 0)
02479       ret = 0;
02480 
02481    return ret;
02482 }
02483 
02484 
02485 static void update_realtime_members(struct call_queue *q)
02486 {
02487    struct ast_config *member_config = NULL;
02488    struct member *m;
02489    char *interface = NULL;
02490    struct ao2_iterator mem_iter;
02491 
02492    if (!(member_config = ast_load_realtime_multientry("queue_members", "interface LIKE", "%", "queue_name", q->name , SENTINEL))) {
02493       /* This queue doesn't have realtime members. If the queue still has any realtime
02494        * members in memory, they need to be removed.
02495        */
02496       ao2_lock(q);
02497       mem_iter = ao2_iterator_init(q->members, 0);
02498       while ((m = ao2_iterator_next(&mem_iter))) {
02499          if (m->realtime) {
02500             member_remove_from_queue(q, m);
02501          }
02502          ao2_ref(m, -1);
02503       }
02504       ast_debug(3, "Queue %s has no realtime members defined. No need for update\n", q->name);
02505       ao2_unlock(q);
02506       return;
02507    }
02508 
02509    ao2_lock(q);
02510 
02511    /* Temporarily set realtime  members dead so we can detect deleted ones.*/
02512    mem_iter = ao2_iterator_init(q->members, 0);
02513    while ((m = ao2_iterator_next(&mem_iter))) {
02514       if (m->realtime)
02515          m->dead = 1;
02516       ao2_ref(m, -1);
02517    }
02518    ao2_iterator_destroy(&mem_iter);
02519 
02520    while ((interface = ast_category_browse(member_config, interface))) {
02521       rt_handle_member_record(q, interface,
02522          ast_variable_retrieve(member_config, interface, "uniqueid"),
02523          S_OR(ast_variable_retrieve(member_config, interface, "membername"), interface),
02524          ast_variable_retrieve(member_config, interface, "penalty"),
02525          ast_variable_retrieve(member_config, interface, "paused"),
02526          S_OR(ast_variable_retrieve(member_config, interface, "state_interface"), interface));
02527    }
02528 
02529    /* Delete all realtime members that have been deleted in DB. */
02530    mem_iter = ao2_iterator_init(q->members, 0);
02531    while ((m = ao2_iterator_next(&mem_iter))) {
02532       if (m->dead) {
02533          ast_queue_log(q->name, "REALTIME", m->interface, "REMOVEMEMBER", "%s", "");
02534          member_remove_from_queue(q, m);
02535       }
02536       ao2_ref(m, -1);
02537    }
02538    ao2_iterator_destroy(&mem_iter);
02539    ao2_unlock(q);
02540    ast_config_destroy(member_config);
02541 }
02542 
02543 static int join_queue(char *queuename, struct queue_ent *qe, enum queue_result *reason, int position)
02544 {
02545    struct call_queue *q;
02546    struct queue_ent *cur, *prev = NULL;
02547    int res = -1;
02548    int pos = 0;
02549    int inserted = 0;
02550 
02551    if (!(q = load_realtime_queue(queuename)))
02552       return res;
02553 
02554    ao2_lock(q);
02555 
02556    /* This is our one */
02557    if (q->joinempty) {
02558       int status = 0;
02559       if ((status = get_member_status(q, qe->max_penalty, qe->min_penalty, q->joinempty))) {
02560          *reason = QUEUE_JOINEMPTY;
02561          ao2_unlock(q);
02562          queue_t_unref(q, "Done with realtime queue");
02563          return res;
02564       }
02565    }
02566    if (*reason == QUEUE_UNKNOWN && q->maxlen && (q->count >= q->maxlen))
02567       *reason = QUEUE_FULL;
02568    else if (*reason == QUEUE_UNKNOWN) {
02569       /* There's space for us, put us at the right position inside
02570        * the queue.
02571        * Take into account the priority of the calling user */
02572       inserted = 0;
02573       prev = NULL;
02574       cur = q->head;
02575       while (cur) {
02576          /* We have higher priority than the current user, enter
02577           * before him, after all the other users with priority
02578           * higher or equal to our priority. */
02579          if ((!inserted) && (qe->prio > cur->prio)) {
02580             insert_entry(q, prev, qe, &pos);
02581             inserted = 1;
02582          }
02583          /* <= is necessary for the position comparison because it may not be possible to enter
02584           * at our desired position since higher-priority callers may have taken the position we want
02585           */
02586          if (!inserted && (qe->prio >= cur->prio) && position && (position <= pos + 1)) {
02587             insert_entry(q, prev, qe, &pos);
02588             inserted = 1;
02589             /*pos is incremented inside insert_entry, so don't need to add 1 here*/
02590             if (position < pos) {
02591                ast_log(LOG_NOTICE, "Asked to be inserted at position %d but forced into position %d due to higher priority callers\n", position, pos);
02592             }
02593          }
02594          cur->pos = ++pos;
02595          prev = cur;
02596          cur = cur->next;
02597       }
02598       /* No luck, join at the end of the queue */
02599       if (!inserted)
02600          insert_entry(q, prev, qe, &pos);
02601       ast_copy_string(qe->moh, q->moh, sizeof(qe->moh));
02602       ast_copy_string(qe->announce, q->announce, sizeof(qe->announce));
02603       ast_copy_string(qe->context, q->context, sizeof(qe->context));
02604       q->count++;
02605       res = 0;
02606       ast_manager_event(qe->chan, EVENT_FLAG_CALL, "Join",
02607          "Channel: %s\r\n"
02608          "CallerIDNum: %s\r\n"
02609          "CallerIDName: %s\r\n"
02610          "ConnectedLineNum: %s\r\n"
02611          "ConnectedLineName: %s\r\n"
02612          "Queue: %s\r\n"
02613          "Position: %d\r\n"
02614          "Count: %d\r\n"
02615          "Uniqueid: %s\r\n",
02616          qe->chan->name,
02617          S_COR(qe->chan->caller.id.number.valid, qe->chan->caller.id.number.str, "unknown"),/* XXX somewhere else it is <unknown> */
02618          S_COR(qe->chan->caller.id.name.valid, qe->chan->caller.id.name.str, "unknown"),
02619          S_COR(qe->chan->connected.id.number.valid, qe->chan->connected.id.number.str, "unknown"),/* XXX somewhere else it is <unknown> */
02620          S_COR(qe->chan->connected.id.name.valid, qe->chan->connected.id.name.str, "unknown"),
02621          q->name, qe->pos, q->count, qe->chan->uniqueid );
02622       ast_debug(1, "Queue '%s' Join, Channel '%s', Position '%d'\n", q->name, qe->chan->name, qe->pos );
02623    }
02624    ao2_unlock(q);
02625    queue_t_unref(q, "Done with realtime queue");
02626 
02627    return res;
02628 }
02629 
02630 static int play_file(struct ast_channel *chan, const char *filename)
02631 {
02632    int res;
02633 
02634    if (ast_strlen_zero(filename)) {
02635       return 0;
02636    }
02637 
02638    if (!ast_fileexists(filename, NULL, chan->language)) {
02639       return 0;
02640    }
02641 
02642    ast_stopstream(chan);
02643 
02644    res = ast_streamfile(chan, filename, chan->language);
02645    if (!res)
02646       res = ast_waitstream(chan, AST_DIGIT_ANY);
02647 
02648    ast_stopstream(chan);
02649 
02650    return res;
02651 }
02652 
02653 /*!
02654  * \brief Check for valid exit from queue via goto
02655  * \retval 0 if failure
02656  * \retval 1 if successful
02657 */
02658 static int valid_exit(struct queue_ent *qe, char digit)
02659 {
02660    int digitlen = strlen(qe->digits);
02661 
02662    /* Prevent possible buffer overflow */
02663    if (digitlen < sizeof(qe->digits) - 2) {
02664       qe->digits[digitlen] = digit;
02665       qe->digits[digitlen + 1] = '\0';
02666    } else {
02667       qe->digits[0] = '\0';
02668       return 0;
02669    }
02670 
02671    /* If there's no context to goto, short-circuit */
02672    if (ast_strlen_zero(qe->context))
02673       return 0;
02674 
02675    /* If the extension is bad, then reset the digits to blank */
02676    if (!ast_canmatch_extension(qe->chan, qe->context, qe->digits, 1,
02677       S_COR(qe->chan->caller.id.number.valid, qe->chan->caller.id.number.str, NULL))) {
02678       qe->digits[0] = '\0';
02679       return 0;
02680    }
02681 
02682    /* We have an exact match */
02683    if (!ast_goto_if_exists(qe->chan, qe->context, qe->digits, 1)) {
02684       qe->valid_digits = 1;
02685       /* Return 1 on a successful goto */
02686       return 1;
02687    }
02688 
02689    return 0;
02690 }
02691 
02692 static int say_position(struct queue_ent *qe, int ringing)
02693 {
02694    int res = 0, avgholdmins, avgholdsecs, announceposition = 0;
02695    int say_thanks = 1;
02696    time_t now;
02697 
02698    /* Let minannouncefrequency seconds pass between the start of each position announcement */
02699    time(&now);
02700    if ((now - qe->last_pos) < qe->parent->minannouncefrequency)
02701       return 0;
02702 
02703    /* If either our position has changed, or we are over the freq timer, say position */
02704    if ((qe->last_pos_said == qe->pos) && ((now - qe->last_pos) < qe->parent->announcefrequency))
02705       return 0;
02706 
02707    if (ringing) {
02708       ast_indicate(qe->chan,-1);
02709    } else {
02710       ast_moh_stop(qe->chan);
02711    }
02712 
02713    if (qe->parent->announceposition == ANNOUNCEPOSITION_YES ||
02714       qe->parent->announceposition == ANNOUNCEPOSITION_MORE_THAN ||
02715       (qe->parent->announceposition == ANNOUNCEPOSITION_LIMIT &&
02716       qe->pos <= qe->parent->announcepositionlimit))
02717          announceposition = 1;
02718 
02719 
02720    if (announceposition == 1) {
02721       /* Say we're next, if we are */
02722       if (qe->pos == 1) {
02723          res = play_file(qe->chan, qe->parent->sound_next);
02724          if (res)
02725             goto playout;
02726          else
02727             goto posout;
02728       } else {
02729          if (qe->parent->announceposition == ANNOUNCEPOSITION_MORE_THAN && qe->pos > qe->parent->announcepositionlimit){
02730             /* More than Case*/
02731             res = play_file(qe->chan, qe->parent->queue_quantity1);
02732             if (res)
02733                goto playout;
02734             res = ast_say_number(qe->chan, qe->parent->announcepositionlimit, AST_DIGIT_ANY, qe->chan->language, NULL); /* Needs gender */
02735             if (res)
02736                goto playout;
02737          } else {
02738             /* Normal Case */
02739             res = play_file(qe->chan, qe->parent->sound_thereare);
02740             if (res)
02741                goto playout;
02742             res = ast_say_number(qe->chan, qe->pos, AST_DIGIT_ANY, qe->chan->language, NULL); /* Needs gender */
02743             if (res)
02744                goto playout;
02745          }
02746          if (qe->parent->announceposition == ANNOUNCEPOSITION_MORE_THAN && qe->pos > qe->parent->announcepositionlimit){
02747             /* More than Case*/
02748             res = play_file(qe->chan, qe->parent->queue_quantity2);
02749             if (res)
02750                goto playout;
02751          } else {
02752             res = play_file(qe->chan, qe->parent->sound_calls);
02753             if (res)
02754                goto playout;
02755          }
02756       }
02757    }
02758    /* Round hold time to nearest minute */
02759    avgholdmins = abs(((qe->parent->holdtime + 30) - (now - qe->start)) / 60);
02760 
02761    /* If they have specified a rounding then round the seconds as well */
02762    if (qe->parent->roundingseconds) {
02763       avgholdsecs = (abs(((qe->parent->holdtime + 30) - (now - qe->start))) - 60 * avgholdmins) / qe->parent->roundingseconds;
02764       avgholdsecs *= qe->parent->roundingseconds;
02765    } else {
02766       avgholdsecs = 0;
02767    }
02768 
02769    ast_verb(3, "Hold time for %s is %d minute(s) %d seconds\n", qe->parent->name, avgholdmins, avgholdsecs);
02770 
02771    /* If the hold time is >1 min, if it's enabled, and if it's not
02772       supposed to be only once and we have already said it, say it */
02773     if ((avgholdmins+avgholdsecs) > 0 && qe->parent->announceholdtime &&
02774         ((qe->parent->announceholdtime == ANNOUNCEHOLDTIME_ONCE && !qe->last_pos) ||
02775         !(qe->parent->announceholdtime == ANNOUNCEHOLDTIME_ONCE))) {
02776       res = play_file(qe->chan, qe->parent->sound_holdtime);
02777       if (res)
02778          goto playout;
02779 
02780       if (avgholdmins >= 1) {
02781          res = ast_say_number(qe->chan, avgholdmins, AST_DIGIT_ANY, qe->chan->language, NULL);
02782          if (res)
02783             goto playout;
02784 
02785          if (avgholdmins == 1) {
02786             res = play_file(qe->chan, qe->parent->sound_minute);
02787             if (res)
02788                goto playout;
02789          } else {
02790             res = play_file(qe->chan, qe->parent->sound_minutes);
02791             if (res)
02792                goto playout;
02793          }
02794       }
02795       if (avgholdsecs >= 1) {
02796          res = ast_say_number(qe->chan, avgholdsecs, AST_DIGIT_ANY, qe->chan->language, NULL);
02797          if (res)
02798             goto playout;
02799 
02800          res = play_file(qe->chan, qe->parent->sound_seconds);
02801          if (res)
02802             goto playout;
02803       }
02804    } else if (qe->parent->announceholdtime && !qe->parent->announceposition) {
02805       say_thanks = 0;
02806    }
02807 
02808 posout:
02809    if (qe->parent->announceposition) {
02810       ast_verb(3, "Told %s in %s their queue position (which was %d)\n",
02811          qe->chan->name, qe->parent->name, qe->pos);
02812    }
02813    if (say_thanks) {
02814       res = play_file(qe->chan, qe->parent->sound_thanks);
02815    }
02816 playout:
02817 
02818    if ((res > 0 && !valid_exit(qe, res)))
02819       res = 0;
02820 
02821    /* Set our last_pos indicators */
02822    qe->last_pos = now;
02823    qe->last_pos_said = qe->pos;
02824 
02825    /* Don't restart music on hold if we're about to exit the caller from the queue */
02826    if (!res) {
02827       if (ringing) {
02828          ast_indicate(qe->chan, AST_CONTROL_RINGING);
02829       } else {
02830          ast_moh_start(qe->chan, qe->moh, NULL);
02831       }
02832    }
02833    return res;
02834 }
02835 
02836 static void recalc_holdtime(struct queue_ent *qe, int newholdtime)
02837 {
02838    int oldvalue;
02839 
02840    /* Calculate holdtime using an exponential average */
02841    /* Thanks to SRT for this contribution */
02842    /* 2^2 (4) is the filter coefficient; a higher exponent would give old entries more weight */
02843 
02844    ao2_lock(qe->parent);
02845    oldvalue = qe->parent->holdtime;
02846    qe->parent->holdtime = (((oldvalue << 2) - oldvalue) + newholdtime) >> 2;
02847    ao2_unlock(qe->parent);
02848 }
02849 
02850 /*! \brief Caller leaving queue.
02851  * 
02852  * Search the queue to find the leaving client, if found remove from queue
02853  * create manager event, move others up the queue.
02854 */
02855 static void leave_queue(struct queue_ent *qe)
02856 {
02857    struct call_queue *q;
02858    struct queue_ent *current, *prev = NULL;
02859    struct penalty_rule *pr_iter;
02860    int pos = 0;
02861 
02862    if (!(q = qe->parent))
02863       return;
02864    queue_t_ref(q, "Copy queue pointer from queue entry");
02865    ao2_lock(q);
02866 
02867    prev = NULL;
02868    for (current = q->head; current; current = current->next) {
02869       if (current == qe) {
02870          char posstr[20];
02871          q->count--;
02872 
02873          /* Take us out of the queue */
02874          ast_manager_event(qe->chan, EVENT_FLAG_CALL, "Leave",
02875             "Channel: %s\r\nQueue: %s\r\nCount: %d\r\nPosition: %d\r\nUniqueid: %s\r\n",
02876             qe->chan->name, q->name,  q->count, qe->pos, qe->chan->uniqueid);
02877          ast_debug(1, "Queue '%s' Leave, Channel '%s'\n", q->name, qe->chan->name );
02878          /* Take us out of the queue */
02879          if (prev)
02880             prev->next = current->next;
02881          else
02882             q->head = current->next;
02883          /* Free penalty rules */
02884          while ((pr_iter = AST_LIST_REMOVE_HEAD(&qe->qe_rules, list)))
02885             ast_free(pr_iter);
02886          snprintf(posstr, sizeof(posstr), "%d", qe->pos);
02887          pbx_builtin_setvar_helper(qe->chan, "QUEUEPOSITION", posstr);
02888       } else {
02889          /* Renumber the people after us in the queue based on a new count */
02890          current->pos = ++pos;
02891          prev = current;
02892       }
02893    }
02894    ao2_unlock(q);
02895 
02896    /*If the queue is a realtime queue, check to see if it's still defined in real time*/
02897    if (q->realtime) {
02898       struct ast_variable *var;
02899       if (!(var = ast_load_realtime("queues", "name", q->name, SENTINEL))) {
02900          q->dead = 1;
02901       } else {
02902          ast_variables_destroy(var);
02903       }
02904    }
02905 
02906    if (q->dead) { 
02907       /* It's dead and nobody is in it, so kill it */
02908       queues_t_unlink(queues, q, "Queue is now dead; remove it from the container");
02909    }
02910    /* unref the explicit ref earlier in the function */
02911    queue_t_unref(q, "Expire copied reference");
02912 }
02913 
02914 /*!
02915  * \internal
02916  * \brief Destroy the given callattempt structure and free it.
02917  * \since 1.8
02918  *
02919  * \param doomed callattempt structure to destroy.
02920  *
02921  * \return Nothing
02922  */
02923 static void callattempt_free(struct callattempt *doomed)
02924 {
02925    if (doomed->member) {
02926       ao2_ref(doomed->member, -1);
02927    }
02928    ast_party_connected_line_free(&doomed->connected);
02929    ast_free(doomed);
02930 }
02931 
02932 /*! \brief Hang up a list of outgoing calls */
02933 static void hangupcalls(struct callattempt *outgoing, struct ast_channel *exception, int cancel_answered_elsewhere)
02934 {
02935    struct callattempt *oo;
02936 
02937    while (outgoing) {
02938       /* If someone else answered the call we should indicate this in the CANCEL */
02939       /* Hangup any existing lines we have open */
02940       if (outgoing->chan && (outgoing->chan != exception)) {
02941          if (exception || cancel_answered_elsewhere)
02942             ast_set_flag(outgoing->chan, AST_FLAG_ANSWERED_ELSEWHERE);
02943          ast_hangup(outgoing->chan);
02944       }
02945       oo = outgoing;
02946       outgoing = outgoing->q_next;
02947       ast_aoc_destroy_decoded(oo->aoc_s_rate_list);
02948       callattempt_free(oo);
02949    }
02950 }
02951 
02952 /*!
02953  * \brief Get the number of members available to accept a call.
02954  *
02955  * \note The queue passed in should be locked prior to this function call
02956  *
02957  * \param[in] q The queue for which we are couting the number of available members
02958  * \return Return the number of available members in queue q
02959  */
02960 static int num_available_members(struct call_queue *q)
02961 {
02962    struct member *mem;
02963    int avl = 0;
02964    struct ao2_iterator mem_iter;
02965 
02966    mem_iter = ao2_iterator_init(q->members, 0);
02967    while ((mem = ao2_iterator_next(&mem_iter))) {
02968       switch (mem->status) {
02969       case AST_DEVICE_INUSE:
02970          if (!q->ringinuse)
02971             break;
02972          /* else fall through */
02973       case AST_DEVICE_NOT_INUSE:
02974       case AST_DEVICE_UNKNOWN:
02975          if (!mem->paused) {
02976             avl++;
02977          }
02978          break;
02979       }
02980       ao2_ref(mem, -1);
02981 
02982       /* If autofill is not enabled or if the queue's strategy is ringall, then
02983        * we really don't care about the number of available members so much as we
02984        * do that there is at least one available.
02985        *
02986        * In fact, we purposely will return from this function stating that only
02987        * one member is available if either of those conditions hold. That way,
02988        * functions which determine what action to take based on the number of available
02989        * members will operate properly. The reasoning is that even if multiple
02990        * members are available, only the head caller can actually be serviced.
02991        */
02992       if ((!q->autofill || q->strategy == QUEUE_STRATEGY_RINGALL) && avl) {
02993          break;
02994       }
02995    }
02996    ao2_iterator_destroy(&mem_iter);
02997 
02998    return avl;
02999 }
03000 
03001 /* traverse all defined queues which have calls waiting and contain this member
03002    return 0 if no other queue has precedence (higher weight) or 1 if found  */
03003 static int compare_weight(struct call_queue *rq, struct member *member)
03004 {
03005    struct call_queue *q;
03006    struct member *mem;
03007    int found = 0;
03008    struct ao2_iterator queue_iter;
03009 
03010    queue_iter = ao2_iterator_init(queues, 0);
03011    while ((q = ao2_t_iterator_next(&queue_iter, "Iterate through queues"))) {
03012       if (q == rq) { /* don't check myself, could deadlock */
03013          queue_t_unref(q, "Done with iterator");
03014          continue;
03015       }
03016       ao2_lock(q);
03017       if (q->count && q->members) {
03018          if ((mem = ao2_find(q->members, member, OBJ_POINTER))) {
03019             ast_debug(1, "Found matching member %s in queue '%s'\n", mem->interface, q->name);
03020             if (q->weight > rq->weight && q->count >= num_available_members(q)) {
03021                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);
03022                found = 1;
03023             }
03024             ao2_ref(mem, -1);
03025          }
03026       }
03027       ao2_unlock(q);
03028       queue_t_unref(q, "Done with iterator");
03029       if (found) {
03030          break;
03031       }
03032    }
03033    ao2_iterator_destroy(&queue_iter);
03034    return found;
03035 }
03036 
03037 /*! \brief common hangup actions */
03038 static void do_hang(struct callattempt *o)
03039 {
03040    o->stillgoing = 0;
03041    ast_hangup(o->chan);
03042    o->chan = NULL;
03043 }
03044 
03045 /*! \brief convert "\n" to "\nVariable: " ready for manager to use */
03046 static char *vars2manager(struct ast_channel *chan, char *vars, size_t len)
03047 {
03048    struct ast_str *buf = ast_str_thread_get(&ast_str_thread_global_buf, len + 1);
03049    const char *tmp;
03050 
03051    if (pbx_builtin_serialize_variables(chan, &buf)) {
03052       int i, j;
03053 
03054       /* convert "\n" to "\nVariable: " */
03055       strcpy(vars, "Variable: ");
03056       tmp = ast_str_buffer(buf);
03057 
03058       for (i = 0, j = 10; (i < len - 1) && (j < len - 1); i++, j++) {
03059          vars[j] = tmp[i];
03060 
03061          if (tmp[i + 1] == '\0')
03062             break;
03063          if (tmp[i] == '\n') {
03064             vars[j++] = '\r';
03065             vars[j++] = '\n';
03066 
03067             ast_copy_string(&(vars[j]), "Variable: ", len - j);
03068             j += 9;
03069          }
03070       }
03071       if (j > len - 3)
03072          j = len - 3;
03073       vars[j++] = '\r';
03074       vars[j++] = '\n';
03075       vars[j] = '\0';
03076    } else {
03077       /* there are no channel variables; leave it blank */
03078       *vars = '\0';
03079    }
03080    return vars;
03081 }
03082 
03083 /*!
03084  * \internal
03085  * \brief Check if the member status is available.
03086  *
03087  * \param status Member status to check if available.
03088  *
03089  * \retval non-zero if the member status is available.
03090  */
03091 static int member_status_available(int status)
03092 {
03093    return status == AST_DEVICE_NOT_INUSE || status == AST_DEVICE_UNKNOWN;
03094 }
03095 
03096 /*!
03097  * \internal
03098  * \brief Clear the member call pending flag.
03099  *
03100  * \param mem Queue member.
03101  *
03102  * \return Nothing
03103  */
03104 static void member_call_pending_clear(struct member *mem)
03105 {
03106    ao2_lock(mem);
03107    mem->call_pending = 0;
03108    ao2_unlock(mem);
03109 }
03110 
03111 /*!
03112  * \internal
03113  * \brief Set the member call pending flag.
03114  *
03115  * \param mem Queue member.
03116  *
03117  * \retval non-zero if call pending flag was already set.
03118  */
03119 static int member_call_pending_set(struct member *mem)
03120 {
03121    int old_pending;
03122 
03123    ao2_lock(mem);
03124    old_pending = mem->call_pending;
03125    mem->call_pending = 1;
03126    ao2_unlock(mem);
03127 
03128    return old_pending;
03129 }
03130 
03131 /*!
03132  * \internal
03133  * \brief Determine if can ring a queue entry.
03134  *
03135  * \param qe Queue entry to check.
03136  * \param call Member call attempt.
03137  *
03138  * \retval non-zero if an entry can be called.
03139  */
03140 static int can_ring_entry(struct queue_ent *qe, struct callattempt *call)
03141 {
03142    if (call->member->paused) {
03143       ast_debug(1, "%s paused, can't receive call\n", call->interface);
03144       return 0;
03145    }
03146 
03147    if (!qe->parent->ringinuse && !member_status_available(call->member->status)) {
03148       ast_debug(1, "%s not available, can't receive call\n", call->interface);
03149       return 0;
03150    }
03151 
03152    if ((call->lastqueue && call->lastqueue->wrapuptime && (time(NULL) - call->lastcall < call->lastqueue->wrapuptime))
03153       || (!call->lastqueue && qe->parent->wrapuptime && (time(NULL) - call->lastcall < qe->parent->wrapuptime))) {
03154       ast_debug(1, "Wrapuptime not yet expired on queue %s for %s\n",
03155          (call->lastqueue ? call->lastqueue->name : qe->parent->name),
03156          call->interface);
03157       return 0;
03158    }
03159 
03160    if (use_weight && compare_weight(qe->parent, call->member)) {
03161       ast_debug(1, "Priority queue delaying call to %s:%s\n",
03162          qe->parent->name, call->interface);
03163       return 0;
03164    }
03165 
03166    if (!qe->parent->ringinuse) {
03167       if (member_call_pending_set(call->member)) {
03168          ast_debug(1, "%s has another call pending, can't receive call\n",
03169             call->interface);
03170          return 0;
03171       }
03172 
03173       /*
03174        * The queue member is available.  Get current status to be sure
03175        * because the device state and extension state callbacks may
03176        * not have updated the status yet.
03177        */
03178       if (!member_status_available(get_queue_member_status(call->member))) {
03179          ast_debug(1, "%s actually not available, can't receive call\n",
03180             call->interface);
03181          member_call_pending_clear(call->member);
03182          return 0;
03183       }
03184    }
03185 
03186    return 1;
03187 }
03188 
03189 /*! 
03190  * \brief Part 2 of ring_one
03191  *
03192  * Does error checking before attempting to request a channel and call a member. 
03193  * This function is only called from ring_one(). 
03194  * Failure can occur if:
03195  * - Agent on call
03196  * - Agent is paused
03197  * - Wrapup time not expired
03198  * - Priority by another queue
03199  *
03200  * \retval 1 on success to reach a free agent
03201  * \retval 0 on failure to get agent.
03202  */
03203 static int ring_entry(struct queue_ent *qe, struct callattempt *tmp, int *busies)
03204 {
03205    int res;
03206    int status;
03207    char tech[256];
03208    char *location;
03209    const char *macrocontext, *macroexten;
03210 
03211    /* on entry here, we know that tmp->chan == NULL */
03212    if (!can_ring_entry(qe, tmp)) {
03213       if (qe->chan->cdr) {
03214          ast_cdr_busy(qe->chan->cdr);
03215       }
03216       tmp->stillgoing = 0;
03217       ++*busies;
03218       return 0;
03219    }
03220    ast_assert(qe->parent->ringinuse || tmp->member->call_pending);
03221 
03222    ast_copy_string(tech, tmp->interface, sizeof(tech));
03223    if ((location = strchr(tech, '/')))
03224       *location++ = '\0';
03225    else
03226       location = "";
03227 
03228    /* Request the peer */
03229    tmp->chan = ast_request(tech, qe->chan->nativeformats, qe->chan, location, &status);
03230    if (!tmp->chan) {       /* If we can't, just go on to the next call */
03231       ao2_lock(qe->parent);
03232       qe->parent->rrpos++;
03233       qe->linpos++;
03234       ao2_unlock(qe->parent);
03235 
03236       member_call_pending_clear(tmp->member);
03237 
03238       if (qe->chan->cdr) {
03239          ast_cdr_busy(qe->chan->cdr);
03240       }
03241       tmp->stillgoing = 0;
03242       ++*busies;
03243       return 0;
03244    }
03245 
03246    ast_channel_lock_both(tmp->chan, qe->chan);
03247 
03248    if (qe->cancel_answered_elsewhere) {
03249       ast_set_flag(tmp->chan, AST_FLAG_ANSWERED_ELSEWHERE);
03250    }
03251    tmp->chan->appl = "AppQueue";
03252    tmp->chan->data = "(Outgoing Line)";
03253    memset(&tmp->chan->whentohangup, 0, sizeof(tmp->chan->whentohangup));
03254 
03255    /* If the new channel has no callerid, try to guess what it should be */
03256    if (!tmp->chan->caller.id.number.valid) {
03257       if (qe->chan->connected.id.number.valid) {
03258          struct ast_party_caller caller;
03259 
03260          ast_party_caller_set_init(&caller, &tmp->chan->caller);
03261          caller.id = qe->chan->connected.id;
03262          caller.ani = qe->chan->connected.ani;
03263          ast_channel_set_caller_event(tmp->chan, &caller, NULL);
03264       } else if (!ast_strlen_zero(qe->chan->dialed.number.str)) {
03265          ast_set_callerid(tmp->chan, qe->chan->dialed.number.str, NULL, NULL);
03266       } else if (!ast_strlen_zero(S_OR(qe->chan->macroexten, qe->chan->exten))) {
03267          ast_set_callerid(tmp->chan, S_OR(qe->chan->macroexten, qe->chan->exten), NULL, NULL); 
03268       }
03269       tmp->dial_callerid_absent = 1;
03270    }
03271 
03272    ast_party_redirecting_copy(&tmp->chan->redirecting, &qe->chan->redirecting);
03273 
03274    tmp->chan->dialed.transit_network_select = qe->chan->dialed.transit_network_select;
03275 
03276    ast_connected_line_copy_from_caller(&tmp->chan->connected, &qe->chan->caller);
03277 
03278    /* Inherit specially named variables from parent channel */
03279    ast_channel_inherit_variables(qe->chan, tmp->chan);
03280    ast_channel_datastore_inherit(qe->chan, tmp->chan);
03281 
03282    /* Presense of ADSI CPE on outgoing channel follows ours */
03283    tmp->chan->adsicpe = qe->chan->adsicpe;
03284 
03285    /* Inherit context and extension */
03286    macrocontext = pbx_builtin_getvar_helper(qe->chan, "MACRO_CONTEXT");
03287    ast_string_field_set(tmp->chan, dialcontext, ast_strlen_zero(macrocontext) ? qe->chan->context : macrocontext);
03288    macroexten = pbx_builtin_getvar_helper(qe->chan, "MACRO_EXTEN");
03289    if (!ast_strlen_zero(macroexten))
03290       ast_copy_string(tmp->chan->exten, macroexten, sizeof(tmp->chan->exten));
03291    else
03292       ast_copy_string(tmp->chan->exten, qe->chan->exten, sizeof(tmp->chan->exten));
03293    if (ast_cdr_isset_unanswered()) {
03294       /* they want to see the unanswered dial attempts! */
03295       /* set up the CDR fields on all the CDRs to give sensical information */
03296       ast_cdr_setdestchan(tmp->chan->cdr, tmp->chan->name);
03297       strcpy(tmp->chan->cdr->clid, qe->chan->cdr->clid);
03298       strcpy(tmp->chan->cdr->channel, qe->chan->cdr->channel);
03299       strcpy(tmp->chan->cdr->src, qe->chan->cdr->src);
03300       strcpy(tmp->chan->cdr->dst, qe->chan->exten);
03301       strcpy(tmp->chan->cdr->dcontext, qe->chan->context);
03302       strcpy(tmp->chan->cdr->lastapp, qe->chan->cdr->lastapp);
03303       strcpy(tmp->chan->cdr->lastdata, qe->chan->cdr->lastdata);
03304       tmp->chan->cdr->amaflags = qe->chan->cdr->amaflags;
03305       strcpy(tmp->chan->cdr->accountcode, qe->chan->cdr->accountcode);
03306       strcpy(tmp->chan->cdr->userfield, qe->chan->cdr->userfield);
03307    }
03308 
03309    ast_channel_unlock(tmp->chan);
03310    ast_channel_unlock(qe->chan);
03311 
03312    /* Place the call, but don't wait on the answer */
03313    if ((res = ast_call(tmp->chan, location, 0))) {
03314       /* Again, keep going even if there's an error */
03315       ast_verb(3, "Couldn't call %s\n", tmp->interface);
03316       do_hang(tmp);
03317       member_call_pending_clear(tmp->member);
03318       ++*busies;
03319       return 0;
03320    }
03321 
03322    if (qe->parent->eventwhencalled) {
03323       char vars[2048];
03324 
03325       ast_channel_lock_both(tmp->chan, qe->chan);
03326 
03327       manager_event(EVENT_FLAG_AGENT, "AgentCalled",
03328          "Queue: %s\r\n"
03329          "AgentCalled: %s\r\n"
03330          "AgentName: %s\r\n"
03331          "ChannelCalling: %s\r\n"
03332          "DestinationChannel: %s\r\n"
03333          "CallerIDNum: %s\r\n"
03334          "CallerIDName: %s\r\n"
03335          "ConnectedLineNum: %s\r\n"
03336          "ConnectedLineName: %s\r\n"
03337          "Context: %s\r\n"
03338          "Extension: %s\r\n"
03339          "Priority: %d\r\n"
03340          "Uniqueid: %s\r\n"
03341          "%s",
03342          qe->parent->name, tmp->interface, tmp->member->membername, qe->chan->name, tmp->chan->name,
03343          S_COR(qe->chan->caller.id.number.valid, qe->chan->caller.id.number.str, "unknown"),
03344          S_COR(qe->chan->caller.id.name.valid, qe->chan->caller.id.name.str, "unknown"),
03345          S_COR(qe->chan->connected.id.number.valid, qe->chan->connected.id.number.str, "unknown"),
03346          S_COR(qe->chan->connected.id.name.valid, qe->chan->connected.id.name.str, "unknown"),
03347          qe->chan->context, qe->chan->exten, qe->chan->priority, qe->chan->uniqueid,
03348          qe->parent->eventwhencalled == QUEUE_EVENT_VARIABLES ? vars2manager(qe->chan, vars, sizeof(vars)) : "");
03349 
03350       ast_channel_unlock(tmp->chan);
03351       ast_channel_unlock(qe->chan);
03352 
03353       ast_verb(3, "Called %s\n", tmp->interface);
03354    }
03355 
03356    member_call_pending_clear(tmp->member);
03357    return 1;
03358 }
03359 
03360 /*! \brief find the entry with the best metric, or NULL */
03361 static struct callattempt *find_best(struct callattempt *outgoing)
03362 {
03363    struct callattempt *best = NULL, *cur;
03364 
03365    for (cur = outgoing; cur; cur = cur->q_next) {
03366       if (cur->stillgoing &&              /* Not already done */
03367          !cur->chan &&              /* Isn't already going */
03368          (!best || cur->metric < best->metric)) {     /* We haven't found one yet, or it's better */
03369          best = cur;
03370       }
03371    }
03372 
03373    return best;
03374 }
03375 
03376 /*! 
03377  * \brief Place a call to a queue member.
03378  *
03379  * Once metrics have been calculated for each member, this function is used
03380  * to place a call to the appropriate member (or members). The low-level
03381  * channel-handling and error detection is handled in ring_entry
03382  *
03383  * \retval 1 if a member was called successfully
03384  * \retval 0 otherwise
03385  */
03386 static int ring_one(struct queue_ent *qe, struct callattempt *outgoing, int *busies)
03387 {
03388    int ret = 0;
03389 
03390    while (ret == 0) {
03391       struct callattempt *best = find_best(outgoing);
03392       if (!best) {
03393          ast_debug(1, "Nobody left to try ringing in queue\n");
03394          break;
03395       }
03396       if (qe->parent->strategy == QUEUE_STRATEGY_RINGALL) {
03397          struct callattempt *cur;
03398          /* Ring everyone who shares this best metric (for ringall) */
03399          for (cur = outgoing; cur; cur = cur->q_next) {
03400             if (cur->stillgoing && !cur->chan && cur->metric <= best->metric) {
03401                ast_debug(1, "(Parallel) Trying '%s' with metric %d\n", cur->interface, cur->metric);
03402                ret |= ring_entry(qe, cur, busies);
03403             }
03404          }
03405       } else {
03406          /* Ring just the best channel */
03407          ast_debug(1, "Trying '%s' with metric %d\n", best->interface, best->metric);
03408          ret = ring_entry(qe, best, busies);
03409       }
03410       
03411       /* If we have timed out, break out */
03412       if (qe->expire && (time(NULL) >= qe->expire)) {
03413          ast_debug(1, "Queue timed out while ringing members.\n");
03414          ret = 0;
03415          break;
03416       }
03417    }
03418 
03419    return ret;
03420 }
03421 
03422 /*! \brief Search for best metric and add to Round Robbin queue */
03423 static int store_next_rr(struct queue_ent *qe, struct callattempt *outgoing)
03424 {
03425    struct callattempt *best = find_best(outgoing);
03426 
03427    if (best) {
03428       /* Ring just the best channel */
03429       ast_debug(1, "Next is '%s' with metric %d\n", best->interface, best->metric);
03430       qe->parent->rrpos = best->metric % 1000;
03431    } else {
03432       /* Just increment rrpos */
03433       if (qe->parent->wrapped) {
03434          /* No more channels, start over */
03435          qe->parent->rrpos = 0;
03436       } else {
03437          /* Prioritize next entry */
03438          qe->parent->rrpos++;
03439       }
03440    }
03441    qe->parent->wrapped = 0;
03442 
03443    return 0;
03444 }
03445 
03446 /*! \brief Search for best metric and add to Linear queue */
03447 static int store_next_lin(struct queue_ent *qe, struct callattempt *outgoing)
03448 {
03449    struct callattempt *best = find_best(outgoing);
03450 
03451    if (best) {
03452       /* Ring just the best channel */
03453       ast_debug(1, "Next is '%s' with metric %d\n", best->interface, best->metric);
03454       qe->linpos = best->metric % 1000;
03455    } else {
03456       /* Just increment rrpos */
03457       if (qe->linwrapped) {
03458          /* No more channels, start over */
03459          qe->linpos = 0;
03460       } else {
03461          /* Prioritize next entry */
03462          qe->linpos++;
03463       }
03464    }
03465    qe->linwrapped = 0;
03466 
03467    return 0;
03468 }
03469 
03470 /*! \brief Playback announcement to queued members if period has elapsed */
03471 static int say_periodic_announcement(struct queue_ent *qe, int ringing)
03472 {
03473    int res = 0;
03474    time_t now;
03475 
03476    /* Get the current time */
03477    time(&now);
03478 
03479    /* Check to see if it is time to announce */
03480    if ((now - qe->last_periodic_announce_time) < qe->parent->periodicannouncefrequency)
03481       return 0;
03482 
03483    /* Stop the music on hold so we can play our own file */
03484    if (ringing)
03485       ast_indicate(qe->chan,-1);
03486    else
03487       ast_moh_stop(qe->chan);
03488 
03489    ast_verb(3, "Playing periodic announcement\n");
03490    
03491    if (qe->parent->randomperiodicannounce && qe->parent->numperiodicannounce) {
03492       qe->last_periodic_announce_sound = ((unsigned long) ast_random()) % qe->parent->numperiodicannounce;
03493    } else if (qe->last_periodic_announce_sound >= qe->parent->numperiodicannounce || 
03494       ast_str_strlen(qe->parent->sound_periodicannounce[qe->last_periodic_announce_sound]) == 0) {
03495       qe->last_periodic_announce_sound = 0;
03496    }
03497    
03498    /* play the announcement */
03499    res = play_file(qe->chan, ast_str_buffer(qe->parent->sound_periodicannounce[qe->last_periodic_announce_sound]));
03500 
03501    if (res > 0 && !valid_exit(qe, res))
03502       res = 0;
03503 
03504    /* Resume Music on Hold if the caller is going to stay in the queue */
03505    if (!res) {
03506       if (ringing)
03507          ast_indicate(qe->chan, AST_CONTROL_RINGING);
03508       else
03509          ast_moh_start(qe->chan, qe->moh, NULL);
03510    }
03511 
03512    /* update last_periodic_announce_time */
03513    if (qe->parent->relativeperiodicannounce)
03514       time(&qe->last_periodic_announce_time);
03515    else
03516       qe->last_periodic_announce_time = now;
03517 
03518    /* Update the current periodic announcement to the next announcement */
03519    if (!qe->parent->randomperiodicannounce) {
03520       qe->last_periodic_announce_sound++;
03521    }
03522    
03523    return res;
03524 }
03525 
03526 /*! \brief Record that a caller gave up on waiting in queue */
03527 static void record_abandoned(struct queue_ent *qe)
03528 {
03529    set_queue_variables(qe->parent, qe->chan);
03530    ao2_lock(qe->parent);
03531    manager_event(EVENT_FLAG_AGENT, "QueueCallerAbandon",
03532       "Queue: %s\r\n"
03533       "Uniqueid: %s\r\n"
03534       "Position: %d\r\n"
03535       "OriginalPosition: %d\r\n"
03536       "HoldTime: %d\r\n",
03537       qe->parent->name, qe->chan->uniqueid, qe->pos, qe->opos, (int)(time(NULL) - qe->start));
03538 
03539    qe->parent->callsabandoned++;
03540    ao2_unlock(qe->parent);
03541 }
03542 
03543 /*! \brief RNA == Ring No Answer. Common code that is executed when we try a queue member and they don't answer. */
03544 static void rna(int rnatime, struct queue_ent *qe, char *interface, char *membername, int pause)
03545 {
03546    ast_verb(3, "Nobody picked up in %d ms\n", rnatime);
03547 
03548    /* Stop ringing, and resume MOH if specified */
03549    if (qe->ring_when_ringing) {
03550       ast_indicate(qe->chan, -1);
03551       ast_moh_start(qe->chan, qe->moh, NULL);
03552    }
03553 
03554    if (qe->parent->eventwhencalled) {
03555       char vars[2048];
03556 
03557       manager_event(EVENT_FLAG_AGENT, "AgentRingNoAnswer",
03558                   "Queue: %s\r\n"
03559                   "Uniqueid: %s\r\n"
03560                   "Channel: %s\r\n"
03561                   "Member: %s\r\n"
03562                   "MemberName: %s\r\n"
03563                   "Ringtime: %d\r\n"
03564                   "%s",
03565                   qe->parent->name,
03566                   qe->chan->uniqueid,
03567                   qe->chan->name,
03568                   interface,
03569                   membername,
03570                   rnatime,
03571                   qe->parent->eventwhencalled == QUEUE_EVENT_VARIABLES ? vars2manager(qe->chan, vars, sizeof(vars)) : "");
03572    }
03573    ast_queue_log(qe->parent->name, qe->chan->uniqueid, membername, "RINGNOANSWER", "%d", rnatime);
03574    if (qe->parent->autopause != QUEUE_AUTOPAUSE_OFF && pause) {
03575       if (qe->parent->autopause == QUEUE_AUTOPAUSE_ON) {
03576          if (!set_member_paused(qe->parent->name, interface, "Auto-Pause", 1)) {
03577             ast_verb(3, "Auto-Pausing Queue Member %s in queue %s since they failed to answer.\n",
03578                interface, qe->parent->name);
03579          } else {
03580             ast_verb(3, "Failed to pause Queue Member %s in queue %s!\n", interface, qe->parent->name);
03581          }
03582       } else {
03583          /* If queue autopause is mode all, just don't send any queue to stop.
03584          * the function will stop in all queues */
03585          if (!set_member_paused("", interface, "Auto-Pause", 1)) {
03586             ast_verb(3, "Auto-Pausing Queue Member %s in all queues since they failed to answer on queue %s.\n",
03587                   interface, qe->parent->name);
03588          } else {
03589                ast_verb(3, "Failed to pause Queue Member %s in all queues!\n", interface);
03590          }
03591       }
03592    }
03593    return;
03594 }
03595 
03596 #define AST_MAX_WATCHERS 256
03597 /*!
03598  * \brief Wait for a member to answer the call
03599  *
03600  * \param[in] qe the queue_ent corresponding to the caller in the queue
03601  * \param[in] outgoing the list of callattempts. Relevant ones will have their chan and stillgoing parameters non-zero
03602  * \param[in] to the amount of time (in milliseconds) to wait for a response
03603  * \param[out] digit if a user presses a digit to exit the queue, this is the digit the caller pressed
03604  * \param[in] prebusies number of busy members calculated prior to calling wait_for_answer
03605  * \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
03606  * \param[in] forwardsallowed used to detect if we should allow call forwarding, based on the 'i' option to Queue()
03607  *
03608  * \todo eventually all call forward logic should be intergerated into and replaced by ast_call_forward()
03609  */
03610 static struct callattempt *wait_for_answer(struct queue_ent *qe, struct callattempt *outgoing, int *to, char *digit, int prebusies, int caller_disconnect, int forwardsallowed)
03611 {
03612    const char *queue = qe->parent->name;
03613    struct callattempt *o, *start = NULL, *prev = NULL;
03614    int status;
03615    int numbusies = prebusies;
03616    int numnochan = 0;
03617    int stillgoing = 0;
03618    int orig = *to;
03619    struct ast_frame *f;
03620    struct callattempt *peer = NULL;
03621    struct ast_channel *winner;
03622    struct ast_channel *in = qe->chan;
03623    char on[80] = "";
03624    char membername[80] = "";
03625    long starttime = 0;
03626    long endtime = 0;
03627 #ifdef HAVE_EPOLL
03628    struct callattempt *epollo;
03629 #endif
03630    struct ast_party_connected_line connected_caller;
03631    char *inchan_name;
03632    struct timeval start_time_tv = ast_tvnow();
03633 
03634    ast_party_connected_line_init(&connected_caller);
03635 
03636    ast_channel_lock(qe->chan);
03637    inchan_name = ast_strdupa(qe->chan->name);
03638    ast_channel_unlock(qe->chan);
03639 
03640    starttime = (long) time(NULL);
03641 #ifdef HAVE_EPOLL
03642    for (epollo = outgoing; epollo; epollo = epollo->q_next) {
03643       if (epollo->chan)
03644          ast_poll_channel_add(in, epollo->chan);
03645    }
03646 #endif
03647 
03648    while ((*to = ast_remaining_ms(start_time_tv, orig)) && !peer) {
03649       int numlines, retry, pos = 1;
03650       struct ast_channel *watchers[AST_MAX_WATCHERS];
03651       watchers[0] = in;
03652       start = NULL;
03653 
03654       for (retry = 0; retry < 2; retry++) {
03655          numlines = 0;
03656          for (o = outgoing; o; o = o->q_next) { /* Keep track of important channels */
03657             if (o->stillgoing) { /* Keep track of important channels */
03658                stillgoing = 1;
03659                if (o->chan) {
03660                   if (pos < AST_MAX_WATCHERS) {
03661                      watchers[pos++] = o->chan;
03662                   }
03663                   if (!start)
03664                      start = o;
03665                   else
03666                      prev->call_next = o;
03667                   prev = o;
03668                }
03669             }
03670             numlines++;
03671          }
03672          if (pos > 1 /* found */ || !stillgoing /* nobody listening */ ||
03673             (qe->parent->strategy != QUEUE_STRATEGY_RINGALL) /* ring would not be delivered */)
03674             break;
03675          /* On "ringall" strategy we only move to the next penalty level
03676             when *all* ringing phones are done in the current penalty level */
03677          ring_one(qe, outgoing, &numbusies);
03678          /* and retry... */
03679       }
03680       if (pos == 1 /* not found */) {
03681          if (numlines == (numbusies + numnochan)) {
03682             ast_debug(1, "Everyone is busy at this time\n");
03683          } else {
03684             ast_debug(3, "No one is answering queue '%s' (%d numlines / %d busies / %d failed channels)\n", queue, numlines, numbusies, numnochan);
03685          }
03686          *to = 0;
03687          return NULL;
03688       }
03689 
03690       /* Poll for events from both the incoming channel as well as any outgoing channels */
03691       winner = ast_waitfor_n(watchers, pos, to);
03692 
03693       /* Service all of the outgoing channels */
03694       for (o = start; o; o = o->call_next) {
03695          /* We go with a fixed buffer here instead of using ast_strdupa. Using
03696           * ast_strdupa in a loop like this one can cause a stack overflow
03697           */
03698          char ochan_name[AST_CHANNEL_NAME];
03699 
03700          if (o->chan) {
03701             ast_channel_lock(o->chan);
03702             ast_copy_string(ochan_name, o->chan->name, sizeof(ochan_name));
03703             ast_channel_unlock(o->chan);
03704          }
03705          if (o->stillgoing && (o->chan) &&  (o->chan->_state == AST_STATE_UP)) {
03706             if (!peer) {
03707                ast_verb(3, "%s answered %s\n", ochan_name, inchan_name);
03708                if (!o->block_connected_update) {
03709                   if (o->pending_connected_update) {
03710                      if (ast_channel_connected_line_macro(o->chan, in, &o->connected, 1, 0)) {
03711                         ast_channel_update_connected_line(in, &o->connected, NULL);
03712                      }
03713                   } else if (!o->dial_callerid_absent) {
03714                      ast_channel_lock(o->chan);
03715                      ast_connected_line_copy_from_caller(&connected_caller, &o->chan->caller);
03716                      ast_channel_unlock(o->chan);
03717                      connected_caller.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
03718                      if (ast_channel_connected_line_macro(o->chan, in, &connected_caller, 1, 0)) {
03719                         ast_channel_update_connected_line(in, &connected_caller, NULL);
03720                      }
03721                      ast_party_connected_line_free(&connected_caller);
03722                   }
03723                }
03724                if (o->aoc_s_rate_list) {
03725                   size_t encoded_size;
03726                   struct ast_aoc_encoded *encoded;
03727                   if ((encoded = ast_aoc_encode(o->aoc_s_rate_list, &encoded_size, o->chan))) {
03728                      ast_indicate_data(in, AST_CONTROL_AOC, encoded, encoded_size);
03729                      ast_aoc_destroy_encoded(encoded);
03730                   }
03731                }
03732                peer = o;
03733             }
03734          } else if (o->chan && (o->chan == winner)) {
03735 
03736             ast_copy_string(on, o->member->interface, sizeof(on));
03737             ast_copy_string(membername, o->member->membername, sizeof(membername));
03738 
03739             /* Before processing channel, go ahead and check for forwarding */
03740             if (!ast_strlen_zero(o->chan->call_forward) && !forwardsallowed) {
03741                ast_verb(3, "Forwarding %s to '%s' prevented.\n", inchan_name, o->chan->call_forward);
03742                numnochan++;
03743                do_hang(o);
03744                winner = NULL;
03745                continue;
03746             } else if (!ast_strlen_zero(o->chan->call_forward)) {
03747                struct ast_channel *original = o->chan;
03748                char tmpchan[256];
03749                char *stuff;
03750                char *tech;
03751 
03752                ast_copy_string(tmpchan, o->chan->call_forward, sizeof(tmpchan));
03753                if ((stuff = strchr(tmpchan, '/'))) {
03754                   *stuff++ = '\0';
03755                   tech = tmpchan;
03756                } else {
03757                   snprintf(tmpchan, sizeof(tmpchan), "%s@%s", o->chan->call_forward, o->chan->context);
03758                   stuff = tmpchan;
03759                   tech = "Local";
03760                }
03761                if (!strcasecmp(tech, "Local")) {
03762                   /*
03763                    * Drop the connected line update block for local channels since
03764                    * this is going to run dialplan and the user can change his
03765                    * mind about what connected line information he wants to send.
03766                    */
03767                   o->block_connected_update = 0;
03768                }
03769 
03770                ast_cel_report_event(in, AST_CEL_FORWARD, NULL, o->chan->call_forward, NULL);
03771 
03772                ast_verb(3, "Now forwarding %s to '%s/%s' (thanks to %s)\n", inchan_name, tech, stuff, ochan_name);
03773                /* Setup parameters */
03774                o->chan = ast_request(tech, in->nativeformats, in, stuff, &status);
03775                if (!o->chan) {
03776                   ast_log(LOG_NOTICE,
03777                      "Forwarding failed to create channel to dial '%s/%s'\n",
03778                      tech, stuff);
03779                   o->stillgoing = 0;
03780                   numnochan++;
03781                } else {
03782                   ast_channel_lock_both(o->chan, original);
03783                   ast_party_redirecting_copy(&o->chan->redirecting, &original->redirecting);
03784                   ast_channel_unlock(o->chan);
03785                   ast_channel_unlock(original);
03786 
03787                   ast_channel_lock_both(o->chan, in);
03788                   ast_channel_inherit_variables(in, o->chan);
03789                   ast_channel_datastore_inherit(in, o->chan);
03790 
03791                   if (o->pending_connected_update) {
03792                      /*
03793                       * Re-seed the callattempt's connected line information with
03794                       * previously acquired connected line info from the queued
03795                       * channel.  The previously acquired connected line info could
03796                       * have been set through the CONNECTED_LINE dialplan function.
03797                       */
03798                      o->pending_connected_update = 0;
03799                      ast_party_connected_line_copy(&o->connected, &in->connected);
03800                   }
03801 
03802                   ast_string_field_set(o->chan, accountcode, in->accountcode);
03803 
03804                   if (!o->chan->redirecting.from.number.valid
03805                      || ast_strlen_zero(o->chan->redirecting.from.number.str)) {
03806                      /*
03807                       * The call was not previously redirected so it is
03808                       * now redirected from this number.
03809                       */
03810                      ast_party_number_free(&o->chan->redirecting.from.number);
03811                      ast_party_number_init(&o->chan->redirecting.from.number);
03812                      o->chan->redirecting.from.number.valid = 1;
03813                      o->chan->redirecting.from.number.str =
03814                         ast_strdup(S_OR(in->macroexten, in->exten));
03815                   }
03816 
03817                   o->chan->dialed.transit_network_select = in->dialed.transit_network_select;
03818 
03819                   o->dial_callerid_absent = !o->chan->caller.id.number.valid
03820                      || ast_strlen_zero(o->chan->caller.id.number.str);
03821                   ast_connected_line_copy_from_caller(&o->chan->connected, &in->caller);
03822 
03823                   ast_channel_unlock(in);
03824                   if (qe->parent->strategy != QUEUE_STRATEGY_RINGALL
03825                      && !o->block_connected_update) {
03826                      struct ast_party_redirecting redirecting;
03827 
03828                      /*
03829                       * Redirecting updates to the caller make sense only on single
03830                       * call at a time strategies.
03831                       *
03832                       * We must unlock o->chan before calling
03833                       * ast_channel_redirecting_macro, because we put o->chan into
03834                       * autoservice there.  That is pretty much a guaranteed
03835                       * deadlock.  This is why the handling of o->chan's lock may
03836                       * seem a bit unusual here.
03837                       */
03838                      ast_party_redirecting_init(&redirecting);
03839                      ast_party_redirecting_copy(&redirecting, &o->chan->redirecting);
03840                      ast_channel_unlock(o->chan);
03841                      if (ast_channel_redirecting_macro(o->chan, in, &redirecting, 1, 0)) {
03842                         ast_channel_update_redirecting(in, &redirecting, NULL);
03843                      }
03844                      ast_party_redirecting_free(&redirecting);
03845                   } else {
03846                      ast_channel_unlock(o->chan);
03847                   }
03848 
03849                   if (ast_call(o->chan, stuff, 0)) {
03850                      ast_log(LOG_NOTICE, "Forwarding failed to dial '%s/%s'\n",
03851                         tech, stuff);
03852                      do_hang(o);
03853                      numnochan++;
03854                   }
03855                }
03856                /* Hangup the original channel now, in case we needed it */
03857                ast_hangup(winner);
03858                continue;
03859             }
03860             f = ast_read(winner);
03861             if (f) {
03862                if (f->frametype == AST_FRAME_CONTROL) {
03863                   switch (f->subclass.integer) {
03864                   case AST_CONTROL_ANSWER:
03865                      /* This is our guy if someone answered. */
03866                      if (!peer) {
03867                         ast_verb(3, "%s answered %s\n", ochan_name, inchan_name);
03868                         if (!o->block_connected_update) {
03869                            if (o->pending_connected_update) {
03870                               if (ast_channel_connected_line_macro(o->chan, in, &o->connected, 1, 0)) {
03871                                  ast_channel_update_connected_line(in, &o->connected, NULL);
03872                               }
03873                            } else if (!o->dial_callerid_absent) {
03874                               ast_channel_lock(o->chan);
03875                               ast_connected_line_copy_from_caller(&connected_caller, &o->chan->caller);
03876                               ast_channel_unlock(o->chan);
03877                               connected_caller.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
03878                               if (ast_channel_connected_line_macro(o->chan, in, &connected_caller, 1, 0)) {
03879                                  ast_channel_update_connected_line(in, &connected_caller, NULL);
03880                               }
03881                               ast_party_connected_line_free(&connected_caller);
03882                            }
03883                         }
03884                         if (o->aoc_s_rate_list) {
03885                            size_t encoded_size;
03886                            struct ast_aoc_encoded *encoded;
03887                            if ((encoded = ast_aoc_encode(o->aoc_s_rate_list, &encoded_size, o->chan))) {
03888                               ast_indicate_data(in, AST_CONTROL_AOC, encoded, encoded_size);
03889                               ast_aoc_destroy_encoded(encoded);
03890                            }
03891                         }
03892                         peer = o;
03893                      }
03894                      break;
03895                   case AST_CONTROL_BUSY:
03896                      ast_verb(3, "%s is busy\n", ochan_name);
03897                      if (in->cdr)
03898                         ast_cdr_busy(in->cdr);
03899                      do_hang(o);
03900                      endtime = (long) time(NULL);
03901                      endtime -= starttime;
03902                      rna(endtime * 1000, qe, on, membername, 0);
03903                      if (qe->parent->strategy != QUEUE_STRATEGY_RINGALL) {
03904                         if (qe->parent->timeoutrestart) {
03905                            start_time_tv = ast_tvnow();
03906                         }
03907                         /* Have enough time for a queue member to answer? */
03908                         if (ast_remaining_ms(start_time_tv, orig) > 500) {
03909                            ring_one(qe, outgoing, &numbusies);
03910                            starttime = (long) time(NULL);
03911                         }
03912                      }
03913                      numbusies++;
03914                      break;
03915                   case AST_CONTROL_CONGESTION:
03916                      ast_verb(3, "%s is circuit-busy\n", ochan_name);
03917                      if (in->cdr)
03918                         ast_cdr_busy(in->cdr);
03919                      endtime = (long) time(NULL);
03920                      endtime -= starttime;
03921                      rna(endtime * 1000, qe, on, membername, 0);
03922                      do_hang(o);
03923                      if (qe->parent->strategy != QUEUE_STRATEGY_RINGALL) {
03924                         if (qe->parent->timeoutrestart) {
03925                            start_time_tv = ast_tvnow();
03926                         }
03927                         if (ast_remaining_ms(start_time_tv, orig) > 500) {
03928                            ring_one(qe, outgoing, &numbusies);
03929                            starttime = (long) time(NULL);
03930                         }
03931                      }
03932                      numbusies++;
03933                      break;
03934                   case AST_CONTROL_RINGING:
03935                      ast_verb(3, "%s is ringing\n", ochan_name);
03936 
03937                      /* Start ring indication when the channel is ringing, if specified */
03938                      if (qe->ring_when_ringing) {
03939                         ast_moh_stop(qe->chan);
03940                         ast_indicate(qe->chan, AST_CONTROL_RINGING);
03941                      }
03942                      break;
03943                   case AST_CONTROL_OFFHOOK:
03944                      /* Ignore going off hook */
03945                      break;
03946                   case AST_CONTROL_CONNECTED_LINE:
03947                      if (o->block_connected_update) {
03948                         ast_verb(3, "Connected line update to %s prevented.\n", inchan_name);
03949                         break;
03950                      }
03951                      if (qe->parent->strategy == QUEUE_STRATEGY_RINGALL) {
03952                         struct ast_party_connected_line connected;
03953 
03954                         ast_verb(3, "%s connected line has changed. Saving it until answer for %s\n", ochan_name, inchan_name);
03955                         ast_party_connected_line_set_init(&connected, &o->connected);
03956                         ast_connected_line_parse_data(f->data.ptr, f->datalen, &connected);
03957                         ast_party_connected_line_set(&o->connected, &connected, NULL);
03958                         ast_party_connected_line_free(&connected);
03959                         o->pending_connected_update = 1;
03960                         break;
03961                      }
03962 
03963                      /*
03964                       * Prevent using the CallerID from the outgoing channel since we
03965                       * got a connected line update from it.
03966                       */
03967                      o->dial_callerid_absent = 1;
03968 
03969                      if (ast_channel_connected_line_macro(o->chan, in, f, 1, 1)) {
03970                         ast_indicate_data(in, AST_CONTROL_CONNECTED_LINE, f->data.ptr, f->datalen);
03971                      }
03972                      break;
03973                   case AST_CONTROL_AOC:
03974                      {
03975                         struct ast_aoc_decoded *decoded = ast_aoc_decode(f->data.ptr, f->datalen, o->chan);
03976                         if (decoded && (ast_aoc_get_msg_type(decoded) == AST_AOC_S)) {
03977                            ast_aoc_destroy_decoded(o->aoc_s_rate_list);
03978                            o->aoc_s_rate_list = decoded;
03979                         } else {
03980                            ast_aoc_destroy_decoded(decoded);
03981                         }
03982                      }
03983                      break;
03984                   case AST_CONTROL_REDIRECTING:
03985                      if (qe->parent->strategy == QUEUE_STRATEGY_RINGALL) {
03986                         /*
03987                          * Redirecting updates to the caller make sense only on single
03988                          * call at a time strategies.
03989                          */
03990                         break;
03991                      }
03992                      if (o->block_connected_update) {
03993                         ast_verb(3, "Redirecting update to %s prevented\n",
03994                            inchan_name);
03995                         break;
03996                      }
03997                      ast_verb(3, "%s redirecting info has changed, passing it to %s\n",
03998                         ochan_name, inchan_name);
03999                      if (ast_channel_redirecting_macro(o->chan, in, f, 1, 1)) {
04000                         ast_indicate_data(in, AST_CONTROL_REDIRECTING, f->data.ptr, f->datalen);
04001                      }
04002                      break;
04003                   default:
04004                      ast_debug(1, "Dunno what to do with control type %d\n", f->subclass.integer);
04005                      break;
04006                   }
04007                }
04008                ast_frfree(f);
04009             } else { /* ast_read() returned NULL */
04010                endtime = (long) time(NULL) - starttime;
04011                rna(endtime * 1000, qe, on, membername, 1);
04012                do_hang(o);
04013                if (qe->parent->strategy != QUEUE_STRATEGY_RINGALL) {
04014                   if (qe->parent->timeoutrestart) {
04015                      start_time_tv = ast_tvnow();
04016                   }
04017                   if (ast_remaining_ms(start_time_tv, orig) > 500) {
04018                      ring_one(qe, outgoing, &numbusies);
04019                      starttime = (long) time(NULL);
04020                   }
04021                }
04022             }
04023          }
04024       }
04025 
04026       /* If we received an event from the caller, deal with it. */
04027       if (winner == in) {
04028          f = ast_read(in);
04029          if (!f || ((f->frametype == AST_FRAME_CONTROL) && (f->subclass.integer == AST_CONTROL_HANGUP))) {
04030             /* Got hung up */
04031             *to = -1;
04032             if (f) {
04033                if (f->data.uint32) {
04034                   in->hangupcause = f->data.uint32;
04035                }
04036                ast_frfree(f);
04037             }
04038             return NULL;
04039          }
04040 
04041          if ((f->frametype == AST_FRAME_DTMF) && caller_disconnect && (f->subclass.integer == '*')) {
04042             ast_verb(3, "User hit %c to disconnect call.\n", f->subclass.integer);
04043             *to = 0;
04044             ast_frfree(f);
04045             return NULL;
04046          }
04047          if ((f->frametype == AST_FRAME_DTMF) && valid_exit(qe, f->subclass.integer)) {
04048             ast_verb(3, "User pressed digit: %c\n", f->subclass.integer);
04049             *to = 0;
04050             *digit = f->subclass.integer;
04051             ast_frfree(f);
04052             return NULL;
04053          }
04054 
04055          /* Send the frame from the in channel to all outgoing channels. */
04056          for (o = start; o; o = o->call_next) {
04057             if (!o->stillgoing || !o->chan) {
04058                /* This outgoing channel has died so don't send the frame to it. */
04059                continue;
04060             }
04061             switch (f->frametype) {
04062             case AST_FRAME_CONTROL:
04063                switch (f->subclass.integer) {
04064                case AST_CONTROL_CONNECTED_LINE:
04065                   if (ast_channel_connected_line_macro(in, o->chan, f, 0, 1)) {
04066                      ast_indicate_data(o->chan, f->subclass.integer, f->data.ptr, f->datalen);
04067                   }
04068                   break;
04069                case AST_CONTROL_REDIRECTING:
04070                   if (ast_channel_redirecting_macro(in, o->chan, f, 0, 1)) {
04071                      ast_indicate_data(o->chan, f->subclass.integer, f->data.ptr, f->datalen);
04072                   }
04073                   break;
04074                default:
04075                   /* We are not going to do anything with this frame. */
04076                   goto skip_frame;
04077                }
04078                break;
04079             default:
04080                /* We are not going to do anything with this frame. */
04081                goto skip_frame;
04082             }
04083          }
04084 skip_frame:;
04085 
04086          ast_frfree(f);
04087       }
04088    }
04089 
04090    if (!*to) {
04091       for (o = start; o; o = o->call_next) {
04092          rna(orig, qe, o->interface, o->member->membername, 1);
04093       }
04094    }
04095 
04096 #ifdef HAVE_EPOLL
04097    for (epollo = outgoing; epollo; epollo = epollo->q_next) {
04098       if (epollo->chan)
04099          ast_poll_channel_del(in, epollo->chan);
04100    }
04101 #endif
04102 
04103    return peer;
04104 }
04105 
04106 /*! 
04107  * \brief Check if we should start attempting to call queue members.
04108  *
04109  * A simple process, really. Count the number of members who are available
04110  * to take our call and then see if we are in a position in the queue at
04111  * which a member could accept our call.
04112  *
04113  * \param[in] qe The caller who wants to know if it is his turn
04114  * \retval 0 It is not our turn
04115  * \retval 1 It is our turn
04116  */
04117 static int is_our_turn(struct queue_ent *qe)
04118 {
04119    struct queue_ent *ch;
04120    int res;
04121    int avl;
04122    int idx = 0;
04123    /* This needs a lock. How many members are available to be served? */
04124    ao2_lock(qe->parent);
04125 
04126    avl = num_available_members(qe->parent);
04127 
04128    ch = qe->parent->head;
04129 
04130    ast_debug(1, "There %s %d available %s.\n", avl != 1 ? "are" : "is", avl, avl != 1 ? "members" : "member");
04131 
04132    while ((idx < avl) && (ch) && (ch != qe)) {
04133       if (!ch->pending)
04134          idx++;
04135       ch = ch->next;       
04136    }
04137 
04138    ao2_unlock(qe->parent);
04139    /* If the queue entry is within avl [the number of available members] calls from the top ... 
04140     * Autofill and position check added to support autofill=no (as only calls
04141     * from the front of the queue are valid when autofill is disabled)
04142     */
04143    if (ch && idx < avl && (qe->parent->autofill || qe->pos == 1)) {
04144       ast_debug(1, "It's our turn (%s).\n", qe->chan->name);
04145       res = 1;
04146    } else {
04147       ast_debug(1, "It's not our turn (%s).\n", qe->chan->name);
04148       res = 0;
04149    }
04150 
04151    return res;
04152 }
04153 
04154 /*!
04155  * \brief update rules for queues
04156  *
04157  * Calculate min/max penalties making sure if relative they stay within bounds.
04158  * Update queues penalty and set dialplan vars, goto next list entry.
04159 */
04160 static void update_qe_rule(struct queue_ent *qe)
04161 {
04162    int max_penalty = qe->pr->max_relative ? qe->max_penalty + qe->pr->max_value : qe->pr->max_value;
04163    int min_penalty = qe->pr->min_relative ? qe->min_penalty + qe->pr->min_value : qe->pr->min_value;
04164    char max_penalty_str[20], min_penalty_str[20]; 
04165    /* a relative change to the penalty could put it below 0 */
04166    if (max_penalty < 0)
04167       max_penalty = 0;
04168    if (min_penalty < 0)
04169       min_penalty = 0;
04170    if (min_penalty > max_penalty)
04171       min_penalty = max_penalty;
04172    snprintf(max_penalty_str, sizeof(max_penalty_str), "%d", max_penalty);
04173    snprintf(min_penalty_str, sizeof(min_penalty_str), "%d", min_penalty);
04174    pbx_builtin_setvar_helper(qe->chan, "QUEUE_MAX_PENALTY", max_penalty_str);
04175    pbx_builtin_setvar_helper(qe->chan, "QUEUE_MIN_PENALTY", min_penalty_str);
04176    qe->max_penalty = max_penalty;
04177    qe->min_penalty = min_penalty;
04178    ast_debug(3, "Setting max penalty to %d and min penalty to %d for caller %s since %d seconds have elapsed\n", qe->max_penalty, qe->min_penalty, qe->chan->name, qe->pr->time);
04179    qe->pr = AST_LIST_NEXT(qe->pr, list);
04180 }
04181 
04182 /*! \brief The waiting areas for callers who are not actively calling members
04183  *
04184  * This function is one large loop. This function will return if a caller
04185  * either exits the queue or it becomes that caller's turn to attempt calling
04186  * queue members. Inside the loop, we service the caller with periodic announcements,
04187  * holdtime announcements, etc. as configured in queues.conf
04188  *
04189  * \retval  0 if the caller's turn has arrived
04190  * \retval -1 if the caller should exit the queue.
04191  */
04192 static int wait_our_turn(struct queue_ent *qe, int ringing, enum queue_result *reason)
04193 {
04194    int res = 0;
04195 
04196    /* This is the holding pen for callers 2 through maxlen */
04197    for (;;) {
04198 
04199       if (is_our_turn(qe))
04200          break;
04201 
04202       /* If we have timed out, break out */
04203       if (qe->expire && (time(NULL) >= qe->expire)) {
04204          *reason = QUEUE_TIMEOUT;
04205          break;
04206       }
04207 
04208       if (qe->parent->leavewhenempty) {
04209          int status = 0;
04210 
04211          if ((status = get_member_status(qe->parent, qe->max_penalty, qe->min_penalty, qe->parent->leavewhenempty))) {
04212             *reason = QUEUE_LEAVEEMPTY;
04213             ast_queue_log(qe->parent->name, qe->chan->uniqueid, "NONE", "EXITEMPTY", "%d|%d|%ld", qe->pos, qe->opos, (long) time(NULL) - qe->start);
04214             leave_queue(qe);
04215             break;
04216          }
04217       }
04218 
04219       /* Make a position announcement, if enabled */
04220       if (qe->parent->announcefrequency &&
04221          (res = say_position(qe,ringing)))
04222          break;
04223 
04224       /* If we have timed out, break out */
04225       if (qe->expire && (time(NULL) >= qe->expire)) {
04226          *reason = QUEUE_TIMEOUT;
04227          break;
04228       }
04229 
04230       /* Make a periodic announcement, if enabled */
04231       if (qe->parent->periodicannouncefrequency &&
04232          (res = say_periodic_announcement(qe,ringing)))
04233          break;
04234       
04235       /* see if we need to move to the next penalty level for this queue */
04236       while (qe->pr && ((time(NULL) - qe->start) >= qe->pr->time)) {
04237          update_qe_rule(qe);
04238       }
04239 
04240       /* If we have timed out, break out */
04241       if (qe->expire && (time(NULL) >= qe->expire)) {
04242          *reason = QUEUE_TIMEOUT;
04243          break;
04244       }
04245       
04246       /* Wait a second before checking again */
04247       if ((res = ast_waitfordigit(qe->chan, RECHECK * 1000))) {
04248          if (res > 0 && !valid_exit(qe, res))
04249             res = 0;
04250          else
04251             break;
04252       }
04253       
04254       /* If we have timed out, break out */
04255       if (qe->expire && (time(NULL) >= qe->expire)) {
04256          *reason = QUEUE_TIMEOUT;
04257          break;
04258       }
04259    }
04260 
04261    return res;
04262 }
04263 
04264 /*!
04265  * \brief update the queue status
04266  * \retval Always 0
04267 */
04268 static int update_queue(struct call_queue *q, struct member *member, int callcompletedinsl, int newtalktime)
04269 {
04270    int oldtalktime;
04271 
04272    struct member *mem;
04273    struct call_queue *qtmp;
04274    struct ao2_iterator queue_iter;  
04275    
04276    if (shared_lastcall) {
04277       queue_iter = ao2_iterator_init(queues, 0);
04278       while ((qtmp = ao2_t_iterator_next(&queue_iter, "Iterate through queues"))) {
04279          ao2_lock(qtmp);
04280          if ((mem = ao2_find(qtmp->members, member, OBJ_POINTER))) {
04281             time(&mem->lastcall);
04282             mem->calls++;
04283             mem->lastqueue = q;
04284             ao2_ref(mem, -1);
04285          }
04286          ao2_unlock(qtmp);
04287          queue_t_unref(qtmp, "Done with iterator");
04288       }
04289       ao2_iterator_destroy(&queue_iter);
04290    } else {
04291       ao2_lock(q);
04292       time(&member->lastcall);
04293       member->calls++;
04294       member->lastqueue = q;
04295       ao2_unlock(q);
04296    }  
04297    ao2_lock(q);
04298    q->callscompleted++;
04299    if (callcompletedinsl)
04300       q->callscompletedinsl++;
04301    /* Calculate talktime using the same exponential average as holdtime code*/
04302    oldtalktime = q->talktime;
04303    q->talktime = (((oldtalktime << 2) - oldtalktime) + newtalktime) >> 2;
04304    ao2_unlock(q);
04305    return 0;
04306 }
04307 
04308 /*! \brief Calculate the metric of each member in the outgoing callattempts
04309  *
04310  * A numeric metric is given to each member depending on the ring strategy used
04311  * by the queue. Members with lower metrics will be called before members with
04312  * higher metrics
04313  * \retval -1 if penalties are exceeded
04314  * \retval 0 otherwise
04315  */
04316 static int calc_metric(struct call_queue *q, struct member *mem, int pos, struct queue_ent *qe, struct callattempt *tmp)
04317 {
04318    /* disregarding penalty on too few members? */
04319    int membercount = ao2_container_count(q->members);
04320    unsigned char usepenalty = (membercount <= q->penaltymemberslimit) ? 0 : 1;
04321 
04322    if (usepenalty) {
04323       if ((qe->max_penalty && (mem->penalty > qe->max_penalty)) ||
04324          (qe->min_penalty && (mem->penalty < qe->min_penalty))) {
04325          return -1;
04326       }
04327    } else {
04328       ast_debug(1, "Disregarding penalty, %d members and %d in penaltymemberslimit.\n",
04329            membercount, q->penaltymemberslimit);
04330    }
04331 
04332    switch (q->strategy) {
04333    case QUEUE_STRATEGY_RINGALL:
04334       /* Everyone equal, except for penalty */
04335       tmp->metric = mem->penalty * 1000000 * usepenalty;
04336       break;
04337    case QUEUE_STRATEGY_LINEAR:
04338       if (pos < qe->linpos) {
04339          tmp->metric = 1000 + pos;
04340       } else {
04341          if (pos > qe->linpos)
04342             /* Indicate there is another priority */
04343             qe->linwrapped = 1;
04344          tmp->metric = pos;
04345       }
04346       tmp->metric += mem->penalty * 1000000 * usepenalty;
04347       break;
04348    case QUEUE_STRATEGY_RRORDERED:
04349    case QUEUE_STRATEGY_RRMEMORY:
04350       pos = mem->queuepos;
04351       if (pos < q->rrpos) {
04352          tmp->metric = 1000 + pos;
04353       } else {
04354          if (pos > q->rrpos)
04355             /* Indicate there is another priority */
04356             q->wrapped = 1;
04357          tmp->metric = pos;
04358       }
04359       tmp->metric += mem->penalty * 1000000 * usepenalty;
04360       break;
04361    case QUEUE_STRATEGY_RANDOM:
04362       tmp->metric = ast_random() % 1000;
04363       tmp->metric += mem->penalty * 1000000 * usepenalty;
04364       break;
04365    case QUEUE_STRATEGY_WRANDOM:
04366       tmp->metric = ast_random() % ((1 + mem->penalty) * 1000);
04367       break;
04368    case QUEUE_STRATEGY_FEWESTCALLS:
04369       tmp->metric = mem->calls;
04370       tmp->metric += mem->penalty * 1000000 * usepenalty;
04371       break;
04372    case QUEUE_STRATEGY_LEASTRECENT:
04373       if (!mem->lastcall)
04374          tmp->metric = 0;
04375       else
04376          tmp->metric = 1000000 - (time(NULL) - mem->lastcall);
04377       tmp->metric += mem->penalty * 1000000 * usepenalty;
04378       break;
04379    default:
04380       ast_log(LOG_WARNING, "Can't calculate metric for unknown strategy %d\n", q->strategy);
04381       break;
04382    }
04383    return 0;
04384 }
04385 
04386 enum agent_complete_reason {
04387    CALLER,
04388    AGENT,
04389    TRANSFER
04390 };
04391 
04392 /*! \brief Send out AMI message with member call completion status information */
04393 static void send_agent_complete(const struct queue_ent *qe, const char *queuename,
04394    const struct ast_channel *peer, const struct member *member, time_t callstart,
04395    char *vars, size_t vars_len, enum agent_complete_reason rsn)
04396 {
04397    const char *reason = NULL; /* silence dumb compilers */
04398 
04399    if (!qe->parent->eventwhencalled)
04400       return;
04401 
04402    switch (rsn) {
04403    case CALLER:
04404       reason = "caller";
04405       break;
04406    case AGENT:
04407       reason = "agent";
04408       break;
04409    case TRANSFER:
04410       reason = "transfer";
04411       break;
04412    }
04413 
04414    manager_event(EVENT_FLAG_AGENT, "AgentComplete",
04415       "Queue: %s\r\n"
04416       "Uniqueid: %s\r\n"
04417       "Channel: %s\r\n"
04418       "Member: %s\r\n"
04419       "MemberName: %s\r\n"
04420       "HoldTime: %ld\r\n"
04421       "TalkTime: %ld\r\n"
04422       "Reason: %s\r\n"
04423       "%s",
04424       queuename, qe->chan->uniqueid, peer->name, member->interface, member->membername,
04425       (long)(callstart - qe->start), (long)(time(NULL) - callstart), reason,
04426       qe->parent->eventwhencalled == QUEUE_EVENT_VARIABLES ? vars2manager(qe->chan, vars, vars_len) : "");
04427 }
04428 
04429 struct queue_transfer_ds {
04430    struct queue_ent *qe;
04431    struct member *member;
04432    time_t starttime;
04433    int callcompletedinsl;
04434 };
04435 
04436 static void queue_transfer_destroy(void *data)
04437 {
04438    struct queue_transfer_ds *qtds = data;
04439    ast_free(qtds);
04440 }
04441 
04442 /*! \brief a datastore used to help correctly log attended transfers of queue callers
04443  */
04444 static const struct ast_datastore_info queue_transfer_info = {
04445    .type = "queue_transfer",
04446    .chan_fixup = queue_transfer_fixup,
04447    .destroy = queue_transfer_destroy,
04448 };
04449 
04450 /*! \brief Log an attended transfer when a queue caller channel is masqueraded
04451  *
04452  * When a caller is masqueraded, we want to log a transfer. Fixup time is the closest we can come to when
04453  * the actual transfer occurs. This happens during the masquerade after datastores are moved from old_chan
04454  * to new_chan. This is why new_chan is referenced for exten, context, and datastore information.
04455  *
04456  * At the end of this, we want to remove the datastore so that this fixup function is not called on any
04457  * future masquerades of the caller during the current call.
04458  */
04459 static void queue_transfer_fixup(void *data, struct ast_channel *old_chan, struct ast_channel *new_chan)
04460 {
04461    struct queue_transfer_ds *qtds = data;
04462    struct queue_ent *qe = qtds->qe;
04463    struct member *member = qtds->member;
04464    time_t callstart = qtds->starttime;
04465    int callcompletedinsl = qtds->callcompletedinsl;
04466    struct ast_datastore *datastore;
04467 
04468    ast_queue_log(qe->parent->name, qe->chan->uniqueid, member->membername, "TRANSFER", "%s|%s|%ld|%ld|%d",
04469             new_chan->exten, new_chan->context, (long) (callstart - qe->start),
04470             (long) (time(NULL) - callstart), qe->opos);
04471 
04472    update_queue(qe->parent, member, callcompletedinsl, (time(NULL) - callstart));
04473    
04474    /* No need to lock the channels because they are already locked in ast_do_masquerade */
04475    if ((datastore = ast_channel_datastore_find(old_chan, &queue_transfer_info, NULL))) {
04476       ast_channel_datastore_remove(old_chan, datastore);
04477    } else {
04478       ast_log(LOG_WARNING, "Can't find the queue_transfer datastore.\n");
04479    }
04480 }
04481 
04482 /*! \brief mechanism to tell if a queue caller was atxferred by a queue member.
04483  *
04484  * When a caller is atxferred, then the queue_transfer_info datastore
04485  * is removed from the channel. If it's still there after the bridge is
04486  * broken, then the caller was not atxferred.
04487  *
04488  * \note Only call this with chan locked
04489  */
04490 static int attended_transfer_occurred(struct ast_channel *chan)
04491 {
04492    return ast_channel_datastore_find(chan, &queue_transfer_info, NULL) ? 0 : 1;
04493 }
04494 
04495 /*! \brief create a datastore for storing relevant info to log attended transfers in the queue_log
04496  */
04497 static struct ast_datastore *setup_transfer_datastore(struct queue_ent *qe, struct member *member, time_t starttime, int callcompletedinsl)
04498 {
04499    struct ast_datastore *ds;
04500    struct queue_transfer_ds *qtds = ast_calloc(1, sizeof(*qtds));
04501 
04502    if (!qtds) {
04503       ast_log(LOG_WARNING, "Memory allocation error!\n");
04504       return NULL;
04505    }
04506 
04507    ast_channel_lock(qe->chan);
04508    if (!(ds = ast_datastore_alloc(&queue_transfer_info, NULL))) {
04509       ast_channel_unlock(qe->chan);
04510       ast_free(qtds);
04511       ast_log(LOG_WARNING, "Unable to create transfer datastore. queue_log will not show attended transfer\n");
04512       return NULL;
04513    }
04514 
04515    qtds->qe = qe;
04516    /* This member is refcounted in try_calling, so no need to add it here, too */
04517    qtds->member = member;
04518    qtds->starttime = starttime;
04519    qtds->callcompletedinsl = callcompletedinsl;
04520    ds->data = qtds;
04521    ast_channel_datastore_add(qe->chan, ds);
04522    ast_channel_unlock(qe->chan);
04523    return ds;
04524 }
04525 
04526 struct queue_end_bridge {
04527    struct call_queue *q;
04528    struct ast_channel *chan;
04529 };
04530 
04531 static void end_bridge_callback_data_fixup(struct ast_bridge_config *bconfig, struct ast_channel *originator, struct ast_channel *terminator)
04532 {
04533    struct queue_end_bridge *qeb = bconfig->end_bridge_callback_data;
04534    ao2_ref(qeb, +1);
04535    qeb->chan = originator;
04536 }
04537 
04538 static void end_bridge_callback(void *data)
04539 {
04540    struct queue_end_bridge *qeb = data;
04541    struct call_queue *q = qeb->q;
04542    struct ast_channel *chan = qeb->chan;
04543 
04544    if (ao2_ref(qeb, -1) == 1) {
04545       set_queue_variables(q, chan);
04546       /* This unrefs the reference we made in try_calling when we allocated qeb */
04547       queue_t_unref(q, "Expire bridge_config reference");
04548    }
04549 }
04550 
04551 /*! \brief A large function which calls members, updates statistics, and bridges the caller and a member
04552  * 
04553  * Here is the process of this function
04554  * 1. Process any options passed to the Queue() application. Options here mean the third argument to Queue()
04555  * 2. Iterate trough the members of the queue, creating a callattempt corresponding to each member. During this
04556  *    iteration, we also check the dialed_interfaces datastore to see if we have already attempted calling this
04557  *    member. If we have, we do not create a callattempt. This is in place to prevent call forwarding loops. Also
04558  *    during each iteration, we call calc_metric to determine which members should be rung when.
04559  * 3. Call ring_one to place a call to the appropriate member(s)
04560  * 4. Call wait_for_answer to wait for an answer. If no one answers, return.
04561  * 5. Take care of any holdtime announcements, member delays, or other options which occur after a call has been answered.
04562  * 6. Start the monitor or mixmonitor if the option is set
04563  * 7. Remove the caller from the queue to allow other callers to advance
04564  * 8. Bridge the call.
04565  * 9. Do any post processing after the call has disconnected.
04566  *
04567  * \param[in] qe the queue_ent structure which corresponds to the caller attempting to reach members
04568  * \param[in] options the options passed as the third parameter to the Queue() application
04569  * \param[in] announceoverride filename to play to user when waiting 
04570  * \param[in] url the url passed as the fourth parameter to the Queue() application
04571  * \param[in,out] tries the number of times we have tried calling queue members
04572  * \param[out] noption set if the call to Queue() has the 'n' option set.
04573  * \param[in] agi the agi passed as the fifth parameter to the Queue() application
04574  * \param[in] macro the macro passed as the sixth parameter to the Queue() application
04575  * \param[in] gosub the gosub passed as the seventh parameter to the Queue() application
04576  * \param[in] ringing 1 if the 'r' option is set, otherwise 0
04577  */
04578 static int try_calling(struct queue_ent *qe, const char *options, char *announceoverride, const char *url, int *tries, int *noption, const char *agi, const char *macro, const char *gosub, int ringing)
04579 {
04580    struct member *cur;
04581    struct callattempt *outgoing = NULL; /* the list of calls we are building */
04582    int to, orig;
04583    char oldexten[AST_MAX_EXTENSION]="";
04584    char oldcontext[AST_MAX_CONTEXT]="";
04585    char queuename[256]="";
04586    char interfacevar[256]="";
04587    struct ast_channel *peer;
04588    struct ast_channel *which;
04589    struct callattempt *lpeer;
04590    struct member *member;
04591    struct ast_app *application;
04592    int res = 0, bridge = 0;
04593    int numbusies = 0;
04594    int x=0;
04595    char *announce = NULL;
04596    char digit = 0;
04597    time_t callstart;
04598    time_t now = time(NULL);
04599    struct ast_bridge_config bridge_config;
04600    char nondataquality = 1;
04601    char *agiexec = NULL;
04602    char *macroexec = NULL;
04603    char *gosubexec = NULL;
04604    const char *monitorfilename;
04605    const char *monitor_exec;
04606    const char *monitor_options;
04607    char tmpid[256], tmpid2[256];
04608    char meid[1024], meid2[1024];
04609    char mixmonargs[1512];
04610    struct ast_app *mixmonapp = NULL;
04611    char *p;
04612    char vars[2048];
04613    int forwardsallowed = 1;
04614    int block_connected_line = 0;
04615    int callcompletedinsl;
04616    struct ao2_iterator memi;
04617    struct ast_datastore *datastore, *transfer_ds;
04618    struct queue_end_bridge *queue_end_bridge = NULL;
04619 
04620    ast_channel_lock(qe->chan);
04621    datastore = ast_channel_datastore_find(qe->chan, &dialed_interface_info, NULL);
04622    ast_channel_unlock(qe->chan);
04623 
04624    memset(&bridge_config, 0, sizeof(bridge_config));
04625    tmpid[0] = 0;
04626    meid[0] = 0;
04627    time(&now);
04628 
04629    /* If we've already exceeded our timeout, then just stop
04630     * This should be extremely rare. queue_exec will take care
04631     * of removing the caller and reporting the timeout as the reason.
04632     */
04633    if (qe->expire && now >= qe->expire) {
04634       res = 0;
04635       goto out;
04636    }
04637       
04638    for (; options && *options; options++)
04639       switch (*options) {
04640       case 't':
04641          ast_set_flag(&(bridge_config.features_callee), AST_FEATURE_REDIRECT);
04642          break;
04643       case 'T':
04644          ast_set_flag(&(bridge_config.features_caller), AST_FEATURE_REDIRECT);
04645          break;
04646       case 'w':
04647          ast_set_flag(&(bridge_config.features_callee), AST_FEATURE_AUTOMON);
04648          break;
04649       case 'W':
04650          ast_set_flag(&(bridge_config.features_caller), AST_FEATURE_AUTOMON);
04651          break;
04652       case 'c':
04653          ast_set_flag(&(bridge_config.features_caller), AST_FEATURE_NO_H_EXTEN);
04654          break;
04655       case 'd':
04656          nondataquality = 0;
04657          break;
04658       case 'h':
04659          ast_set_flag(&(bridge_config.features_callee), AST_FEATURE_DISCONNECT);
04660          break;
04661       case 'H':
04662          ast_set_flag(&(bridge_config.features_caller), AST_FEATURE_DISCONNECT);
04663          break;
04664       case 'k':
04665          ast_set_flag(&(bridge_config.features_callee), AST_FEATURE_PARKCALL);
04666          break;
04667       case 'K':
04668          ast_set_flag(&(bridge_config.features_caller), AST_FEATURE_PARKCALL);
04669          break;
04670       case 'n':
04671          if (qe->parent->strategy == QUEUE_STRATEGY_RRMEMORY || qe->parent->strategy == QUEUE_STRATEGY_LINEAR || qe->parent->strategy == QUEUE_STRATEGY_RRORDERED)
04672             (*tries)++;
04673          else
04674             *tries = ao2_container_count(qe->parent->members);
04675          *noption = 1;
04676          break;
04677       case 'i':
04678          forwardsallowed = 0;
04679          break;
04680       case 'I':
04681          block_connected_line = 1;
04682          break;
04683       case 'x':
04684          ast_set_flag(&(bridge_config.features_callee), AST_FEATURE_AUTOMIXMON);
04685          break;
04686       case 'X':
04687          ast_set_flag(&(bridge_config.features_caller), AST_FEATURE_AUTOMIXMON);
04688          break;
04689       case 'C':
04690          qe->cancel_answered_elsewhere = 1;
04691          break;
04692       }
04693 
04694    /* if the calling channel has the ANSWERED_ELSEWHERE flag set, make sure this is inherited. 
04695       (this is mainly to support chan_local)
04696    */
04697    if (ast_test_flag(qe->chan, AST_FLAG_ANSWERED_ELSEWHERE)) {
04698       qe->cancel_answered_elsewhere = 1;
04699    }
04700 
04701    ao2_lock(qe->parent);
04702    ast_debug(1, "%s is trying to call a queue member.\n",
04703                      qe->chan->name);
04704    ast_copy_string(queuename, qe->parent->name, sizeof(queuename));
04705    if (!ast_strlen_zero(qe->announce))
04706       announce = qe->announce;
04707    if (!ast_strlen_zero(announceoverride))
04708       announce = announceoverride;
04709 
04710    memi = ao2_iterator_init(qe->parent->members, 0);
04711    while ((cur = ao2_iterator_next(&memi))) {
04712       struct callattempt *tmp = ast_calloc(1, sizeof(*tmp));
04713       struct ast_dialed_interface *di;
04714       AST_LIST_HEAD(, ast_dialed_interface) *dialed_interfaces;
04715       if (!tmp) {
04716          ao2_ref(cur, -1);
04717          ao2_iterator_destroy(&memi);
04718          ao2_unlock(qe->parent);
04719          goto out;
04720       }
04721       if (!datastore) {
04722          if (!(datastore = ast_datastore_alloc(&dialed_interface_info, NULL))) {
04723             callattempt_free(tmp);
04724             ao2_ref(cur, -1);
04725             ao2_iterator_destroy(&memi);
04726             ao2_unlock(qe->parent);
04727             goto out;
04728          }
04729          datastore->inheritance = DATASTORE_INHERIT_FOREVER;
04730          if (!(dialed_interfaces = ast_calloc(1, sizeof(*dialed_interfaces)))) {
04731             callattempt_free(tmp);
04732             ao2_ref(cur, -1);
04733             ao2_iterator_destroy(&memi);
04734             ao2_unlock(qe->parent);
04735             goto out;
04736          }
04737          datastore->data = dialed_interfaces;
04738          AST_LIST_HEAD_INIT(dialed_interfaces);
04739 
04740          ast_channel_lock(qe->chan);
04741          ast_channel_datastore_add(qe->chan, datastore);
04742          ast_channel_unlock(qe->chan);
04743       } else
04744          dialed_interfaces = datastore->data;
04745 
04746       AST_LIST_LOCK(dialed_interfaces);
04747       AST_LIST_TRAVERSE(dialed_interfaces, di, list) {
04748          if (!strcasecmp(cur->interface, di->interface)) {
04749             ast_debug(1, "Skipping dialing interface '%s' since it has already been dialed\n", 
04750                di->interface);
04751             break;
04752          }
04753       }
04754       AST_LIST_UNLOCK(dialed_interfaces);
04755 
04756       if (di) {
04757          callattempt_free(tmp);
04758          ao2_ref(cur, -1);
04759          continue;
04760       }
04761 
04762       /* It is always ok to dial a Local interface.  We only keep track of
04763        * which "real" interfaces have been dialed.  The Local channel will
04764        * inherit this list so that if it ends up dialing a real interface,
04765        * it won't call one that has already been called. */
04766       if (strncasecmp(cur->interface, "Local/", 6)) {
04767          if (!(di = ast_calloc(1, sizeof(*di) + strlen(cur->interface)))) {
04768             callattempt_free(tmp);
04769             ao2_ref(cur, -1);
04770             ao2_iterator_destroy(&memi);
04771             ao2_unlock(qe->parent);
04772             goto out;
04773          }
04774          strcpy(di->interface, cur->interface);
04775 
04776          AST_LIST_LOCK(dialed_interfaces);
04777          AST_LIST_INSERT_TAIL(dialed_interfaces, di, list);
04778          AST_LIST_UNLOCK(dialed_interfaces);
04779       }
04780 
04781       /*
04782        * Seed the callattempt's connected line information with previously
04783        * acquired connected line info from the queued channel.  The
04784        * previously acquired connected line info could have been set
04785        * through the CONNECTED_LINE dialplan function.
04786        */
04787       ast_channel_lock(qe->chan);
04788       ast_party_connected_line_copy(&tmp->connected, &qe->chan->connected);
04789       ast_channel_unlock(qe->chan);
04790 
04791       tmp->block_connected_update = block_connected_line;
04792       tmp->stillgoing = 1;
04793       tmp->member = cur;/* Place the reference for cur into callattempt. */
04794       tmp->lastcall = cur->lastcall;
04795       tmp->lastqueue = cur->lastqueue;
04796       ast_copy_string(tmp->interface, cur->interface, sizeof(tmp->interface));
04797       /* Special case: If we ring everyone, go ahead and ring them, otherwise
04798          just calculate their metric for the appropriate strategy */
04799       if (!calc_metric(qe->parent, cur, x++, qe, tmp)) {
04800          /* Put them in the list of outgoing thingies...  We're ready now.
04801             XXX If we're forcibly removed, these outgoing calls won't get
04802             hung up XXX */
04803          tmp->q_next = outgoing;
04804          outgoing = tmp;      
04805          /* If this line is up, don't try anybody else */
04806          if (outgoing->chan && (outgoing->chan->_state == AST_STATE_UP))
04807             break;
04808       } else {
04809          callattempt_free(tmp);
04810       }
04811    }
04812    ao2_iterator_destroy(&memi);
04813 
04814    if (qe->parent->timeoutpriority == TIMEOUT_PRIORITY_APP) {
04815       /* Application arguments have higher timeout priority (behaviour for <=1.6) */
04816       if (qe->expire && (!qe->parent->timeout || (qe->expire - now) <= qe->parent->timeout))
04817          to = (qe->expire - now) * 1000;
04818       else
04819          to = (qe->parent->timeout) ? qe->parent->timeout * 1000 : -1;
04820    } else {
04821       /* Config timeout is higher priority thatn application timeout */
04822       if (qe->expire && qe->expire<=now) {
04823          to = 0;
04824       } else if (qe->parent->timeout) {
04825          to = qe->parent->timeout * 1000;
04826       } else {
04827          to = -1;
04828       }
04829    }
04830    orig = to;
04831    ++qe->pending;
04832    ao2_unlock(qe->parent);
04833    ring_one(qe, outgoing, &numbusies);
04834    lpeer = wait_for_answer(qe, outgoing, &to, &digit, numbusies,
04835       ast_test_flag(&(bridge_config.features_caller), AST_FEATURE_DISCONNECT),
04836       forwardsallowed);
04837    /* The ast_channel_datastore_remove() function could fail here if the
04838     * datastore was moved to another channel during a masquerade. If this is
04839     * the case, don't free the datastore here because later, when the channel
04840     * to which the datastore was moved hangs up, it will attempt to free this
04841     * datastore again, causing a crash
04842     */
04843    ast_channel_lock(qe->chan);
04844    if (datastore && !ast_channel_datastore_remove(qe->chan, datastore)) {
04845       ast_datastore_free(datastore);
04846    }
04847    ast_channel_unlock(qe->chan);
04848    ao2_lock(qe->parent);
04849    if (qe->parent->strategy == QUEUE_STRATEGY_RRMEMORY || qe->parent->strategy == QUEUE_STRATEGY_RRORDERED) {
04850       store_next_rr(qe, outgoing);
04851 
04852    }
04853    if (qe->parent->strategy == QUEUE_STRATEGY_LINEAR) {
04854       store_next_lin(qe, outgoing);
04855    }
04856    ao2_unlock(qe->parent);
04857    peer = lpeer ? lpeer->chan : NULL;
04858    if (!peer) {
04859       qe->pending = 0;
04860       if (to) {
04861          /* Must gotten hung up */
04862          res = -1;
04863       } else {
04864          /* User exited by pressing a digit */
04865          res = digit;
04866       }
04867       if (res == -1)
04868          ast_debug(1, "%s: Nobody answered.\n", qe->chan->name);
04869       if (ast_cdr_isset_unanswered()) {
04870          /* channel contains the name of one of the outgoing channels
04871             in its CDR; zero out this CDR to avoid a dual-posting */
04872          struct callattempt *o;
04873          for (o = outgoing; o; o = o->q_next) {
04874             if (!o->chan) {
04875                continue;
04876             }
04877             if (strcmp(o->chan->cdr->dstchannel, qe->chan->cdr->dstchannel) == 0) {
04878                ast_set_flag(o->chan->cdr, AST_CDR_FLAG_POST_DISABLED);
04879                break;
04880             }
04881          }
04882       }
04883    } else { /* peer is valid */
04884       /* Ah ha!  Someone answered within the desired timeframe.  Of course after this
04885          we will always return with -1 so that it is hung up properly after the
04886          conversation.  */
04887       if (!strcmp(qe->chan->tech->type, "DAHDI"))
04888          ast_channel_setoption(qe->chan, AST_OPTION_TONE_VERIFY, &nondataquality, sizeof(nondataquality), 0);
04889       if (!strcmp(peer->tech->type, "DAHDI"))
04890          ast_channel_setoption(peer, AST_OPTION_TONE_VERIFY, &nondataquality, sizeof(nondataquality), 0);
04891       /* Update parameters for the queue */
04892       time(&now);
04893       recalc_holdtime(qe, (now - qe->start));
04894       ao2_lock(qe->parent);
04895       callcompletedinsl = ((now - qe->start) <= qe->parent->servicelevel);
04896       ao2_unlock(qe->parent);
04897       member = lpeer->member;
04898       /* Increment the refcount for this member, since we're going to be using it for awhile in here. */
04899       ao2_ref(member, 1);
04900       hangupcalls(outgoing, peer, qe->cancel_answered_elsewhere);
04901       outgoing = NULL;
04902       if (announce || qe->parent->reportholdtime || qe->parent->memberdelay) {
04903          int res2;
04904 
04905          res2 = ast_autoservice_start(qe->chan);
04906          if (!res2) {
04907             if (qe->parent->memberdelay) {
04908                ast_log(LOG_NOTICE, "Delaying member connect for %d seconds\n", qe->parent->memberdelay);
04909                res2 = ast_safe_sleep(peer, qe->parent->memberdelay * 1000);
04910             }
04911             if (!res2 && announce) {
04912                if (play_file(peer, announce) < 0) {
04913                   ast_log(LOG_ERROR, "play_file failed for '%s' on %s\n", announce, peer->name);
04914                }
04915             }
04916             if (!res2 && qe->parent->reportholdtime) {
04917                if (!play_file(peer, qe->parent->sound_reporthold)) {
04918                   int holdtime, holdtimesecs;
04919 
04920                   time(&now);
04921                   holdtime = abs((now - qe->start) / 60);
04922                   holdtimesecs = abs((now - qe->start) % 60);
04923                   if (holdtime > 0) {
04924                      ast_say_number(peer, holdtime, AST_DIGIT_ANY, peer->language, NULL);
04925                      if (play_file(peer, qe->parent->sound_minutes) < 0) {
04926                         ast_log(LOG_ERROR, "play_file failed for '%s' on %s\n", qe->parent->sound_minutes, peer->name);
04927                      }
04928                   }
04929                   if (holdtimesecs > 1) {
04930                      ast_say_number(peer, holdtimesecs, AST_DIGIT_ANY, peer->language, NULL);
04931                      if (play_file(peer, qe->parent->sound_seconds) < 0) {
04932                         ast_log(LOG_ERROR, "play_file failed for '%s' on %s\n", qe->parent->sound_seconds, peer->name);
04933                      }
04934                   }
04935                }
04936             }
04937             ast_autoservice_stop(qe->chan);
04938          }
04939          if (ast_check_hangup(peer)) {
04940             /* Agent must have hung up */
04941             ast_log(LOG_WARNING, "Agent on %s hungup on the customer.\n", peer->name);
04942             ast_queue_log(queuename, qe->chan->uniqueid, member->membername, "AGENTDUMP", "%s", "");
04943             if (qe->parent->eventwhencalled)
04944                manager_event(EVENT_FLAG_AGENT, "AgentDump",
04945                      "Queue: %s\r\n"
04946                      "Uniqueid: %s\r\n"
04947                      "Channel: %s\r\n"
04948                      "Member: %s\r\n"
04949                      "MemberName: %s\r\n"
04950                      "%s",
04951                      queuename, qe->chan->uniqueid, peer->name, member->interface, member->membername,
04952                      qe->parent->eventwhencalled == QUEUE_EVENT_VARIABLES ? vars2manager(qe->chan, vars, sizeof(vars)) : "");
04953             ast_hangup(peer);
04954             ao2_ref(member, -1);
04955             goto out;
04956          } else if (ast_check_hangup(qe->chan)) {
04957             /* Caller must have hung up just before being connected */
04958             ast_log(LOG_NOTICE, "Caller was about to talk to agent on %s but the caller hungup.\n", peer->name);
04959             ast_queue_log(queuename, qe->chan->uniqueid, member->membername, "ABANDON", "%d|%d|%ld", qe->pos, qe->opos, (long) time(NULL) - qe->start);
04960             record_abandoned(qe);
04961             ast_hangup(peer);
04962             ao2_ref(member, -1);
04963             return -1;
04964          }
04965       }
04966       /* Stop music on hold */
04967       if (ringing)
04968          ast_indicate(qe->chan,-1);
04969       else
04970          ast_moh_stop(qe->chan);
04971       /* If appropriate, log that we have a destination channel */
04972       if (qe->chan->cdr)
04973          ast_cdr_setdestchan(qe->chan->cdr, peer->name);
04974       /* Make sure channels are compatible */
04975       res = ast_channel_make_compatible(qe->chan, peer);
04976       if (res < 0) {
04977          ast_queue_log(queuename, qe->chan->uniqueid, member->membername, "SYSCOMPAT", "%s", "");
04978          ast_log(LOG_WARNING, "Had to drop call because I couldn't make %s compatible with %s\n", qe->chan->name, peer->name);
04979          record_abandoned(qe);
04980          ast_cdr_failed(qe->chan->cdr);
04981          ast_hangup(peer);
04982          ao2_ref(member, -1);
04983          return -1;
04984       }
04985 
04986       /* Play announcement to the caller telling it's his turn if defined */
04987       if (!ast_strlen_zero(qe->parent->sound_callerannounce)) {
04988          if (play_file(qe->chan, qe->parent->sound_callerannounce))
04989             ast_log(LOG_WARNING, "Announcement file '%s' is unavailable, continuing anyway...\n", qe->parent->sound_callerannounce);
04990       }
04991 
04992       ao2_lock(qe->parent);
04993       /* if setinterfacevar is defined, make member variables available to the channel */
04994       /* use  pbx_builtin_setvar to set a load of variables with one call */
04995       if (qe->parent->setinterfacevar) {
04996          snprintf(interfacevar, sizeof(interfacevar), "MEMBERINTERFACE=%s,MEMBERNAME=%s,MEMBERCALLS=%d,MEMBERLASTCALL=%ld,MEMBERPENALTY=%d,MEMBERDYNAMIC=%d,MEMBERREALTIME=%d",
04997             member->interface, member->membername, member->calls, (long)member->lastcall, member->penalty, member->dynamic, member->realtime);
04998          pbx_builtin_setvar_multiple(qe->chan, interfacevar);
04999          pbx_builtin_setvar_multiple(peer, interfacevar);
05000       }
05001       
05002       /* if setqueueentryvar is defined, make queue entry (i.e. the caller) variables available to the channel */
05003       /* use  pbx_builtin_setvar to set a load of variables with one call */
05004       if (qe->parent->setqueueentryvar) {
05005          snprintf(interfacevar, sizeof(interfacevar), "QEHOLDTIME=%ld,QEORIGINALPOS=%d",
05006             (long) time(NULL) - qe->start, qe->opos);
05007          pbx_builtin_setvar_multiple(qe->chan, interfacevar);
05008          pbx_builtin_setvar_multiple(peer, interfacevar);
05009       }
05010    
05011       ao2_unlock(qe->parent);
05012 
05013       /* try to set queue variables if configured to do so*/
05014       set_queue_variables(qe->parent, qe->chan);
05015       set_queue_variables(qe->parent, peer);
05016       
05017       ast_channel_lock(qe->chan);
05018       if ((monitorfilename = pbx_builtin_getvar_helper(qe->chan, "MONITOR_FILENAME"))) {
05019             monitorfilename = ast_strdupa(monitorfilename);
05020       }
05021       ast_channel_unlock(qe->chan);
05022       /* Begin Monitoring */
05023       if (qe->parent->monfmt && *qe->parent->monfmt) {
05024          if (!qe->parent->montype) {
05025             const char *monexec;
05026             ast_debug(1, "Starting Monitor as requested.\n");
05027             ast_channel_lock(qe->chan);
05028             if ((monexec = pbx_builtin_getvar_helper(qe->chan, "MONITOR_EXEC")) || pbx_builtin_getvar_helper(qe->chan, "MONITOR_EXEC_ARGS")) {
05029                which = qe->chan;
05030                monexec = monexec ? ast_strdupa(monexec) : NULL;
05031             }
05032             else
05033                which = peer;
05034             ast_channel_unlock(qe->chan);
05035             if (monitorfilename) {
05036                ast_monitor_start(which, qe->parent->monfmt, monitorfilename, 1, X_REC_IN | X_REC_OUT);
05037             } else if (qe->chan->cdr) {
05038                ast_monitor_start(which, qe->parent->monfmt, qe->chan->cdr->uniqueid, 1, X_REC_IN | X_REC_OUT);
05039             } else {
05040                /* Last ditch effort -- no CDR, make up something */
05041                snprintf(tmpid, sizeof(tmpid), "chan-%lx", ast_random());
05042                ast_monitor_start(which, qe->parent->monfmt, tmpid, 1, X_REC_IN | X_REC_OUT);
05043             }
05044             if (!ast_strlen_zero(monexec)) {
05045                ast_monitor_setjoinfiles(which, 1);
05046             }
05047          } else {
05048             mixmonapp = pbx_findapp("MixMonitor");
05049             
05050             if (mixmonapp) {
05051                ast_debug(1, "Starting MixMonitor as requested.\n");
05052                if (!monitorfilename) {
05053                   if (qe->chan->cdr)
05054                      ast_copy_string(tmpid, qe->chan->cdr->uniqueid, sizeof(tmpid));
05055                   else
05056                      snprintf(tmpid, sizeof(tmpid), "chan-%lx", ast_random());
05057                } else {
05058                   const char *m = monitorfilename;
05059                   for (p = tmpid2; p < tmpid2 + sizeof(tmpid2) - 1; p++, m++) {
05060                      switch (*m) {
05061                      case '^':
05062                         if (*(m + 1) == '{')
05063                            *p = '$';
05064                         break;
05065                      case ',':
05066                         *p++ = '\\';
05067                         /* Fall through */
05068                      default:
05069                         *p = *m;
05070                      }
05071                      if (*m == '\0')
05072                         break;
05073                   }
05074                   if (p == tmpid2 + sizeof(tmpid2))
05075                      tmpid2[sizeof(tmpid2) - 1] = '\0';
05076 
05077                   pbx_substitute_variables_helper(qe->chan, tmpid2, tmpid, sizeof(tmpid) - 1);
05078                }
05079 
05080                ast_channel_lock(qe->chan);
05081                if ((monitor_exec = pbx_builtin_getvar_helper(qe->chan, "MONITOR_EXEC"))) {
05082                      monitor_exec = ast_strdupa(monitor_exec);
05083                }
05084                if ((monitor_options = pbx_builtin_getvar_helper(qe->chan, "MONITOR_OPTIONS"))) {
05085                      monitor_options = ast_strdupa(monitor_options);
05086                } else {
05087                   monitor_options = "";
05088                }
05089                ast_channel_unlock(qe->chan);
05090 
05091                if (monitor_exec) {
05092                   const char *m = monitor_exec;
05093                   for (p = meid2; p < meid2 + sizeof(meid2) - 1; p++, m++) {
05094                      switch (*m) {
05095                      case '^':
05096                         if (*(m + 1) == '{')
05097                            *p = '$';
05098                         break;
05099                      case ',':
05100                         *p++ = '\\';
05101                         /* Fall through */
05102                      default:
05103                         *p = *m;
05104                      }
05105                      if (*m == '\0')
05106                         break;
05107                   }
05108                   if (p == meid2 + sizeof(meid2))
05109                      meid2[sizeof(meid2) - 1] = '\0';
05110 
05111                   pbx_substitute_variables_helper(qe->chan, meid2, meid, sizeof(meid) - 1);
05112                }
05113    
05114                snprintf(tmpid2, sizeof(tmpid2), "%s.%s", tmpid, qe->parent->monfmt);
05115 
05116                if (!ast_strlen_zero(monitor_exec))
05117                   snprintf(mixmonargs, sizeof(mixmonargs), "%s,b%s,%s", tmpid2, monitor_options, monitor_exec);
05118                else
05119                   snprintf(mixmonargs, sizeof(mixmonargs), "%s,b%s", tmpid2, monitor_options);
05120                
05121                ast_debug(1, "Arguments being passed to MixMonitor: %s\n", mixmonargs);
05122                /* We purposely lock the CDR so that pbx_exec does not update the application data */
05123                if (qe->chan->cdr)
05124                   ast_set_flag(qe->chan->cdr, AST_CDR_FLAG_LOCKED);
05125                pbx_exec(qe->chan, mixmonapp, mixmonargs);
05126                if (qe->chan->cdr)
05127                   ast_clear_flag(qe->chan->cdr, AST_CDR_FLAG_LOCKED);
05128 
05129             } else {
05130                ast_log(LOG_WARNING, "Asked to run MixMonitor on this call, but cannot find the MixMonitor app!\n");
05131             }
05132          }
05133       }
05134       /* Drop out of the queue at this point, to prepare for next caller */
05135       leave_queue(qe);        
05136       if (!ast_strlen_zero(url) && ast_channel_supports_html(peer)) {
05137          ast_debug(1, "app_queue: sendurl=%s.\n", url);
05138          ast_channel_sendurl(peer, url);
05139       }
05140       
05141       /* run a macro for this connection if defined. The macro simply returns, no action is taken on the result */
05142       /* use macro from dialplan if passed as a option, otherwise use the default queue macro */
05143       if (!ast_strlen_zero(macro)) {
05144             macroexec = ast_strdupa(macro);
05145       } else {
05146          if (qe->parent->membermacro)
05147             macroexec = ast_strdupa(qe->parent->membermacro);
05148       }
05149 
05150       if (!ast_strlen_zero(macroexec)) {
05151          ast_debug(1, "app_queue: macro=%s.\n", macroexec);
05152          
05153          res = ast_autoservice_start(qe->chan);
05154          if (res) {
05155             ast_log(LOG_ERROR, "Unable to start autoservice on calling channel\n");
05156             res = -1;
05157          }
05158          
05159          application = pbx_findapp("Macro");
05160 
05161          if (application) {
05162             res = pbx_exec(peer, application, macroexec);
05163             ast_debug(1, "Macro exited with status %d\n", res);
05164             res = 0;
05165          } else {
05166             ast_log(LOG_ERROR, "Could not find application Macro\n");
05167             res = -1;
05168          }
05169 
05170          if (ast_autoservice_stop(qe->chan) < 0) {
05171             ast_log(LOG_ERROR, "Could not stop autoservice on calling channel\n");
05172             res = -1;
05173          }
05174       }
05175 
05176       /* run a gosub for this connection if defined. The gosub simply returns, no action is taken on the result */
05177       /* use gosub from dialplan if passed as a option, otherwise use the default queue gosub */
05178       if (!ast_strlen_zero(gosub)) {
05179             gosubexec = ast_strdupa(gosub);
05180       } else {
05181          if (qe->parent->membergosub)
05182             gosubexec = ast_strdupa(qe->parent->membergosub);
05183       }
05184 
05185       if (!ast_strlen_zero(gosubexec)) {
05186          ast_debug(1, "app_queue: gosub=%s.\n", gosubexec);
05187          
05188          res = ast_autoservice_start(qe->chan);
05189          if (res) {
05190             ast_log(LOG_ERROR, "Unable to start autoservice on calling channel\n");
05191             res = -1;
05192          }
05193          
05194          application = pbx_findapp("Gosub");
05195          
05196          if (application) {
05197             char *gosub_args, *gosub_argstart;
05198 
05199             /* Set where we came from */
05200             ast_copy_string(peer->context, "app_queue_gosub_virtual_context", sizeof(peer->context));
05201             ast_copy_string(peer->exten, "s", sizeof(peer->exten));
05202             peer->priority = 0;
05203 
05204             gosub_argstart = strchr(gosubexec, ',');
05205             if (gosub_argstart) {
05206                const char *what_is_s = "s";
05207                *gosub_argstart = 0;
05208                if (!ast_exists_extension(peer, gosubexec, "s", 1, S_COR(peer->caller.id.number.valid, peer->caller.id.number.str, NULL)) &&
05209                    ast_exists_extension(peer, gosubexec, "~~s~~", 1, S_COR(peer->caller.id.number.valid, peer->caller.id.number.str, NULL))) {
05210                   what_is_s = "~~s~~";
05211                }
05212                if (ast_asprintf(&gosub_args, "%s,%s,1(%s)", gosubexec, what_is_s, gosub_argstart + 1) < 0) {
05213                   gosub_args = NULL;
05214                }
05215                *gosub_argstart = ',';
05216             } else {
05217                const char *what_is_s = "s";
05218                if (!ast_exists_extension(peer, gosubexec, "s", 1, S_COR(peer->caller.id.number.valid, peer->caller.id.number.str, NULL)) &&
05219                    ast_exists_extension(peer, gosubexec, "~~s~~", 1, S_COR(peer->caller.id.number.valid, peer->caller.id.number.str, NULL))) {
05220                   what_is_s = "~~s~~";
05221                }
05222                if (ast_asprintf(&gosub_args, "%s,%s,1", gosubexec, what_is_s) < 0) {
05223                   gosub_args = NULL;
05224                }
05225             }
05226             if (gosub_args) {
05227                res = pbx_exec(peer, application, gosub_args);
05228                if (!res) {
05229                   struct ast_pbx_args args;
05230                   memset(&args, 0, sizeof(args));
05231                   args.no_hangup_chan = 1;
05232                   ast_pbx_run_args(peer, &args);
05233                }
05234                ast_free(gosub_args);
05235                ast_debug(1, "Gosub exited with status %d\n", res);
05236             } else {
05237                ast_log(LOG_ERROR, "Could not Allocate string for Gosub arguments -- Gosub Call Aborted!\n");
05238             }
05239          } else {
05240             ast_log(LOG_ERROR, "Could not find application Gosub\n");
05241             res = -1;
05242          }
05243       
05244          if (ast_autoservice_stop(qe->chan) < 0) {
05245             ast_log(LOG_ERROR, "Could not stop autoservice on calling channel\n");
05246             res = -1;
05247          }
05248       }
05249 
05250       if (!ast_strlen_zero(agi)) {
05251          ast_debug(1, "app_queue: agi=%s.\n", agi);
05252          application = pbx_findapp("agi");
05253          if (application) {
05254             agiexec = ast_strdupa(agi);
05255             pbx_exec(qe->chan, application, agiexec);
05256          } else
05257             ast_log(LOG_WARNING, "Asked to execute an AGI on this channel, but could not find application (agi)!\n");
05258       }
05259       qe->handled++;
05260       ast_queue_log(queuename, qe->chan->uniqueid, member->membername, "CONNECT", "%ld|%s|%ld", (long) time(NULL) - qe->start, peer->uniqueid,
05261                                        (long)(orig - to > 0 ? (orig - to) / 1000 : 0));
05262 
05263       if (qe->chan->cdr) {
05264          struct ast_cdr *cdr;
05265          struct ast_cdr *newcdr;
05266 
05267          /* Only work with the last CDR in the stack*/
05268          cdr = qe->chan->cdr;
05269          while (cdr->next) {
05270             cdr = cdr->next;
05271          }
05272 
05273          /* If this CDR is not related to us add new one*/
05274          if ((strcasecmp(cdr->uniqueid, qe->chan->uniqueid)) &&
05275              (strcasecmp(cdr->linkedid, qe->chan->uniqueid)) &&
05276              (newcdr = ast_cdr_dup(cdr))) {
05277             ast_channel_lock(qe->chan);
05278             ast_cdr_init(newcdr, qe->chan);
05279             ast_cdr_reset(newcdr, 0);
05280             cdr = ast_cdr_append(cdr, newcdr);
05281             cdr = cdr->next;
05282             ast_channel_unlock(qe->chan);
05283          }
05284 
05285          if (update_cdr) {
05286             ast_copy_string(cdr->dstchannel, member->membername, sizeof(cdr->dstchannel));
05287          }
05288       }
05289 
05290       if (qe->parent->eventwhencalled)
05291          manager_event(EVENT_FLAG_AGENT, "AgentConnect",
05292                "Queue: %s\r\n"
05293                "Uniqueid: %s\r\n"
05294                "Channel: %s\r\n"
05295                "Member: %s\r\n"
05296                "MemberName: %s\r\n"
05297                "Holdtime: %ld\r\n"
05298                "BridgedChannel: %s\r\n"
05299                "Ringtime: %ld\r\n"
05300                "%s",
05301                queuename, qe->chan->uniqueid, peer->name, member->interface, member->membername,
05302                (long) time(NULL) - qe->start, peer->uniqueid, (long)(orig - to > 0 ? (orig - to) / 1000 : 0),
05303                qe->parent->eventwhencalled == QUEUE_EVENT_VARIABLES ? vars2manager(qe->chan, vars, sizeof(vars)) : "");
05304       ast_copy_string(oldcontext, qe->chan->context, sizeof(oldcontext));
05305       ast_copy_string(oldexten, qe->chan->exten, sizeof(oldexten));
05306    
05307       if ((queue_end_bridge = ao2_alloc(sizeof(*queue_end_bridge), NULL))) {
05308          queue_end_bridge->q = qe->parent;
05309          queue_end_bridge->chan = qe->chan;
05310          bridge_config.end_bridge_callback = end_bridge_callback;
05311          bridge_config.end_bridge_callback_data = queue_end_bridge;
05312          bridge_config.end_bridge_callback_data_fixup = end_bridge_callback_data_fixup;
05313          /* Since queue_end_bridge can survive beyond the life of this call to Queue, we need
05314           * to make sure to increase the refcount of this queue so it cannot be freed until we
05315           * are done with it. We remove this reference in end_bridge_callback.
05316           */
05317          queue_t_ref(qe->parent, "For bridge_config reference");
05318       }
05319 
05320       time(&callstart);
05321       transfer_ds = setup_transfer_datastore(qe, member, callstart, callcompletedinsl);
05322       bridge = ast_bridge_call(qe->chan,peer, &bridge_config);
05323 
05324       /* If the queue member did an attended transfer, then the TRANSFER already was logged in the queue_log
05325        * when the masquerade occurred. These other "ending" queue_log messages are unnecessary, except for
05326        * the AgentComplete manager event
05327        */
05328       ast_channel_lock(qe->chan);
05329       if (!attended_transfer_occurred(qe->chan)) {
05330          struct ast_datastore *tds;
05331 
05332          /* detect a blind transfer */
05333          if (!(qe->chan->_softhangup | peer->_softhangup) && (strcasecmp(oldcontext, qe->chan->context) || strcasecmp(oldexten, qe->chan->exten))) {
05334             ast_queue_log(queuename, qe->chan->uniqueid, member->membername, "TRANSFER", "%s|%s|%ld|%ld|%d",
05335                qe->chan->exten, qe->chan->context, (long) (callstart - qe->start),
05336                (long) (time(NULL) - callstart), qe->opos);
05337             send_agent_complete(qe, queuename, peer, member, callstart, vars, sizeof(vars), TRANSFER);
05338          } else if (ast_check_hangup(qe->chan)) {
05339             ast_queue_log(queuename, qe->chan->uniqueid, member->membername, "COMPLETECALLER", "%ld|%ld|%d",
05340                (long) (callstart - qe->start), (long) (time(NULL) - callstart), qe->opos);
05341             send_agent_complete(qe, queuename, peer, member, callstart, vars, sizeof(vars), CALLER);
05342          } else {
05343             ast_queue_log(queuename, qe->chan->uniqueid, member->membername, "COMPLETEAGENT", "%ld|%ld|%d",
05344                (long) (callstart - qe->start), (long) (time(NULL) - callstart), qe->opos);
05345             send_agent_complete(qe, queuename, peer, member, callstart, vars, sizeof(vars), AGENT);
05346          }
05347          if ((tds = ast_channel_datastore_find(qe->chan, &queue_transfer_info, NULL))) {  
05348             ast_channel_datastore_remove(qe->chan, tds);
05349          }
05350          ast_channel_unlock(qe->chan);
05351          update_queue(qe->parent, member, callcompletedinsl, (time(NULL) - callstart));
05352       } else {
05353          ast_channel_unlock(qe->chan);
05354 
05355          /* We already logged the TRANSFER on the queue_log, but we still need to send the AgentComplete event */
05356          send_agent_complete(qe, queuename, peer, member, callstart, vars, sizeof(vars), TRANSFER);
05357       }
05358 
05359       if (transfer_ds) {
05360          ast_datastore_free(transfer_ds);
05361       }
05362       ast_hangup(peer);
05363       res = bridge ? bridge : 1;
05364       ao2_ref(member, -1);
05365    }
05366 out:
05367    hangupcalls(outgoing, NULL, qe->cancel_answered_elsewhere);
05368 
05369    return res;
05370 }
05371 
05372 static int wait_a_bit(struct queue_ent *qe)
05373 {
05374    /* Don't need to hold the lock while we setup the outgoing calls */
05375    int retrywait = qe->parent->retry * 1000;
05376 
05377    int res = ast_waitfordigit(qe->chan, retrywait);
05378    if (res > 0 && !valid_exit(qe, res))
05379       res = 0;
05380 
05381    return res;
05382 }
05383 
05384 static struct member *interface_exists(struct call_queue *q, const char *interface)
05385 {
05386    struct member *mem;
05387    struct ao2_iterator mem_iter;
05388 
05389    if (!q)
05390       return NULL;
05391 
05392    mem_iter = ao2_iterator_init(q->members, 0);
05393    while ((mem = ao2_iterator_next(&mem_iter))) {
05394       if (!strcasecmp(interface, mem->interface)) {
05395          ao2_iterator_destroy(&mem_iter);
05396          return mem;
05397       }
05398       ao2_ref(mem, -1);
05399    }
05400    ao2_iterator_destroy(&mem_iter);
05401 
05402    return NULL;
05403 }
05404 
05405 
05406 /*! \brief Dump all members in a specific queue to the database
05407  *
05408  * <pm_family>/<queuename> = <interface>;<penalty>;<paused>;<state_interface>[|...]
05409  */
05410 static void dump_queue_members(struct call_queue *pm_queue)
05411 {
05412    struct member *cur_member;
05413    struct ast_str *value;
05414    struct ao2_iterator mem_iter;
05415 
05416    if (!pm_queue) {
05417       return;
05418    }
05419 
05420    /* 4K is a reasonable default for most applications, but we grow to
05421     * accommodate more if necessary. */
05422    if (!(value = ast_str_create(4096))) {
05423       return;
05424    }
05425 
05426    mem_iter = ao2_iterator_init(pm_queue->members, 0);
05427    while ((cur_member = ao2_iterator_next(&mem_iter))) {
05428       if (!cur_member->dynamic) {
05429          ao2_ref(cur_member, -1);
05430          continue;
05431       }
05432 
05433       ast_str_append(&value, 0, "%s%s;%d;%d;%s;%s",
05434          ast_str_strlen(value) ? "|" : "",
05435          cur_member->interface,
05436          cur_member->penalty,
05437          cur_member->paused,
05438          cur_member->membername,
05439          cur_member->state_interface);
05440 
05441       ao2_ref(cur_member, -1);
05442    }
05443    ao2_iterator_destroy(&mem_iter);
05444 
05445    if (ast_str_strlen(value) && !cur_member) {
05446       if (ast_db_put(pm_family, pm_queue->name, ast_str_buffer(value)))
05447          ast_log(LOG_WARNING, "failed to create persistent dynamic entry!\n");
05448    } else {
05449       /* Delete the entry if the queue is empty or there is an error */
05450       ast_db_del(pm_family, pm_queue->name);
05451    }
05452 
05453    ast_free(value);
05454 }
05455 
05456 /*! \brief Remove member from queue 
05457  * \retval RES_NOT_DYNAMIC when they aren't a RT member
05458  * \retval RES_NOSUCHQUEUE queue does not exist
05459  * \retval RES_OKAY removed member from queue
05460  * \retval RES_EXISTS queue exists but no members
05461 */
05462 static int remove_from_queue(const char *queuename, const char *interface)
05463 {
05464    struct call_queue *q, tmpq = {
05465       .name = queuename,   
05466    };
05467    struct member *mem, tmpmem;
05468    int res = RES_NOSUCHQUEUE;
05469 
05470    ast_copy_string(tmpmem.interface, interface, sizeof(tmpmem.interface));
05471    if ((q = ao2_t_find(queues, &tmpq, OBJ_POINTER, "Temporary reference for interface removal"))) {
05472       ao2_lock(q);
05473       if ((mem = ao2_find(q->members, &tmpmem, OBJ_POINTER))) {
05474          /* XXX future changes should beware of this assumption!! */
05475          if (!mem->dynamic) {
05476             ao2_ref(mem, -1);
05477             ao2_unlock(q);
05478             queue_t_unref(q, "Interface wasn't dynamic, expiring temporary reference");
05479             return RES_NOT_DYNAMIC;
05480          }
05481          manager_event(EVENT_FLAG_AGENT, "QueueMemberRemoved",
05482             "Queue: %s\r\n"
05483             "Location: %s\r\n"
05484             "MemberName: %s\r\n",
05485             q->name, mem->interface, mem->membername);
05486          member_remove_from_queue(q, mem);
05487          ao2_ref(mem, -1);
05488 
05489          if (queue_persistent_members)
05490             dump_queue_members(q);
05491          
05492          res = RES_OKAY;
05493       } else {
05494          res = RES_EXISTS;
05495       }
05496       ao2_unlock(q);
05497       queue_t_unref(q, "Expiring temporary reference");
05498    }
05499 
05500    return res;
05501 }
05502 
05503 /*! \brief Add member to queue 
05504  * \retval RES_NOT_DYNAMIC when they aren't a RT member
05505  * \retval RES_NOSUCHQUEUE queue does not exist
05506  * \retval RES_OKAY added member from queue
05507  * \retval RES_EXISTS queue exists but no members
05508  * \retval RES_OUT_OF_MEMORY queue exists but not enough memory to create member
05509 */
05510 static int add_to_queue(const char *queuename, const char *interface, const char *membername, int penalty, int paused, int dump, const char *state_interface)
05511 {
05512    struct call_queue *q;
05513    struct member *new_member, *old_member;
05514    int res = RES_NOSUCHQUEUE;
05515 
05516    /*! \note Ensure the appropriate realtime queue is loaded.  Note that this
05517     * short-circuits if the queue is already in memory. */
05518    if (!(q = load_realtime_queue(queuename)))
05519       return res;
05520 
05521    ao2_lock(q);
05522    if ((old_member = interface_exists(q, interface)) == NULL) {
05523       if ((new_member = create_queue_member(interface, membername, penalty, paused, state_interface))) {
05524          new_member->dynamic = 1;
05525          member_add_to_queue(q, new_member);
05526          manager_event(EVENT_FLAG_AGENT, "QueueMemberAdded",
05527             "Queue: %s\r\n"
05528             "Location: %s\r\n"
05529             "MemberName: %s\r\n"
05530             "Membership: %s\r\n"
05531             "Penalty: %d\r\n"
05532             "CallsTaken: %d\r\n"
05533             "LastCall: %d\r\n"
05534             "Status: %d\r\n"
05535             "Paused: %d\r\n",
05536             q->name, new_member->interface, new_member->membername,
05537             "dynamic",
05538             new_member->penalty, new_member->calls, (int) new_member->lastcall,
05539             new_member->status, new_member->paused);
05540          
05541          ao2_ref(new_member, -1);
05542          new_member = NULL;
05543 
05544          if (dump)
05545             dump_queue_members(q);
05546          
05547          res = RES_OKAY;
05548       } else {
05549          res = RES_OUTOFMEMORY;
05550       }
05551    } else {
05552       ao2_ref(old_member, -1);
05553       res = RES_EXISTS;
05554    }
05555    ao2_unlock(q);
05556    queue_t_unref(q, "Expiring temporary reference");
05557 
05558    return res;
05559 }
05560 
05561 static int set_member_paused(const char *queuename, const char *interface, const char *reason, int paused)
05562 {
05563    int found = 0;
05564    struct call_queue *q;
05565    struct member *mem;
05566    struct ao2_iterator queue_iter;
05567    int failed;
05568 
05569    /* Special event for when all queues are paused - individual events still generated */
05570    /* XXX In all other cases, we use the membername, but since this affects all queues, we cannot */
05571    if (ast_strlen_zero(queuename))
05572       ast_queue_log("NONE", "NONE", interface, (paused ? "PAUSEALL" : "UNPAUSEALL"), "%s", "");
05573 
05574    queue_iter = ao2_iterator_init(queues, 0);
05575    while ((q = ao2_t_iterator_next(&queue_iter, "Iterate over queues"))) {
05576       ao2_lock(q);
05577       if (ast_strlen_zero(queuename) || !strcasecmp(q->name, queuename)) {
05578          if ((mem = interface_exists(q, interface))) {
05579             if (mem->paused == paused) {
05580                ast_debug(1, "%spausing already-%spaused queue member %s:%s\n", (paused ? "" : "un"), (paused ? "" : "un"), q->name, interface);
05581             }
05582 
05583             failed = 0;
05584             if (mem->realtime) {
05585                failed = update_realtime_member_field(mem, q->name, "paused", paused ? "1" : "0");
05586             }
05587          
05588             if (failed) {
05589                ast_log(LOG_WARNING, "Failed %spausing realtime queue member %s:%s\n", (paused ? "" : "un"), q->name, interface);
05590                ao2_ref(mem, -1);
05591                ao2_unlock(q);
05592                queue_t_unref(q, "Done with iterator");
05593                continue;
05594             }  
05595             found++;
05596             mem->paused = paused;
05597 
05598             if (queue_persistent_members)
05599                dump_queue_members(q);
05600 
05601             ast_queue_log(q->name, "NONE", mem->membername, (paused ? "PAUSE" : "UNPAUSE"), "%s", S_OR(reason, ""));
05602             
05603             if (!ast_strlen_zero(reason)) {
05604                manager_event(EVENT_FLAG_AGENT, "QueueMemberPaused",
05605                   "Queue: %s\r\n"
05606                   "Location: %s\r\n"
05607                   "MemberName: %s\r\n"
05608                   "Paused: %d\r\n"
05609                   "Reason: %s\r\n",
05610                      q->name, mem->interface, mem->membername, paused, reason);
05611             } else {
05612                manager_event(EVENT_FLAG_AGENT, "QueueMemberPaused",
05613                   "Queue: %s\r\n"
05614                   "Location: %s\r\n"
05615                   "MemberName: %s\r\n"
05616                   "Paused: %d\r\n",
05617                      q->name, mem->interface, mem->membername, paused);
05618             }
05619             ao2_ref(mem, -1);
05620          }
05621       }
05622       
05623       if (!ast_strlen_zero(queuename) && !strcasecmp(queuename, q->name)) {
05624          ao2_unlock(q);
05625          queue_t_unref(q, "Done with iterator");
05626          break;
05627       }
05628       
05629       ao2_unlock(q);
05630       queue_t_unref(q, "Done with iterator");
05631    }
05632    ao2_iterator_destroy(&queue_iter);
05633 
05634    return found ? RESULT_SUCCESS : RESULT_FAILURE;
05635 }
05636 
05637 /* \brief Sets members penalty, if queuename=NULL we set member penalty in all the queues. */
05638 static int set_member_penalty(const char *queuename, const char *interface, int penalty)
05639 {
05640    int foundinterface = 0, foundqueue = 0;
05641    struct call_queue *q;
05642    struct member *mem;
05643    struct ao2_iterator queue_iter;
05644 
05645    if (penalty < 0) {
05646       ast_log(LOG_ERROR, "Invalid penalty (%d)\n", penalty);
05647       return RESULT_FAILURE;
05648    }
05649 
05650    queue_iter = ao2_iterator_init(queues, 0);
05651    while ((q = ao2_t_iterator_next(&queue_iter, "Iterate through queues"))) {
05652       ao2_lock(q);
05653       if (ast_strlen_zero(queuename) || !strcasecmp(q->name, queuename)) {
05654          foundqueue++;
05655          if ((mem = interface_exists(q, interface))) {
05656             foundinterface++;
05657             mem->penalty = penalty;
05658             
05659             ast_queue_log(q->name, "NONE", interface, "PENALTY", "%d", penalty);
05660             manager_event(EVENT_FLAG_AGENT, "QueueMemberPenalty",
05661                "Queue: %s\r\n"
05662                "Location: %s\r\n"
05663                "Penalty: %d\r\n",
05664                q->name, mem->interface, penalty);
05665             ao2_ref(mem, -1);
05666          }
05667       }
05668       ao2_unlock(q);
05669       queue_t_unref(q, "Done with iterator");
05670    }
05671    ao2_iterator_destroy(&queue_iter);
05672 
05673    if (foundinterface) {
05674       return RESULT_SUCCESS;
05675    } else if (!foundqueue) {
05676       ast_log (LOG_ERROR, "Invalid queuename\n"); 
05677    } else {
05678       ast_log (LOG_ERROR, "Invalid interface\n");
05679    }  
05680 
05681    return RESULT_FAILURE;
05682 }
05683 
05684 /* \brief Gets members penalty. 
05685  * \return Return the members penalty or RESULT_FAILURE on error. 
05686 */
05687 static int get_member_penalty(char *queuename, char *interface)
05688 {
05689    int foundqueue = 0, penalty;
05690    struct call_queue *q, tmpq = {
05691       .name = queuename,   
05692    };
05693    struct member *mem;
05694    
05695    if ((q = ao2_t_find(queues, &tmpq, OBJ_POINTER, "Search for queue"))) {
05696       foundqueue = 1;
05697       ao2_lock(q);
05698       if ((mem = interface_exists(q, interface))) {
05699          penalty = mem->penalty;
05700          ao2_ref(mem, -1);
05701          ao2_unlock(q);
05702          queue_t_unref(q, "Search complete");
05703          return penalty;
05704       }
05705       ao2_unlock(q);
05706       queue_t_unref(q, "Search complete");
05707    }
05708 
05709    /* some useful debuging */
05710    if (foundqueue) 
05711       ast_log (LOG_ERROR, "Invalid queuename\n");
05712    else 
05713       ast_log (LOG_ERROR, "Invalid interface\n");
05714 
05715    return RESULT_FAILURE;
05716 }
05717 
05718 /*! \brief Reload dynamic queue members persisted into the astdb */
05719 static void reload_queue_members(void)
05720 {
05721    char *cur_ptr;
05722    const char *queue_name;
05723    char *member;
05724    char *interface;
05725    char *membername = NULL;
05726    char *state_interface;
05727    char *penalty_tok;
05728    int penalty = 0;
05729    char *paused_tok;
05730    int paused = 0;
05731    struct ast_db_entry *db_tree;
05732    struct ast_db_entry *entry;
05733    struct call_queue *cur_queue;
05734    char *queue_data;
05735 
05736    /* Each key in 'pm_family' is the name of a queue */
05737    db_tree = ast_db_gettree(pm_family, NULL);
05738    for (entry = db_tree; entry; entry = entry->next) {
05739 
05740       queue_name = entry->key + strlen(pm_family) + 2;
05741 
05742       {
05743          struct call_queue tmpq = {
05744             .name = queue_name,
05745          };
05746          cur_queue = ao2_t_find(queues, &tmpq, OBJ_POINTER, "Reload queue members");
05747       }  
05748 
05749       if (!cur_queue)
05750          cur_queue = load_realtime_queue(queue_name);
05751 
05752       if (!cur_queue) {
05753          /* If the queue no longer exists, remove it from the
05754           * database */
05755          ast_log(LOG_WARNING, "Error loading persistent queue: '%s': it does not exist\n", queue_name);
05756          ast_db_del(pm_family, queue_name);
05757          continue;
05758       } 
05759 
05760       if (ast_db_get_allocated(pm_family, queue_name, &queue_data)) {
05761          queue_t_unref(cur_queue, "Expire reload reference");
05762          continue;
05763       }
05764 
05765       cur_ptr = queue_data;
05766       while ((member = strsep(&cur_ptr, ",|"))) {
05767          if (ast_strlen_zero(member))
05768             continue;
05769 
05770          interface = strsep(&member, ";");
05771          penalty_tok = strsep(&member, ";");
05772          paused_tok = strsep(&member, ";");
05773          membername = strsep(&member, ";");
05774          state_interface = strsep(&member, ";");
05775 
05776          if (!penalty_tok) {
05777             ast_log(LOG_WARNING, "Error parsing persistent member string for '%s' (penalty)\n", queue_name);
05778             break;
05779          }
05780          penalty = strtol(penalty_tok, NULL, 10);
05781          if (errno == ERANGE) {
05782             ast_log(LOG_WARNING, "Error converting penalty: %s: Out of range.\n", penalty_tok);
05783             break;
05784          }
05785          
05786          if (!paused_tok) {
05787             ast_log(LOG_WARNING, "Error parsing persistent member string for '%s' (paused)\n", queue_name);
05788             break;
05789          }
05790          paused = strtol(paused_tok, NULL, 10);
05791          if ((errno == ERANGE) || paused < 0 || paused > 1) {
05792             ast_log(LOG_WARNING, "Error converting paused: %s: Expected 0 or 1.\n", paused_tok);
05793             break;
05794          }
05795 
05796          ast_debug(1, "Reload Members: Queue: %s  Member: %s  Name: %s  Penalty: %d  Paused: %d\n", queue_name, interface, membername, penalty, paused);
05797          
05798          if (add_to_queue(queue_name, interface, membername, penalty, paused, 0, state_interface) == RES_OUTOFMEMORY) {
05799             ast_log(LOG_ERROR, "Out of Memory when reloading persistent queue member\n");
05800             break;
05801          }
05802       }
05803       queue_t_unref(cur_queue, "Expire reload reference");
05804       ast_free(queue_data);
05805    }
05806 
05807    if (db_tree) {
05808       ast_log(LOG_NOTICE, "Queue members successfully reloaded from database.\n");
05809       ast_db_freetree(db_tree);
05810    }
05811 }
05812 
05813 /*! \brief PauseQueueMember application */
05814 static int pqm_exec(struct ast_channel *chan, const char *data)
05815 {
05816    char *parse;
05817    AST_DECLARE_APP_ARGS(args,
05818       AST_APP_ARG(queuename);
05819       AST_APP_ARG(interface);
05820       AST_APP_ARG(options);
05821       AST_APP_ARG(reason);
05822    );
05823 
05824    if (ast_strlen_zero(data)) {
05825       ast_log(LOG_WARNING, "PauseQueueMember requires an argument ([queuename],interface[,options][,reason])\n");
05826       return -1;
05827    }
05828 
05829    parse = ast_strdupa(data);
05830 
05831    AST_STANDARD_APP_ARGS(args, parse);
05832 
05833    if (ast_strlen_zero(args.interface)) {
05834       ast_log(LOG_WARNING, "Missing interface argument to PauseQueueMember ([queuename],interface[,options[,reason]])\n");
05835       return -1;
05836    }
05837 
05838    if (set_member_paused(args.queuename, args.interface, args.reason, 1)) {
05839       ast_log(LOG_WARNING, "Attempt to pause interface %s, not found\n", args.interface);
05840       pbx_builtin_setvar_helper(chan, "PQMSTATUS", "NOTFOUND");
05841       return 0;
05842    }
05843 
05844    pbx_builtin_setvar_helper(chan, "PQMSTATUS", "PAUSED");
05845 
05846    return 0;
05847 }
05848 
05849 /*! \brief UnPauseQueueMember application */
05850 static int upqm_exec(struct ast_channel *chan, const char *data)
05851 {
05852    char *parse;
05853    AST_DECLARE_APP_ARGS(args,
05854       AST_APP_ARG(queuename);
05855       AST_APP_ARG(interface);
05856       AST_APP_ARG(options);
05857       AST_APP_ARG(reason);
05858    );
05859 
05860    if (ast_strlen_zero(data)) {
05861       ast_log(LOG_WARNING, "UnpauseQueueMember requires an argument ([queuename],interface[,options[,reason]])\n");
05862       return -1;
05863    }
05864 
05865    parse = ast_strdupa(data);
05866 
05867    AST_STANDARD_APP_ARGS(args, parse);
05868 
05869    if (ast_strlen_zero(args.interface)) {
05870       ast_log(LOG_WARNING, "Missing interface argument to PauseQueueMember ([queuename],interface[,options[,reason]])\n");
05871       return -1;
05872    }
05873 
05874    if (set_member_paused(args.queuename, args.interface, args.reason, 0)) {
05875       ast_log(LOG_WARNING, "Attempt to unpause interface %s, not found\n", args.interface);
05876       pbx_builtin_setvar_helper(chan, "UPQMSTATUS", "NOTFOUND");
05877       return 0;
05878    }
05879 
05880    pbx_builtin_setvar_helper(chan, "UPQMSTATUS", "UNPAUSED");
05881 
05882    return 0;
05883 }
05884 
05885 /*! \brief RemoveQueueMember application */
05886 static int rqm_exec(struct ast_channel *chan, const char *data)
05887 {
05888    int res=-1;
05889    char *parse, *temppos = NULL;
05890    AST_DECLARE_APP_ARGS(args,
05891       AST_APP_ARG(queuename);
05892       AST_APP_ARG(interface);
05893    );
05894 
05895 
05896    if (ast_strlen_zero(data)) {
05897       ast_log(LOG_WARNING, "RemoveQueueMember requires an argument (queuename[,interface])\n");
05898       return -1;
05899    }
05900 
05901    parse = ast_strdupa(data);
05902 
05903    AST_STANDARD_APP_ARGS(args, parse);
05904 
05905    if (ast_strlen_zero(args.interface)) {
05906       args.interface = ast_strdupa(chan->name);
05907       temppos = strrchr(args.interface, '-');
05908       if (temppos)
05909          *temppos = '\0';
05910    }
05911 
05912    ast_debug(1, "queue: %s, member: %s\n", args.queuename, args.interface);
05913 
05914    switch (remove_from_queue(args.queuename, args.interface)) {
05915    case RES_OKAY:
05916       ast_queue_log(args.queuename, chan->uniqueid, args.interface, "REMOVEMEMBER", "%s", "");
05917       ast_log(LOG_NOTICE, "Removed interface '%s' from queue '%s'\n", args.interface, args.queuename);
05918       pbx_builtin_setvar_helper(chan, "RQMSTATUS", "REMOVED");
05919       res = 0;
05920       break;
05921    case RES_EXISTS:
05922       ast_debug(1, "Unable to remove interface '%s' from queue '%s': Not there\n", args.interface, args.queuename);
05923       pbx_builtin_setvar_helper(chan, "RQMSTATUS", "NOTINQUEUE");
05924       res = 0;
05925       break;
05926    case RES_NOSUCHQUEUE:
05927       ast_log(LOG_WARNING, "Unable to remove interface from queue '%s': No such queue\n", args.queuename);
05928       pbx_builtin_setvar_helper(chan, "RQMSTATUS", "NOSUCHQUEUE");
05929       res = 0;
05930       break;
05931    case RES_NOT_DYNAMIC:
05932       ast_log(LOG_WARNING, "Unable to remove interface from queue '%s': '%s' is not a dynamic member\n", args.queuename, args.interface);
05933       pbx_builtin_setvar_helper(chan, "RQMSTATUS", "NOTDYNAMIC");
05934       res = 0;
05935       break;
05936    }
05937 
05938    return res;
05939 }
05940 
05941 /*! \brief AddQueueMember application */
05942 static int aqm_exec(struct ast_channel *chan, const char *data)
05943 {
05944    int res=-1;
05945    char *parse, *temppos = NULL;
05946    AST_DECLARE_APP_ARGS(args,
05947       AST_APP_ARG(queuename);
05948       AST_APP_ARG(interface);
05949       AST_APP_ARG(penalty);
05950       AST_APP_ARG(options);
05951       AST_APP_ARG(membername);
05952       AST_APP_ARG(state_interface);
05953    );
05954    int penalty = 0;
05955 
05956    if (ast_strlen_zero(data)) {
05957       ast_log(LOG_WARNING, "AddQueueMember requires an argument (queuename[,interface[,penalty[,options[,membername[,stateinterface]]]]])\n");
05958       return -1;
05959    }
05960 
05961    parse = ast_strdupa(data);
05962 
05963    AST_STANDARD_APP_ARGS(args, parse);
05964 
05965    if (ast_strlen_zero(args.interface)) {
05966       args.interface = ast_strdupa(chan->name);
05967       temppos = strrchr(args.interface, '-');
05968       if (temppos)
05969          *temppos = '\0';
05970    }
05971 
05972    if (!ast_strlen_zero(args.penalty)) {
05973       if ((sscanf(args.penalty, "%30d", &penalty) != 1) || penalty < 0) {
05974          ast_log(LOG_WARNING, "Penalty '%s' is invalid, must be an integer >= 0\n", args.penalty);
05975          penalty = 0;
05976       }
05977    }
05978 
05979    switch (add_to_queue(args.queuename, args.interface, args.membername, penalty, 0, queue_persistent_members, args.state_interface)) {
05980    case RES_OKAY:
05981       ast_queue_log(args.queuename, chan->uniqueid, args.interface, "ADDMEMBER", "%s", "");
05982       ast_log(LOG_NOTICE, "Added interface '%s' to queue '%s'\n", args.interface, args.queuename);
05983       pbx_builtin_setvar_helper(chan, "AQMSTATUS", "ADDED");
05984       res = 0;
05985       break;
05986    case RES_EXISTS:
05987       ast_log(LOG_WARNING, "Unable to add interface '%s' to queue '%s': Already there\n", args.interface, args.queuename);
05988       pbx_builtin_setvar_helper(chan, "AQMSTATUS", "MEMBERALREADY");
05989       res = 0;
05990       break;
05991    case RES_NOSUCHQUEUE:
05992       ast_log(LOG_WARNING, "Unable to add interface to queue '%s': No such queue\n", args.queuename);
05993       pbx_builtin_setvar_helper(chan, "AQMSTATUS", "NOSUCHQUEUE");
05994       res = 0;
05995       break;
05996    case RES_OUTOFMEMORY:
05997       ast_log(LOG_ERROR, "Out of memory adding member %s to queue %s\n", args.interface, args.queuename);
05998       break;
05999    }
06000 
06001    return res;
06002 }
06003 
06004 /*! \brief QueueLog application */
06005 static int ql_exec(struct ast_channel *chan, const char *data)
06006 {
06007    char *parse;
06008 
06009    AST_DECLARE_APP_ARGS(args,
06010       AST_APP_ARG(queuename);
06011       AST_APP_ARG(uniqueid);
06012       AST_APP_ARG(membername);
06013       AST_APP_ARG(event);
06014       AST_APP_ARG(params);
06015    );
06016 
06017    if (ast_strlen_zero(data)) {
06018       ast_log(LOG_WARNING, "QueueLog requires arguments (queuename,uniqueid,membername,event[,additionalinfo]\n");
06019       return -1;
06020    }
06021 
06022    parse = ast_strdupa(data);
06023 
06024    AST_STANDARD_APP_ARGS(args, parse);
06025 
06026    if (ast_strlen_zero(args.queuename) || ast_strlen_zero(args.uniqueid)
06027        || ast_strlen_zero(args.membername) || ast_strlen_zero(args.event)) {
06028       ast_log(LOG_WARNING, "QueueLog requires arguments (queuename,uniqueid,membername,event[,additionalinfo])\n");
06029       return -1;
06030    }
06031 
06032    ast_queue_log(args.queuename, args.uniqueid, args.membername, args.event, 
06033       "%s", args.params ? args.params : "");
06034 
06035    return 0;
06036 }
06037 
06038 /*! \brief Copy rule from global list into specified queue */
06039 static void copy_rules(struct queue_ent *qe, const char *rulename)
06040 {
06041    struct penalty_rule *pr_iter;
06042    struct rule_list *rl_iter;
06043    const char *tmp = ast_strlen_zero(rulename) ? qe->parent->defaultrule : rulename;
06044    AST_LIST_LOCK(&rule_lists);
06045    AST_LIST_TRAVERSE(&rule_lists, rl_iter, list) {
06046       if (!strcasecmp(rl_iter->name, tmp))
06047          break;
06048    }
06049    if (rl_iter) {
06050       AST_LIST_TRAVERSE(&rl_iter->rules, pr_iter, list) {
06051          struct penalty_rule *new_pr = ast_calloc(1, sizeof(*new_pr));
06052          if (!new_pr) {
06053             ast_log(LOG_ERROR, "Memory allocation error when copying penalty rules! Aborting!\n");
06054             break;
06055          }
06056          new_pr->time = pr_iter->time;
06057          new_pr->max_value = pr_iter->max_value;
06058          new_pr->min_value = pr_iter->min_value;
06059          new_pr->max_relative = pr_iter->max_relative;
06060          new_pr->min_relative = pr_iter->min_relative;
06061          AST_LIST_INSERT_TAIL(&qe->qe_rules, new_pr, list);
06062       }
06063    }
06064    AST_LIST_UNLOCK(&rule_lists);
06065 }
06066 
06067 /*!\brief The starting point for all queue calls
06068  *
06069  * The process involved here is to 
06070  * 1. Parse the options specified in the call to Queue()
06071  * 2. Join the queue
06072  * 3. Wait in a loop until it is our turn to try calling a queue member
06073  * 4. Attempt to call a queue member
06074  * 5. If 4. did not result in a bridged call, then check for between
06075  *    call options such as periodic announcements etc.
06076  * 6. Try 4 again unless some condition (such as an expiration time) causes us to 
06077  *    exit the queue.
06078  */
06079 static int queue_exec(struct ast_channel *chan, const char *data)
06080 {
06081    int res=-1;
06082    int ringing=0;
06083    const char *user_priority;
06084    const char *max_penalty_str;
06085    const char *min_penalty_str;
06086    int prio;
06087    int qcontinue = 0;
06088    int max_penalty, min_penalty;
06089    enum queue_result reason = QUEUE_UNKNOWN;
06090    /* whether to exit Queue application after the timeout hits */
06091    int tries = 0;
06092    int noption = 0;
06093    char *parse;
06094    int makeannouncement = 0;
06095    int position = 0;
06096    AST_DECLARE_APP_ARGS(args,
06097       AST_APP_ARG(queuename);
06098       AST_APP_ARG(options);
06099       AST_APP_ARG(url);
06100       AST_APP_ARG(announceoverride);
06101       AST_APP_ARG(queuetimeoutstr);
06102       AST_APP_ARG(agi);
06103       AST_APP_ARG(macro);
06104       AST_APP_ARG(gosub);
06105       AST_APP_ARG(rule);
06106       AST_APP_ARG(position);
06107    );
06108    /* Our queue entry */
06109    struct queue_ent qe = { 0 };
06110    
06111    if (ast_strlen_zero(data)) {
06112       ast_log(LOG_WARNING, "Queue requires an argument: queuename[,options[,URL[,announceoverride[,timeout[,agi[,macro[,gosub[,rule[,position]]]]]]]]]\n");
06113       return -1;
06114    }
06115    
06116    parse = ast_strdupa(data);
06117    AST_STANDARD_APP_ARGS(args, parse);
06118 
06119    /* Setup our queue entry */
06120    qe.start = time(NULL);
06121 
06122    /* set the expire time based on the supplied timeout; */
06123    if (!ast_strlen_zero(args.queuetimeoutstr))
06124       qe.expire = qe.start + atoi(args.queuetimeoutstr);
06125    else
06126       qe.expire = 0;
06127 
06128    /* Get the priority from the variable ${QUEUE_PRIO} */
06129    ast_channel_lock(chan);
06130    user_priority = pbx_builtin_getvar_helper(chan, "QUEUE_PRIO");
06131    if (user_priority) {
06132       if (sscanf(user_priority, "%30d", &prio) == 1) {
06133          ast_debug(1, "%s: Got priority %d from ${QUEUE_PRIO}.\n", chan->name, prio);
06134       } else {
06135          ast_log(LOG_WARNING, "${QUEUE_PRIO}: Invalid value (%s), channel %s.\n",
06136             user_priority, chan->name);
06137          prio = 0;
06138       }
06139    } else {
06140       ast_debug(3, "NO QUEUE_PRIO variable found. Using default.\n");
06141       prio = 0;
06142    }
06143 
06144    /* Get the maximum penalty from the variable ${QUEUE_MAX_PENALTY} */
06145 
06146    if ((max_penalty_str = pbx_builtin_getvar_helper(chan, "QUEUE_MAX_PENALTY"))) {
06147       if (sscanf(max_penalty_str, "%30d", &max_penalty) == 1) {
06148          ast_debug(1, "%s: Got max penalty %d from ${QUEUE_MAX_PENALTY}.\n", chan->name, max_penalty);
06149       } else {
06150          ast_log(LOG_WARNING, "${QUEUE_MAX_PENALTY}: Invalid value (%s), channel %s.\n",
06151             max_penalty_str, chan->name);
06152          max_penalty = 0;
06153       }
06154    } else {
06155       max_penalty = 0;
06156    }
06157 
06158    if ((min_penalty_str = pbx_builtin_getvar_helper(chan, "QUEUE_MIN_PENALTY"))) {
06159       if (sscanf(min_penalty_str, "%30d", &min_penalty) == 1) {
06160          ast_debug(1, "%s: Got min penalty %d from ${QUEUE_MIN_PENALTY}.\n", chan->name, min_penalty);
06161       } else {
06162          ast_log(LOG_WARNING, "${QUEUE_MIN_PENALTY}: Invalid value (%s), channel %s.\n",
06163             min_penalty_str, chan->name);
06164          min_penalty = 0;
06165       }
06166    } else {
06167       min_penalty = 0;
06168    }
06169    ast_channel_unlock(chan);
06170 
06171    if (args.options && (strchr(args.options, 'r')))
06172       ringing = 1;
06173 
06174    if (ringing != 1 && args.options && (strchr(args.options, 'R'))) {
06175       qe.ring_when_ringing = 1;
06176    }
06177 
06178    if (args.options && (strchr(args.options, 'c')))
06179       qcontinue = 1;
06180 
06181    if (args.position) {
06182       position = atoi(args.position);
06183       if (position < 0) {
06184          ast_log(LOG_WARNING, "Invalid position '%s' given for call to queue '%s'. Assuming no preference for position\n", args.position, args.queuename);
06185          position = 0;
06186       }
06187    }
06188 
06189    ast_debug(1, "queue: %s, options: %s, url: %s, announce: %s, expires: %ld, priority: %d\n",
06190       args.queuename, args.options, args.url, args.announceoverride, (long)qe.expire, prio);
06191 
06192    qe.chan = chan;
06193    qe.prio = prio;
06194    qe.max_penalty = max_penalty;
06195    qe.min_penalty = min_penalty;
06196    qe.last_pos_said = 0;
06197    qe.last_pos = 0;
06198    qe.last_periodic_announce_time = time(NULL);
06199    qe.last_periodic_announce_sound = 0;
06200    qe.valid_digits = 0;
06201    if (join_queue(args.queuename, &qe, &reason, position)) {
06202       ast_log(LOG_WARNING, "Unable to join queue '%s'\n", args.queuename);
06203       set_queue_result(chan, reason);
06204       return 0;
06205    }
06206    ast_assert(qe.parent != NULL);
06207 
06208    ast_queue_log(args.queuename, chan->uniqueid, "NONE", "ENTERQUEUE", "%s|%s|%d",
06209       S_OR(args.url, ""),
06210       S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, ""),
06211       qe.opos);
06212    copy_rules(&qe, args.rule);
06213    qe.pr = AST_LIST_FIRST(&qe.qe_rules);
06214 check_turns:
06215    if (ringing) {
06216       ast_indicate(chan, AST_CONTROL_RINGING);
06217    } else {
06218       ast_moh_start(chan, qe.moh, NULL);
06219    }
06220 
06221    /* This is the wait loop for callers 2 through maxlen */
06222    res = wait_our_turn(&qe, ringing, &reason);
06223    if (res) {
06224       goto stop;
06225    }
06226 
06227    makeannouncement = 0;
06228 
06229    for (;;) {
06230       /* This is the wait loop for the head caller*/
06231       /* To exit, they may get their call answered; */
06232       /* they may dial a digit from the queue context; */
06233       /* or, they may timeout. */
06234 
06235       /* Leave if we have exceeded our queuetimeout */
06236       if (qe.expire && (time(NULL) >= qe.expire)) {
06237          record_abandoned(&qe);
06238          reason = QUEUE_TIMEOUT;
06239          res = 0;
06240          ast_queue_log(args.queuename, chan->uniqueid,"NONE", "EXITWITHTIMEOUT", "%d|%d|%ld", 
06241             qe.pos, qe.opos, (long) time(NULL) - qe.start);
06242          break;
06243       }
06244 
06245       if (makeannouncement) {
06246          /* Make a position announcement, if enabled */
06247          if (qe.parent->announcefrequency)
06248             if ((res = say_position(&qe,ringing)))
06249                goto stop;
06250       }
06251       makeannouncement = 1;
06252 
06253       /* Make a periodic announcement, if enabled */
06254       if (qe.parent->periodicannouncefrequency)
06255          if ((res = say_periodic_announcement(&qe,ringing)))
06256             goto stop;
06257    
06258       /* Leave if we have exceeded our queuetimeout */
06259       if (qe.expire && (time(NULL) >= qe.expire)) {
06260          record_abandoned(&qe);
06261          reason = QUEUE_TIMEOUT;
06262          res = 0;
06263          ast_queue_log(args.queuename, chan->uniqueid, "NONE", "EXITWITHTIMEOUT", "%d", qe.pos);
06264          break;
06265       }
06266 
06267       /* see if we need to move to the next penalty level for this queue */
06268       while (qe.pr && ((time(NULL) - qe.start) > qe.pr->time)) {
06269          update_qe_rule(&qe);
06270       }
06271 
06272       /* Try calling all queue members for 'timeout' seconds */
06273       res = try_calling(&qe, args.options, args.announceoverride, args.url, &tries, &noption, args.agi, args.macro, args.gosub, ringing);
06274       if (res) {
06275          goto stop;
06276       }
06277 
06278       if (qe.parent->leavewhenempty) {
06279          int status = 0;
06280          if ((status = get_member_status(qe.parent, qe.max_penalty, qe.min_penalty, qe.parent->leavewhenempty))) {
06281             record_abandoned(&qe);
06282             reason = QUEUE_LEAVEEMPTY;
06283             ast_queue_log(args.queuename, chan->uniqueid, "NONE", "EXITEMPTY", "%d|%d|%ld", qe.pos, qe.opos, (long)(time(NULL) - qe.start));
06284             res = 0;
06285             break;
06286          }
06287       }
06288 
06289       /* exit after 'timeout' cycle if 'n' option enabled */
06290       if (noption && tries >= ao2_container_count(qe.parent->members)) {
06291          ast_verb(3, "Exiting on time-out cycle\n");
06292          ast_queue_log(args.queuename, chan->uniqueid, "NONE", "EXITWITHTIMEOUT", "%d", qe.pos);
06293          record_abandoned(&qe);
06294          reason = QUEUE_TIMEOUT;
06295          res = 0;
06296          break;
06297       }
06298 
06299       
06300       /* Leave if we have exceeded our queuetimeout */
06301       if (qe.expire && (time(NULL) >= qe.expire)) {
06302          record_abandoned(&qe);
06303          reason = QUEUE_TIMEOUT;
06304          res = 0;
06305          ast_queue_log(qe.parent->name, qe.chan->uniqueid,"NONE", "EXITWITHTIMEOUT", "%d|%d|%ld", qe.pos, qe.opos, (long) time(NULL) - qe.start);
06306          break;
06307       }
06308 
06309       /* If using dynamic realtime members, we should regenerate the member list for this queue */
06310       update_realtime_members(qe.parent);
06311       /* OK, we didn't get anybody; wait for 'retry' seconds; may get a digit to exit with */
06312       res = wait_a_bit(&qe);
06313       if (res)
06314          goto stop;
06315 
06316       /* Since this is a priority queue and
06317        * it is not sure that we are still at the head
06318        * of the queue, go and check for our turn again.
06319        */
06320       if (!is_our_turn(&qe)) {
06321          ast_debug(1, "Darn priorities, going back in queue (%s)!\n", qe.chan->name);
06322          goto check_turns;
06323       }
06324    }
06325 
06326 stop:
06327    if (res) {
06328       if (res < 0) {
06329          if (!qe.handled) {
06330             record_abandoned(&qe);
06331             ast_queue_log(args.queuename, chan->uniqueid, "NONE", "ABANDON",
06332                "%d|%d|%ld", qe.pos, qe.opos,
06333                (long) time(NULL) - qe.start);
06334             res = -1;
06335          } else if (qcontinue) {
06336             reason = QUEUE_CONTINUE;
06337             res = 0;
06338          }
06339       } else if (qe.valid_digits) {
06340          ast_queue_log(args.queuename, chan->uniqueid, "NONE", "EXITWITHKEY",
06341             "%s|%d", qe.digits, qe.pos);
06342       }
06343    }
06344 
06345    /* Don't allow return code > 0 */
06346    if (res >= 0) {
06347       res = 0; 
06348       if (ringing) {
06349          ast_indicate(chan, -1);
06350       } else {
06351          ast_moh_stop(chan);
06352       }        
06353       ast_stopstream(chan);
06354    }
06355 
06356    set_queue_variables(qe.parent, qe.chan);
06357 
06358    leave_queue(&qe);
06359    if (reason != QUEUE_UNKNOWN)
06360       set_queue_result(chan, reason);
06361 
06362    /*
06363     * every queue_ent is given a reference to it's parent
06364     * call_queue when it joins the queue.  This ref must be taken
06365     * away right before the queue_ent is destroyed.  In this case
06366     * the queue_ent is about to be returned on the stack
06367     */
06368    qe.parent = queue_unref(qe.parent);
06369 
06370    return res;
06371 }
06372 
06373 /*!
06374  * \brief create interface var with all queue details.
06375  * \retval 0 on success
06376  * \retval -1 on error
06377 */
06378 static int queue_function_var(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
06379 {
06380    int res = -1;
06381    struct call_queue *q, tmpq = {
06382       .name = data,  
06383    };
06384 
06385    char interfacevar[256] = "";
06386    float sl = 0;
06387 
06388    if (ast_strlen_zero(data)) {
06389       ast_log(LOG_ERROR, "%s requires an argument: queuename\n", cmd);
06390       return -1;
06391    }
06392 
06393    if ((q = ao2_t_find(queues, &tmpq, OBJ_POINTER, "Find for QUEUE() function"))) {
06394       ao2_lock(q);
06395       if (q->setqueuevar) {
06396          sl = 0;
06397          res = 0;
06398 
06399          if (q->callscompleted > 0) {
06400             sl = 100 * ((float) q->callscompletedinsl / (float) q->callscompleted);
06401          }
06402 
06403          snprintf(interfacevar, sizeof(interfacevar),
06404             "QUEUEMAX=%d,QUEUESTRATEGY=%s,QUEUECALLS=%d,QUEUEHOLDTIME=%d,QUEUETALKTIME=%d,QUEUECOMPLETED=%d,QUEUEABANDONED=%d,QUEUESRVLEVEL=%d,QUEUESRVLEVELPERF=%2.1f",
06405             q->maxlen, int2strat(q->strategy), q->count, q->holdtime, q->talktime, q->callscompleted, q->callsabandoned,  q->servicelevel, sl);
06406 
06407          pbx_builtin_setvar_multiple(chan, interfacevar);
06408       }
06409 
06410       ao2_unlock(q);
06411       queue_t_unref(q, "Done with QUEUE() function");
06412    } else {
06413       ast_log(LOG_WARNING, "queue %s was not found\n", data);
06414    }
06415 
06416    snprintf(buf, len, "%d", res);
06417 
06418    return 0;
06419 }
06420 
06421 /*!
06422  * \brief Check if a given queue exists
06423  *
06424  */
06425 static int queue_function_exists(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
06426 {
06427    struct call_queue *q;
06428 
06429    buf[0] = '\0';
06430 
06431    if (ast_strlen_zero(data)) {
06432       ast_log(LOG_ERROR, "%s requires an argument: queuename\n", cmd);
06433       return -1;
06434    }
06435    q = load_realtime_queue(data);
06436    snprintf(buf, len, "%d", q != NULL? 1 : 0);
06437    if (q) {
06438       queue_t_unref(q, "Done with temporary reference in QUEUE_EXISTS()");
06439    }
06440 
06441    return 0;
06442 }
06443 
06444 /*! 
06445  * \brief Get number either busy / free / ready or total members of a specific queue
06446  * \retval number of members (busy / free / ready / total)
06447  * \retval -1 on error
06448 */
06449 static int queue_function_qac(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
06450 {
06451    int count = 0;
06452    struct member *m;
06453    struct ao2_iterator mem_iter;
06454    struct call_queue *q;
06455    char *option;
06456 
06457    if (ast_strlen_zero(data)) {
06458       ast_log(LOG_ERROR, "%s requires an argument: queuename\n", cmd);
06459       return -1;
06460    }
06461 
06462    if ((option = strchr(data, ',')))
06463       *option++ = '\0';
06464    else
06465       option = "logged";
06466    if ((q = load_realtime_queue(data))) {
06467       ao2_lock(q);
06468       if (!strcasecmp(option, "logged")) {
06469          mem_iter = ao2_iterator_init(q->members, 0);
06470          while ((m = ao2_iterator_next(&mem_iter))) {
06471             /* Count the agents who are logged in and presently answering calls */
06472             if ((m->status != AST_DEVICE_UNAVAILABLE) && (m->status != AST_DEVICE_INVALID)) {
06473                count++;
06474             }
06475             ao2_ref(m, -1);
06476          }
06477          ao2_iterator_destroy(&mem_iter);
06478       } else if (!strcasecmp(option, "free")) {
06479          mem_iter = ao2_iterator_init(q->members, 0);
06480          while ((m = ao2_iterator_next(&mem_iter))) {
06481             /* Count the agents who are logged in and presently answering calls */
06482             if ((m->status == AST_DEVICE_NOT_INUSE) && (!m->paused)) {
06483                count++;
06484             }
06485             ao2_ref(m, -1);
06486          }
06487          ao2_iterator_destroy(&mem_iter);
06488       } else if (!strcasecmp(option, "ready")) {
06489          time_t now;
06490          time(&now);
06491          mem_iter = ao2_iterator_init(q->members, 0);
06492          while ((m = ao2_iterator_next(&mem_iter))) {
06493             /* Count the agents who are logged in, not paused and not wrapping up */
06494             if ((m->status == AST_DEVICE_NOT_INUSE) && (!m->paused) &&
06495                   !(m->lastcall && q->wrapuptime && ((now - q->wrapuptime) < m->lastcall))) {
06496                count++;
06497             }
06498             ao2_ref(m, -1);
06499          }
06500          ao2_iterator_destroy(&mem_iter);
06501       } else /* must be "count" */
06502          count = ao2_container_count(q->members);
06503       ao2_unlock(q);
06504       queue_t_unref(q, "Done with temporary reference in QUEUE_MEMBER()");
06505    } else
06506       ast_log(LOG_WARNING, "queue %s was not found\n", data);
06507 
06508    snprintf(buf, len, "%d", count);
06509 
06510    return 0;
06511 }
06512 
06513 /*! 
06514  * \brief Get the total number of members in a specific queue (Deprecated)
06515  * \retval number of members 
06516  * \retval -1 on error 
06517 */
06518 static int queue_function_qac_dep(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
06519 {
06520    int count = 0;
06521    struct member *m;
06522    struct call_queue *q;
06523    struct ao2_iterator mem_iter;
06524    static int depflag = 1;
06525 
06526    if (depflag) {
06527       depflag = 0;
06528       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");
06529    }
06530 
06531    if (ast_strlen_zero(data)) {
06532       ast_log(LOG_ERROR, "%s requires an argument: queuename\n", cmd);
06533       return -1;
06534    }
06535    
06536    if ((q = load_realtime_queue(data))) {
06537       ao2_lock(q);
06538       mem_iter = ao2_iterator_init(q->members, 0);
06539       while ((m = ao2_iterator_next(&mem_iter))) {
06540          /* Count the agents who are logged in and presently answering calls */
06541          if ((m->status != AST_DEVICE_UNAVAILABLE) && (m->status != AST_DEVICE_INVALID)) {
06542             count++;
06543          }
06544          ao2_ref(m, -1);
06545       }
06546       ao2_iterator_destroy(&mem_iter);
06547       ao2_unlock(q);
06548       queue_t_unref(q, "Done with temporary reference in QUEUE_MEMBER_COUNT");
06549    } else
06550       ast_log(LOG_WARNING, "queue %s was not found\n", data);
06551 
06552    snprintf(buf, len, "%d", count);
06553 
06554    return 0;
06555 }
06556 
06557 /*! \brief Dialplan function QUEUE_WAITING_COUNT() Get number callers waiting in a specific queue */
06558 static int queue_function_queuewaitingcount(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
06559 {
06560    int count = 0;
06561    struct call_queue *q, tmpq = {
06562       .name = data,  
06563    };
06564    struct ast_variable *var = NULL;
06565 
06566    buf[0] = '\0';
06567    
06568    if (ast_strlen_zero(data)) {
06569       ast_log(LOG_ERROR, "QUEUE_WAITING_COUNT requires an argument: queuename\n");
06570       return -1;
06571    }
06572 
06573    if ((q = ao2_t_find(queues, &tmpq, OBJ_POINTER, "Find for QUEUE_WAITING_COUNT()"))) {
06574       ao2_lock(q);
06575       count = q->count;
06576       ao2_unlock(q);
06577       queue_t_unref(q, "Done with reference in QUEUE_WAITING_COUNT()");
06578    } else if ((var = ast_load_realtime("queues", "name", data, SENTINEL))) {
06579       /* if the queue is realtime but was not found in memory, this
06580        * means that the queue had been deleted from memory since it was 
06581        * "dead." This means it has a 0 waiting count
06582        */
06583       count = 0;
06584       ast_variables_destroy(var);
06585    } else
06586       ast_log(LOG_WARNING, "queue %s was not found\n", data);
06587 
06588    snprintf(buf, len, "%d", count);
06589 
06590    return 0;
06591 }
06592 
06593 /*! \brief Dialplan function QUEUE_MEMBER_LIST() Get list of members in a specific queue */
06594 static int queue_function_queuememberlist(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
06595 {
06596    struct call_queue *q, tmpq = {
06597       .name = data,  
06598    };
06599    struct member *m;
06600 
06601    /* Ensure an otherwise empty list doesn't return garbage */
06602    buf[0] = '\0';
06603 
06604    if (ast_strlen_zero(data)) {
06605       ast_log(LOG_ERROR, "QUEUE_MEMBER_LIST requires an argument: queuename\n");
06606       return -1;
06607    }
06608 
06609    if ((q = ao2_t_find(queues, &tmpq, OBJ_POINTER, "Find for QUEUE_MEMBER_LIST()"))) {
06610       int buflen = 0, count = 0;
06611       struct ao2_iterator mem_iter;
06612 
06613       ao2_lock(q);
06614       mem_iter = ao2_iterator_init(q->members, 0);
06615       while ((m = ao2_iterator_next(&mem_iter))) {
06616          /* strcat() is always faster than printf() */
06617          if (count++) {
06618             strncat(buf + buflen, ",", len - buflen - 1);
06619             buflen++;
06620          }
06621          strncat(buf + buflen, m->interface, len - buflen - 1);
06622          buflen += strlen(m->interface);
06623          /* Safeguard against overflow (negative length) */
06624          if (buflen >= len - 2) {
06625             ao2_ref(m, -1);
06626             ast_log(LOG_WARNING, "Truncating list\n");
06627             break;
06628          }
06629          ao2_ref(m, -1);
06630       }
06631       ao2_iterator_destroy(&mem_iter);
06632       ao2_unlock(q);
06633       queue_t_unref(q, "Done with QUEUE_MEMBER_LIST()");
06634    } else
06635       ast_log(LOG_WARNING, "queue %s was not found\n", data);
06636 
06637    /* We should already be terminated, but let's make sure. */
06638    buf[len - 1] = '\0';
06639 
06640    return 0;
06641 }
06642 
06643 /*! \brief Dialplan function QUEUE_MEMBER_PENALTY() Gets the members penalty. */
06644 static int queue_function_memberpenalty_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
06645 {
06646    int penalty;
06647    AST_DECLARE_APP_ARGS(args,
06648       AST_APP_ARG(queuename);
06649       AST_APP_ARG(interface);
06650    );
06651    /* Make sure the returned value on error is NULL. */
06652    buf[0] = '\0';
06653 
06654    if (ast_strlen_zero(data)) {
06655       ast_log(LOG_ERROR, "Missing argument. QUEUE_MEMBER_PENALTY(<queuename>,<interface>)\n");
06656       return -1;
06657    }
06658 
06659    AST_STANDARD_APP_ARGS(args, data);
06660 
06661    if (args.argc < 2) {
06662       ast_log(LOG_ERROR, "Missing argument. QUEUE_MEMBER_PENALTY(<queuename>,<interface>)\n");
06663       return -1;
06664    }
06665 
06666    penalty = get_member_penalty (args.queuename, args.interface);
06667    
06668    if (penalty >= 0) /* remember that buf is already '\0' */
06669       snprintf (buf, len, "%d", penalty);
06670 
06671    return 0;
06672 }
06673 
06674 /*! \brief Dialplan function QUEUE_MEMBER_PENALTY() Sets the members penalty. */
06675 static int queue_function_memberpenalty_write(struct ast_channel *chan, const char *cmd, char *data, const char *value)
06676 {
06677    int penalty;
06678    AST_DECLARE_APP_ARGS(args,
06679       AST_APP_ARG(queuename);
06680       AST_APP_ARG(interface);
06681    );
06682 
06683    if (ast_strlen_zero(data)) {
06684       ast_log(LOG_ERROR, "Missing argument. QUEUE_MEMBER_PENALTY(<queuename>,<interface>)\n");
06685       return -1;
06686    }
06687 
06688    AST_STANDARD_APP_ARGS(args, data);
06689 
06690    if (args.argc < 2) {
06691       ast_log(LOG_ERROR, "Missing argument. QUEUE_MEMBER_PENALTY(<queuename>,<interface>)\n");
06692       return -1;
06693    }
06694 
06695    penalty = atoi(value);
06696 
06697    if (ast_strlen_zero(args.interface)) {
06698       ast_log (LOG_ERROR, "<interface> parameter can't be null\n");
06699       return -1;
06700    }
06701 
06702    /* if queuename = NULL then penalty will be set for interface in all the queues. */
06703    if (set_member_penalty(args.queuename, args.interface, penalty)) {
06704       ast_log(LOG_ERROR, "Invalid interface, queue or penalty\n");
06705       return -1;
06706    }
06707 
06708    return 0;
06709 }
06710 
06711 static struct ast_custom_function queueexists_function = {
06712    .name = "QUEUE_EXISTS",
06713    .read = queue_function_exists,
06714 };
06715 
06716 static struct ast_custom_function queuevar_function = {
06717    .name = "QUEUE_VARIABLES",
06718    .read = queue_function_var,
06719 };
06720 
06721 static struct ast_custom_function queuemembercount_function = {
06722    .name = "QUEUE_MEMBER",
06723    .read = queue_function_qac,
06724 };
06725 
06726 static struct ast_custom_function queuemembercount_dep = {
06727    .name = "QUEUE_MEMBER_COUNT",
06728    .read = queue_function_qac_dep,
06729 };
06730 
06731 static struct ast_custom_function queuewaitingcount_function = {
06732    .name = "QUEUE_WAITING_COUNT",
06733    .read = queue_function_queuewaitingcount,
06734 };
06735 
06736 static struct ast_custom_function queuememberlist_function = {
06737    .name = "QUEUE_MEMBER_LIST",
06738    .read = queue_function_queuememberlist,
06739 };
06740 
06741 static struct ast_custom_function queuememberpenalty_function = {
06742    .name = "QUEUE_MEMBER_PENALTY",
06743    .read = queue_function_memberpenalty_read,
06744    .write = queue_function_memberpenalty_write,
06745 };
06746 
06747 /*! \brief Reload the rules defined in queuerules.conf
06748  *
06749  * \param reload If 1, then only process queuerules.conf if the file
06750  * has changed since the last time we inspected it.
06751  * \return Always returns AST_MODULE_LOAD_SUCCESS
06752  */
06753 static int reload_queue_rules(int reload)
06754 {
06755    struct ast_config *cfg;
06756    struct rule_list *rl_iter, *new_rl;
06757    struct penalty_rule *pr_iter;
06758    char *rulecat = NULL;
06759    struct ast_variable *rulevar = NULL;
06760    struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
06761    
06762    if (!(cfg = ast_config_load("queuerules.conf", config_flags))) {
06763       ast_log(LOG_NOTICE, "No queuerules.conf file found, queues will not follow penalty rules\n");
06764       return AST_MODULE_LOAD_SUCCESS;
06765    } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
06766       ast_log(LOG_NOTICE, "queuerules.conf has not changed since it was last loaded. Not taking any action.\n");
06767       return AST_MODULE_LOAD_SUCCESS;
06768    } else if (cfg == CONFIG_STATUS_FILEINVALID) {
06769       ast_log(LOG_ERROR, "Config file queuerules.conf is in an invalid format.  Aborting.\n");
06770       return AST_MODULE_LOAD_SUCCESS;
06771    }
06772 
06773    AST_LIST_LOCK(&rule_lists);
06774    while ((rl_iter = AST_LIST_REMOVE_HEAD(&rule_lists, list))) {
06775       while ((pr_iter = AST_LIST_REMOVE_HEAD(&rl_iter->rules, list)))
06776          ast_free(pr_iter);
06777       ast_free(rl_iter);
06778    }
06779    while ((rulecat = ast_category_browse(cfg, rulecat))) {
06780       if (!(new_rl = ast_calloc(1, sizeof(*new_rl)))) {
06781          AST_LIST_UNLOCK(&rule_lists);
06782          ast_config_destroy(cfg);
06783          return AST_MODULE_LOAD_FAILURE;
06784       } else {
06785          ast_copy_string(new_rl->name, rulecat, sizeof(new_rl->name));
06786          AST_LIST_INSERT_TAIL(&rule_lists, new_rl, list);
06787          for (rulevar = ast_variable_browse(cfg, rulecat); rulevar; rulevar = rulevar->next)
06788             if(!strcasecmp(rulevar->name, "penaltychange"))
06789                insert_penaltychange(new_rl->name, rulevar->value, rulevar->lineno);
06790             else
06791                ast_log(LOG_WARNING, "Don't know how to handle rule type '%s' on line %d\n", rulevar->name, rulevar->lineno);
06792       }
06793    }
06794    AST_LIST_UNLOCK(&rule_lists);
06795 
06796    ast_config_destroy(cfg);
06797 
06798    return AST_MODULE_LOAD_SUCCESS;
06799 }
06800 
06801 /*! Set the global queue parameters as defined in the "general" section of queues.conf */
06802 static void queue_set_global_params(struct ast_config *cfg)
06803 {
06804    const char *general_val = NULL;
06805    queue_persistent_members = 0;
06806    if ((general_val = ast_variable_retrieve(cfg, "general", "persistentmembers")))
06807       queue_persistent_members = ast_true(general_val);
06808    autofill_default = 0;
06809    if ((general_val = ast_variable_retrieve(cfg, "general", "autofill")))
06810       autofill_default = ast_true(general_val);
06811    montype_default = 0;
06812    if ((general_val = ast_variable_retrieve(cfg, "general", "monitor-type"))) {
06813       if (!strcasecmp(general_val, "mixmonitor"))
06814          montype_default = 1;
06815    }
06816    update_cdr = 0;
06817    if ((general_val = ast_variable_retrieve(cfg, "general", "updatecdr")))
06818       update_cdr = ast_true(general_val);
06819    shared_lastcall = 0;
06820    if ((general_val = ast_variable_retrieve(cfg, "general", "shared_lastcall")))
06821       shared_lastcall = ast_true(general_val);
06822 }
06823 
06824 /*! \brief reload information pertaining to a single member
06825  *
06826  * This function is called when a member = line is encountered in
06827  * queues.conf.
06828  *
06829  * \param memberdata The part after member = in the config file
06830  * \param q The queue to which this member belongs
06831  */
06832 static void reload_single_member(const char *memberdata, struct call_queue *q)
06833 {
06834    char *membername, *interface, *state_interface, *tmp;
06835    char *parse;
06836    struct member *cur, *newm;
06837    struct member tmpmem;
06838    int penalty;
06839    AST_DECLARE_APP_ARGS(args,
06840       AST_APP_ARG(interface);
06841       AST_APP_ARG(penalty);
06842       AST_APP_ARG(membername);
06843       AST_APP_ARG(state_interface);
06844    );
06845 
06846    if (ast_strlen_zero(memberdata)) {
06847       ast_log(LOG_WARNING, "Empty queue member definition. Moving on!\n");
06848       return;
06849    }
06850 
06851    /* Add a new member */
06852    parse = ast_strdupa(memberdata);
06853             
06854    AST_STANDARD_APP_ARGS(args, parse);
06855 
06856    interface = args.interface;
06857    if (!ast_strlen_zero(args.penalty)) {
06858       tmp = args.penalty;
06859       ast_strip(tmp);
06860       penalty = atoi(tmp);
06861       if (penalty < 0) {
06862          penalty = 0;
06863       }
06864    } else {
06865       penalty = 0;
06866    }
06867 
06868    if (!ast_strlen_zero(args.membername)) {
06869       membername = args.membername;
06870       ast_strip(membername);
06871    } else {
06872       membername = interface;
06873    }
06874 
06875    if (!ast_strlen_zero(args.state_interface)) {
06876       state_interface = args.state_interface;
06877       ast_strip(state_interface);
06878    } else {
06879       state_interface = interface;
06880    }
06881 
06882    /* Find the old position in the list */
06883    ast_copy_string(tmpmem.interface, interface, sizeof(tmpmem.interface));
06884    cur = ao2_find(q->members, &tmpmem, OBJ_POINTER);
06885 
06886    if ((newm = create_queue_member(interface, membername, penalty, cur ? cur->paused : 0, state_interface))) {
06887       if (cur) {
06888          /* Round Robin Queue Position must be copied if this is replacing an existing member */
06889          ao2_lock(q->members);
06890          newm->queuepos = cur->queuepos;
06891          ao2_link(q->members, newm);
06892          ao2_unlink(q->members, cur);
06893          ao2_unlock(q->members);
06894       } else {
06895          /* Otherwise we need to add using the function that will apply a round robin queue position manually. */
06896          member_add_to_queue(q, newm);
06897       }
06898       ao2_ref(newm, -1);
06899    }
06900    newm = NULL;
06901 
06902    if (cur) {
06903       ao2_ref(cur, -1);
06904    }
06905 }
06906 
06907 static int mark_member_dead(void *obj, void *arg, int flags)
06908 {
06909    struct member *member = obj;
06910    if (!member->dynamic) {
06911       member->delme = 1;
06912    }
06913    return 0;
06914 }
06915 
06916 static int kill_dead_members(void *obj, void *arg, int flags)
06917 {
06918    struct member *member = obj;
06919 
06920    if (!member->delme) {
06921       member->status = get_queue_member_status(member);
06922       return 0;
06923    } else {
06924       return CMP_MATCH;
06925    }
06926 }
06927 
06928 /*! \brief Reload information pertaining to a particular queue
06929  *
06930  * Once we have isolated a queue within reload_queues, we call this. This will either
06931  * reload information for the queue or if we're just reloading member information, we'll just
06932  * reload that without touching other settings within the queue 
06933  *
06934  * \param cfg The configuration which we are reading
06935  * \param mask Tells us what information we need to reload
06936  * \param queuename The name of the queue we are reloading information from
06937  * \retval void
06938  */
06939 static void reload_single_queue(struct ast_config *cfg, struct ast_flags *mask, const char *queuename)
06940 {
06941    int new;
06942    struct call_queue *q = NULL;
06943    /*We're defining a queue*/
06944    struct call_queue tmpq = {
06945       .name = queuename,
06946    };
06947    const char *tmpvar;
06948    const int queue_reload = ast_test_flag(mask, QUEUE_RELOAD_PARAMETERS);
06949    const int member_reload = ast_test_flag(mask, QUEUE_RELOAD_MEMBER);
06950    int prev_weight = 0;
06951    struct ast_variable *var;
06952    if (!(q = ao2_t_find(queues, &tmpq, OBJ_POINTER, "Find queue for reload"))) {
06953       if (queue_reload) {
06954          /* Make one then */
06955          if (!(q = alloc_queue(queuename))) {
06956             return;
06957          }
06958       } else {
06959          /* Since we're not reloading queues, this means that we found a queue
06960           * in the configuration file which we don't know about yet. Just return.
06961           */
06962          return;
06963       }
06964       new = 1;
06965    } else {
06966       new = 0;
06967    }
06968    
06969    if (!new) {
06970       ao2_lock(q);
06971       prev_weight = q->weight ? 1 : 0;
06972    }
06973    /* Check if we already found a queue with this name in the config file */
06974    if (q->found) {
06975       ast_log(LOG_WARNING, "Queue '%s' already defined! Skipping!\n", queuename);
06976       if (!new) {
06977          /* It should be impossible to *not* hit this case*/
06978          ao2_unlock(q);
06979       }
06980       queue_t_unref(q, "We exist! Expiring temporary pointer");
06981       return;
06982    }
06983    /* Due to the fact that the "linear" strategy will have a different allocation
06984     * scheme for queue members, we must devise the queue's strategy before other initializations.
06985     * To be specific, the linear strategy needs to function like a linked list, meaning the ao2
06986     * container used will have only a single bucket instead of the typical number.
06987     */
06988    if (queue_reload) {
06989       if ((tmpvar = ast_variable_retrieve(cfg, queuename, "strategy"))) {
06990          q->strategy = strat2int(tmpvar);
06991          if (q->strategy < 0) {
06992             ast_log(LOG_WARNING, "'%s' isn't a valid strategy for queue '%s', using ringall instead\n",
06993             tmpvar, q->name);
06994             q->strategy = QUEUE_STRATEGY_RINGALL;
06995          }
06996       } else {
06997          q->strategy = QUEUE_STRATEGY_RINGALL;
06998       }
06999       init_queue(q);
07000    }
07001    if (member_reload) {
07002       ao2_callback(q->members, OBJ_NODATA, mark_member_dead, NULL);
07003       q->found = 1;
07004    }
07005    for (var = ast_variable_browse(cfg, queuename); var; var = var->next) {
07006       if (member_reload && !strcasecmp(var->name, "member")) {
07007          reload_single_member(var->value, q);
07008       } else if (queue_reload) {
07009          queue_set_param(q, var->name, var->value, var->lineno, 1);
07010       }
07011    }
07012    /* At this point, we've determined if the queue has a weight, so update use_weight
07013     * as appropriate
07014     */
07015    if (!q->weight && prev_weight) {
07016       ast_atomic_fetchadd_int(&use_weight, -1);
07017    }
07018    else if (q->weight && !prev_weight) {
07019       ast_atomic_fetchadd_int(&use_weight, +1);
07020    }
07021 
07022    /* Free remaining members marked as delme */
07023    if (member_reload) {
07024       ao2_lock(q->members);
07025       ao2_callback(q->members, OBJ_NODATA | OBJ_MULTIPLE, queue_delme_members_decrement_followers, q);
07026       ao2_callback(q->members, OBJ_NODATA | OBJ_MULTIPLE | OBJ_UNLINK, kill_dead_members, q);
07027       ao2_unlock(q->members);
07028    }
07029 
07030    if (new) {
07031       queues_t_link(queues, q, "Add queue to container");
07032    } else {
07033       ao2_unlock(q);
07034    }
07035    queue_t_unref(q, "Expiring creation reference");
07036 }
07037 
07038 static int remove_members_and_mark_unfound(void *obj, void *arg, int flags)
07039 {
07040    struct call_queue *q = obj;
07041    char *queuename = arg;
07042    if (!q->realtime && (ast_strlen_zero(queuename) || !strcasecmp(queuename, q->name))) {
07043       q->found = 0;
07044 
07045    }
07046    return 0;
07047 }
07048 
07049 static int mark_dead_and_unfound(void *obj, void *arg, int flags)
07050 {
07051    struct call_queue *q = obj;
07052    char *queuename = arg;
07053    if (!q->realtime && (ast_strlen_zero(queuename) || !strcasecmp(queuename, q->name))) {
07054       q->dead = 1;
07055       q->found = 0;
07056    }
07057    return 0;
07058 }
07059 
07060 static int kill_dead_queues(void *obj, void *arg, int flags)
07061 {
07062    struct call_queue *q = obj;
07063    char *queuename = arg;
07064    if ((ast_strlen_zero(queuename) || !strcasecmp(queuename, q->name)) && q->dead) {
07065       return CMP_MATCH;
07066    } else {
07067       return 0;
07068    }
07069 }
07070 
07071 /*! \brief reload the queues.conf file
07072  *
07073  * This function reloads the information in the general section of the queues.conf
07074  * file and potentially more, depending on the value of mask.
07075  *
07076  * \param reload 0 if we are calling this the first time, 1 every other time
07077  * \param mask Gives flags telling us what information to actually reload
07078  * \param queuename If set to a non-zero string, then only reload information from
07079  * that particular queue. Otherwise inspect all queues
07080  * \retval -1 Failure occurred 
07081  * \retval 0 All clear!
07082  */
07083 static int reload_queues(int reload, struct ast_flags *mask, const char *queuename)
07084 {
07085    struct ast_config *cfg;
07086    char *cat;
07087    struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
07088    const int queue_reload = ast_test_flag(mask, QUEUE_RELOAD_PARAMETERS);
07089    const int member_reload = ast_test_flag(mask, QUEUE_RELOAD_MEMBER);
07090 
07091    if (!(cfg = ast_config_load("queues.conf", config_flags))) {
07092       ast_log(LOG_NOTICE, "No call queueing config file (queues.conf), so no call queues\n");
07093       return -1;
07094    } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
07095       return 0;
07096    } else if (cfg == CONFIG_STATUS_FILEINVALID) {
07097       ast_log(LOG_ERROR, "Config file queues.conf is in an invalid format.  Aborting.\n");
07098       return -1;
07099    }
07100 
07101    /* We've made it here, so it looks like we're doing operations on all queues. */
07102    ao2_lock(queues);
07103 
07104    /* Mark all queues as dead for the moment if we're reloading queues.
07105     * For clarity, we could just be reloading members, in which case we don't want to mess
07106     * with the other queue parameters at all*/
07107    if (queue_reload) {
07108       ao2_callback(queues, OBJ_NODATA, mark_dead_and_unfound, (char *) queuename);
07109    }
07110 
07111    if (member_reload) {
07112       ao2_callback(queues, OBJ_NODATA, remove_members_and_mark_unfound, (char *) queuename);
07113    }
07114 
07115    /* Chug through config file */
07116    cat = NULL;
07117    while ((cat = ast_category_browse(cfg, cat)) ) {
07118       if (!strcasecmp(cat, "general") && queue_reload) {
07119          queue_set_global_params(cfg);
07120          continue;
07121       }
07122       if (ast_strlen_zero(queuename) || !strcasecmp(cat, queuename))
07123          reload_single_queue(cfg, mask, cat);
07124    }
07125 
07126    ast_config_destroy(cfg);
07127    /* Unref all the dead queues if we were reloading queues */
07128    if (queue_reload) {
07129       ao2_callback(queues, OBJ_NODATA | OBJ_MULTIPLE | OBJ_UNLINK, kill_dead_queues, (char *) queuename);
07130    }
07131    ao2_unlock(queues);
07132    return 0;
07133 }
07134 
07135 /*! \brief Facilitates resetting statistics for a queue
07136  *
07137  * This function actually does not reset any statistics, but
07138  * rather finds a call_queue struct which corresponds to the
07139  * passed-in queue name and passes that structure to the
07140  * clear_queue function. If no queuename is passed in, then
07141  * all queues will have their statistics reset.
07142  *
07143  * \param queuename The name of the queue to reset the statistics
07144  * for. If this is NULL or zero-length, then this means to reset
07145  * the statistics for all queues
07146  * \retval void
07147  */
07148 static int clear_stats(const char *queuename)
07149 {
07150    struct call_queue *q;
07151    struct ao2_iterator queue_iter;
07152 
07153    queue_iter = ao2_iterator_init(queues, 0);
07154    while ((q = ao2_t_iterator_next(&queue_iter, "Iterate through queues"))) {
07155       ao2_lock(q);
07156       if (ast_strlen_zero(queuename) || !strcasecmp(q->name, queuename))
07157          clear_queue(q);
07158       ao2_unlock(q);
07159       queue_t_unref(q, "Done with iterator");
07160    }
07161    ao2_iterator_destroy(&queue_iter);
07162    return 0;
07163 }
07164 
07165 /*! \brief The command center for all reload operations
07166  *
07167  * Whenever any piece of queue information is to be reloaded, this function
07168  * is called. It interprets the flags set in the mask parameter and acts
07169  * based on how they are set.
07170  *
07171  * \param reload True if we are reloading information, false if we are loading
07172  * information for the first time.
07173  * \param mask A bitmask which tells the handler what actions to take
07174  * \param queuename The name of the queue on which we wish to take action
07175  * \retval 0 All reloads were successful
07176  * \retval non-zero There was a failure
07177  */
07178 static int reload_handler(int reload, struct ast_flags *mask, const char *queuename)
07179 {
07180    int res = 0;
07181 
07182    if (ast_test_flag(mask, QUEUE_RELOAD_RULES)) {
07183       res |= reload_queue_rules(reload);
07184    }
07185    if (ast_test_flag(mask, QUEUE_RESET_STATS)) {
07186       res |= clear_stats(queuename);
07187    }
07188    if (ast_test_flag(mask, (QUEUE_RELOAD_PARAMETERS | QUEUE_RELOAD_MEMBER))) {
07189       res |= reload_queues(reload, mask, queuename);
07190    }
07191    return res;
07192 }
07193 
07194 /*! \brief direct ouput to manager or cli with proper terminator */
07195 static void do_print(struct mansession *s, int fd, const char *str)
07196 {
07197    if (s)
07198       astman_append(s, "%s\r\n", str);
07199    else
07200       ast_cli(fd, "%s\n", str);
07201 }
07202 
07203 /*! 
07204  * \brief Show queue(s) status and statistics 
07205  * 
07206  * List the queues strategy, calls processed, members logged in,
07207  * other queue statistics such as avg hold time.
07208 */
07209 static char *__queues_show(struct mansession *s, int fd, int argc, const char * const *argv)
07210 {
07211    struct call_queue *q;
07212    struct ast_str *out = ast_str_alloca(240);
07213    int found = 0;
07214    time_t now = time(NULL);
07215    struct ao2_iterator queue_iter;
07216    struct ao2_iterator mem_iter;
07217 
07218    if (argc != 2 && argc != 3)
07219       return CLI_SHOWUSAGE;
07220 
07221    if (argc == 3) { /* specific queue */
07222       if ((q = load_realtime_queue(argv[2]))) {
07223          queue_t_unref(q, "Done with temporary pointer");
07224       }
07225    } else if (ast_check_realtime("queues")) {
07226       /* This block is to find any queues which are defined in realtime but
07227        * which have not yet been added to the in-core container
07228        */
07229       struct ast_config *cfg = ast_load_realtime_multientry("queues", "name LIKE", "%", SENTINEL);
07230       char *queuename;
07231       if (cfg) {
07232          for (queuename = ast_category_browse(cfg, NULL); !ast_strlen_zero(queuename); queuename = ast_category_browse(cfg, queuename)) {
07233             if ((q = load_realtime_queue(queuename))) {
07234                queue_t_unref(q, "Done with temporary pointer");
07235             }
07236          }
07237          ast_config_destroy(cfg);
07238       }
07239    }
07240 
07241    ao2_lock(queues);
07242    queue_iter = ao2_iterator_init(queues, AO2_ITERATOR_DONTLOCK);
07243    while ((q = ao2_t_iterator_next(&queue_iter, "Iterate through queues"))) {
07244       float sl;
07245       struct call_queue *realtime_queue = NULL;
07246 
07247       ao2_lock(q);
07248       /* This check is to make sure we don't print information for realtime
07249        * queues which have been deleted from realtime but which have not yet
07250        * been deleted from the in-core container
07251        */
07252       if (q->realtime) {
07253          realtime_queue = load_realtime_queue(q->name);
07254          if (!realtime_queue) {
07255             ao2_unlock(q);
07256             queue_t_unref(q, "Done with iterator");
07257             continue;
07258          }
07259          queue_t_unref(realtime_queue, "Queue is already in memory");
07260       }
07261 
07262       if (argc == 3 && strcasecmp(q->name, argv[2])) {
07263          ao2_unlock(q);
07264          queue_t_unref(q, "Done with iterator");
07265          continue;
07266       }
07267       found = 1;
07268 
07269       ast_str_set(&out, 0, "%s has %d calls (max ", q->name, q->count);
07270       if (q->maxlen)
07271          ast_str_append(&out, 0, "%d", q->maxlen);
07272       else
07273          ast_str_append(&out, 0, "unlimited");
07274       sl = 0;
07275       if (q->callscompleted > 0)
07276          sl = 100 * ((float) q->callscompletedinsl / (float) q->callscompleted);
07277       ast_str_append(&out, 0, ") in '%s' strategy (%ds holdtime, %ds talktime), W:%d, C:%d, A:%d, SL:%2.1f%% within %ds",
07278          int2strat(q->strategy), q->holdtime, q->talktime, q->weight,
07279          q->callscompleted, q->callsabandoned,sl,q->servicelevel);
07280       do_print(s, fd, ast_str_buffer(out));
07281       if (!ao2_container_count(q->members))
07282          do_print(s, fd, "   No Members");
07283       else {
07284          struct member *mem;
07285 
07286          do_print(s, fd, "   Members: ");
07287          mem_iter = ao2_iterator_init(q->members, 0);
07288          while ((mem = ao2_iterator_next(&mem_iter))) {
07289             ast_str_set(&out, 0, "      %s", mem->membername);
07290             if (strcasecmp(mem->membername, mem->interface)) {
07291                ast_str_append(&out, 0, " (%s)", mem->interface);
07292             }
07293             if (mem->penalty)
07294                ast_str_append(&out, 0, " with penalty %d", mem->penalty);
07295             ast_str_append(&out, 0, "%s%s%s (%s)",
07296                mem->dynamic ? " (dynamic)" : "",
07297                mem->realtime ? " (realtime)" : "",
07298                mem->paused ? " (paused)" : "",
07299                ast_devstate2str(mem->status));
07300             if (mem->calls)
07301                ast_str_append(&out, 0, " has taken %d calls (last was %ld secs ago)",
07302                   mem->calls, (long) (time(NULL) - mem->lastcall));
07303             else
07304                ast_str_append(&out, 0, " has taken no calls yet");
07305             do_print(s, fd, ast_str_buffer(out));
07306             ao2_ref(mem, -1);
07307          }
07308          ao2_iterator_destroy(&mem_iter);
07309       }
07310       if (!q->head)
07311          do_print(s, fd, "   No Callers");
07312       else {
07313          struct queue_ent *qe;
07314          int pos = 1;
07315 
07316          do_print(s, fd, "   Callers: ");
07317          for (qe = q->head; qe; qe = qe->next) {
07318             ast_str_set(&out, 0, "      %d. %s (wait: %ld:%2.2ld, prio: %d)",
07319                pos++, qe->chan->name, (long) (now - qe->start) / 60,
07320                (long) (now - qe->start) % 60, qe->prio);
07321             do_print(s, fd, ast_str_buffer(out));
07322          }
07323       }
07324       do_print(s, fd, ""); /* blank line between entries */
07325       ao2_unlock(q);
07326       queue_t_unref(q, "Done with iterator"); /* Unref the iterator's reference */
07327    }
07328    ao2_iterator_destroy(&queue_iter);
07329    ao2_unlock(queues);
07330    if (!found) {
07331       if (argc == 3)
07332          ast_str_set(&out, 0, "No such queue: %s.", argv[2]);
07333       else
07334          ast_str_set(&out, 0, "No queues.");
07335       do_print(s, fd, ast_str_buffer(out));
07336    }
07337    return CLI_SUCCESS;
07338 }
07339 
07340 /*! 
07341  * \brief Check if a given word is in a space-delimited list
07342  *
07343  * \param list Space delimited list of words
07344  * \param word The word used to search the list
07345  *
07346  * \note This function will not return 1 if the word is at the very end of the
07347  * list (followed immediately by a \0, not a space) since it is used for
07348  * checking tab-completion and a word at the end is still being tab-completed.
07349  *
07350  * \return Returns 1 if the word is found
07351  * \return Returns 0 if the word is not found
07352 */
07353 static int word_in_list(const char *list, const char *word) {
07354    int list_len, word_len = strlen(word);
07355    const char *find, *end_find, *end_list;
07356 
07357    /* strip whitespace from front */
07358    while (isspace(*list)) {
07359       list++;
07360    }
07361 
07362    while ((find = strstr(list, word))) {
07363       /* beginning of find starts inside another word? */
07364       if (find != list && *(find - 1) != ' ') {
07365          list = find;
07366          /* strip word from front */
07367          while (!isspace(*list) && *list != '\0') {
07368             list++;
07369          }
07370          /* strip whitespace from front */
07371          while (isspace(*list)) {
07372             list++;
07373          }
07374          continue;
07375       }
07376 
07377       /* end of find ends inside another word or at very end of list? */
07378       list_len = strlen(list);
07379       end_find = find + word_len;
07380       end_list = list + list_len;
07381       if (end_find == end_list || *end_find != ' ') {
07382          list = find;
07383          /* strip word from front */
07384          while (!isspace(*list) && *list != '\0') {
07385             list++;
07386          }
07387          /* strip whitespace from front */
07388          while (isspace(*list)) {
07389             list++;
07390          }
07391          continue;
07392       }
07393 
07394       /* terminating conditions satisfied, word at beginning or separated by ' ' */
07395       return 1;
07396    }
07397    
07398    return 0;
07399 }
07400 
07401 /*! 
07402  * \brief Check if a given word is in a space-delimited list
07403  *
07404  * \param line The line as typed not including the current word being completed
07405  * \param word The word currently being completed
07406  * \param pos The number of completed words in line
07407  * \param state The nth desired completion option
07408  * \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.
07409  *
07410  * \return Returns the queue tab-completion for the given word and state
07411 */
07412 static char *complete_queue(const char *line, const char *word, int pos, int state, ptrdiff_t word_list_offset)
07413 {
07414    struct call_queue *q;
07415    char *ret = NULL;
07416    int which = 0;
07417    int wordlen = strlen(word);
07418    struct ao2_iterator queue_iter;
07419    const char *word_list = NULL;
07420 
07421    /* for certain commands, already completed items should be left out of
07422     * the list */
07423    if (word_list_offset && strlen(line) >= word_list_offset) {
07424       word_list = line + word_list_offset;
07425    }
07426 
07427    queue_iter = ao2_iterator_init(queues, 0);
07428    while ((q = ao2_t_iterator_next(&queue_iter, "Iterate through queues"))) {
07429       if (!strncasecmp(word, q->name, wordlen) && ++which > state
07430          && (!word_list_offset || !word_in_list(word_list, q->name))) {
07431          ret = ast_strdup(q->name);
07432          queue_t_unref(q, "Done with iterator");
07433          break;
07434       }
07435       queue_t_unref(q, "Done with iterator");
07436    }
07437    ao2_iterator_destroy(&queue_iter);
07438 
07439    /* Pretend "rules" is at the end of the queues list in certain
07440     * circumstances since it is an alternate command that should be
07441     * tab-completable for "queue show" */
07442    if (!ret && which == state && !wordlen && !strncmp("queue show", line, 10)) {
07443       ret = ast_strdup("rules");
07444    }
07445 
07446    return ret;
07447 }
07448 
07449 static char *complete_queue_show(const char *line, const char *word, int pos, int state)
07450 {
07451    if (pos == 2) {
07452       return complete_queue(line, word, pos, state, 0);
07453    }
07454    return NULL;
07455 }
07456 
07457 static char *queue_show(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
07458 {
07459    switch ( cmd ) {
07460    case CLI_INIT:
07461       e->command = "queue show";
07462       e->usage =
07463          "Usage: queue show\n"
07464          "       Provides summary information on a specified queue.\n";
07465       return NULL;
07466    case CLI_GENERATE:
07467       return complete_queue_show(a->line, a->word, a->pos, a->n); 
07468    }
07469 
07470    return __queues_show(NULL, a->fd, a->argc, a->argv);
07471 }
07472 
07473 /*!\brief callback to display queues status in manager
07474    \addtogroup Group_AMI
07475  */
07476 static int manager_queues_show(struct mansession *s, const struct message *m)
07477 {
07478    static const char * const a[] = { "queue", "show" };
07479 
07480    __queues_show(s, -1, 2, a);
07481    astman_append(s, "\r\n\r\n"); /* Properly terminate Manager output */
07482 
07483    return RESULT_SUCCESS;
07484 }
07485 
07486 static int manager_queue_rule_show(struct mansession *s, const struct message *m)
07487 {
07488    const char *rule = astman_get_header(m, "Rule");
07489    const char *id = astman_get_header(m, "ActionID");
07490    struct rule_list *rl_iter;
07491    struct penalty_rule *pr_iter;
07492 
07493    astman_append(s, "Response: Success\r\n");
07494    if (!ast_strlen_zero(id)) {
07495       astman_append(s, "ActionID: %s\r\n", id);
07496    }
07497 
07498    AST_LIST_LOCK(&rule_lists);
07499    AST_LIST_TRAVERSE(&rule_lists, rl_iter, list) {
07500       if (ast_strlen_zero(rule) || !strcasecmp(rule, rl_iter->name)) {
07501          astman_append(s, "RuleList: %s\r\n", rl_iter->name);
07502          AST_LIST_TRAVERSE(&rl_iter->rules, pr_iter, list) {
07503             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 );
07504          }
07505          if (!ast_strlen_zero(rule))
07506             break;
07507       }
07508    }
07509    AST_LIST_UNLOCK(&rule_lists);
07510 
07511    /*
07512     * Two blank lines instead of one because the Response and
07513     * ActionID headers used to not be present.
07514     */
07515    astman_append(s, "\r\n\r\n");
07516 
07517    return RESULT_SUCCESS;
07518 }
07519 
07520 /*! \brief Summary of queue info via the AMI */
07521 static int manager_queues_summary(struct mansession *s, const struct message *m)
07522 {
07523    time_t now;
07524    int qmemcount = 0;
07525    int qmemavail = 0;
07526    int qchancount = 0;
07527    int qlongestholdtime = 0;
07528    const char *id = astman_get_header(m, "ActionID");
07529    const char *queuefilter = astman_get_header(m, "Queue");
07530    char idText[256] = "";
07531    struct call_queue *q;
07532    struct queue_ent *qe;
07533    struct member *mem;
07534    struct ao2_iterator queue_iter;
07535    struct ao2_iterator mem_iter;
07536 
07537    astman_send_ack(s, m, "Queue summary will follow");
07538    time(&now);
07539    if (!ast_strlen_zero(id))
07540       snprintf(idText, 256, "ActionID: %s\r\n", id);
07541    queue_iter = ao2_iterator_init(queues, 0);
07542    while ((q = ao2_t_iterator_next(&queue_iter, "Iterate through queues"))) {
07543       ao2_lock(q);
07544 
07545       /* List queue properties */
07546       if (ast_strlen_zero(queuefilter) || !strcmp(q->name, queuefilter)) {
07547          /* Reset the necessary local variables if no queuefilter is set*/
07548          qmemcount = 0;
07549          qmemavail = 0;
07550          qchancount = 0;
07551          qlongestholdtime = 0;
07552 
07553          /* List Queue Members */
07554          mem_iter = ao2_iterator_init(q->members, 0);
07555          while ((mem = ao2_iterator_next(&mem_iter))) {
07556             if ((mem->status != AST_DEVICE_UNAVAILABLE) && (mem->status != AST_DEVICE_INVALID)) {
07557                ++qmemcount;
07558                if (member_status_available(mem->status) && !mem->paused) {
07559                   ++qmemavail;
07560                }
07561             }
07562             ao2_ref(mem, -1);
07563          }
07564          ao2_iterator_destroy(&mem_iter);
07565          for (qe = q->head; qe; qe = qe->next) {
07566             if ((now - qe->start) > qlongestholdtime) {
07567                qlongestholdtime = now - qe->start;
07568             }
07569             ++qchancount;
07570          }
07571          astman_append(s, "Event: QueueSummary\r\n"
07572             "Queue: %s\r\n"
07573             "LoggedIn: %d\r\n"
07574             "Available: %d\r\n"
07575             "Callers: %d\r\n" 
07576             "HoldTime: %d\r\n"
07577             "TalkTime: %d\r\n"
07578             "LongestHoldTime: %d\r\n"
07579             "%s"
07580             "\r\n",
07581             q->name, qmemcount, qmemavail, qchancount, q->holdtime, q->talktime, qlongestholdtime, idText);
07582       }
07583       ao2_unlock(q);
07584       queue_t_unref(q, "Done with iterator");
07585    }
07586    ao2_iterator_destroy(&queue_iter);
07587    astman_append(s,
07588       "Event: QueueSummaryComplete\r\n"
07589       "%s"
07590       "\r\n", idText);
07591 
07592    return RESULT_SUCCESS;
07593 }
07594 
07595 /*! \brief Queue status info via AMI */
07596 static int manager_queues_status(struct mansession *s, const struct message *m)
07597 {
07598    time_t now;
07599    int pos;
07600    const char *id = astman_get_header(m,"ActionID");
07601    const char *queuefilter = astman_get_header(m,"Queue");
07602    const char *memberfilter = astman_get_header(m,"Member");
07603    char idText[256] = "";
07604    struct call_queue *q;
07605    struct queue_ent *qe;
07606    float sl = 0;
07607    struct member *mem;
07608    struct ao2_iterator queue_iter;
07609    struct ao2_iterator mem_iter;
07610 
07611    astman_send_ack(s, m, "Queue status will follow");
07612    time(&now);
07613    if (!ast_strlen_zero(id))
07614       snprintf(idText, sizeof(idText), "ActionID: %s\r\n", id);
07615 
07616    queue_iter = ao2_iterator_init(queues, 0);
07617    while ((q = ao2_t_iterator_next(&queue_iter, "Iterate through queues"))) {
07618       ao2_lock(q);
07619 
07620       /* List queue properties */
07621       if (ast_strlen_zero(queuefilter) || !strcmp(q->name, queuefilter)) {
07622          sl = ((q->callscompleted > 0) ? 100 * ((float)q->callscompletedinsl / (float)q->callscompleted) : 0);
07623          astman_append(s, "Event: QueueParams\r\n"
07624             "Queue: %s\r\n"
07625             "Max: %d\r\n"
07626             "Strategy: %s\r\n"
07627             "Calls: %d\r\n"
07628             "Holdtime: %d\r\n"
07629             "TalkTime: %d\r\n"
07630             "Completed: %d\r\n"
07631             "Abandoned: %d\r\n"
07632             "ServiceLevel: %d\r\n"
07633             "ServicelevelPerf: %2.1f\r\n"
07634             "Weight: %d\r\n"
07635             "%s"
07636             "\r\n",
07637             q->name, q->maxlen, int2strat(q->strategy), q->count, q->holdtime, q->talktime, q->callscompleted,
07638             q->callsabandoned, q->servicelevel, sl, q->weight, idText);
07639          /* List Queue Members */
07640          mem_iter = ao2_iterator_init(q->members, 0);
07641          while ((mem = ao2_iterator_next(&mem_iter))) {
07642             if (ast_strlen_zero(memberfilter) || !strcmp(mem->interface, memberfilter) || !strcmp(mem->membername, memberfilter)) {
07643                astman_append(s, "Event: QueueMember\r\n"
07644                   "Queue: %s\r\n"
07645                   "Name: %s\r\n"
07646                   "Location: %s\r\n"
07647                   "Membership: %s\r\n"
07648                   "Penalty: %d\r\n"
07649                   "CallsTaken: %d\r\n"
07650                   "LastCall: %d\r\n"
07651                   "Status: %d\r\n"
07652                   "Paused: %d\r\n"
07653                   "%s"
07654                   "\r\n",
07655                   q->name, mem->membername, mem->interface, mem->dynamic ? "dynamic" : "static",
07656                   mem->penalty, mem->calls, (int)mem->lastcall, mem->status, mem->paused, idText);
07657             }
07658             ao2_ref(mem, -1);
07659          }
07660          ao2_iterator_destroy(&mem_iter);
07661          /* List Queue Entries */
07662          pos = 1;
07663          for (qe = q->head; qe; qe = qe->next) {
07664             astman_append(s, "Event: QueueEntry\r\n"
07665                "Queue: %s\r\n"
07666                "Position: %d\r\n"
07667                "Channel: %s\r\n"
07668                "Uniqueid: %s\r\n"
07669                "CallerIDNum: %s\r\n"
07670                "CallerIDName: %s\r\n"
07671                "ConnectedLineNum: %s\r\n"
07672                "ConnectedLineName: %s\r\n"
07673                "Wait: %ld\r\n"
07674                "%s"
07675                "\r\n",
07676                q->name, pos++, qe->chan->name, qe->chan->uniqueid,
07677                S_COR(qe->chan->caller.id.number.valid, qe->chan->caller.id.number.str, "unknown"),
07678                S_COR(qe->chan->caller.id.name.valid, qe->chan->caller.id.name.str, "unknown"),
07679                S_COR(qe->chan->connected.id.number.valid, qe->chan->connected.id.number.str, "unknown"),
07680                S_COR(qe->chan->connected.id.name.valid, qe->chan->connected.id.name.str, "unknown"),
07681                (long) (now - qe->start), idText);
07682          }
07683       }
07684       ao2_unlock(q);
07685       queue_t_unref(q, "Done with iterator");
07686    }
07687    ao2_iterator_destroy(&queue_iter);
07688 
07689    astman_append(s,
07690       "Event: QueueStatusComplete\r\n"
07691       "%s"
07692       "\r\n",idText);
07693 
07694    return RESULT_SUCCESS;
07695 }
07696 
07697 static int manager_add_queue_member(struct mansession *s, const struct message *m)
07698 {
07699    const char *queuename, *interface, *penalty_s, *paused_s, *membername, *state_interface;
07700    int paused, penalty = 0;
07701 
07702    queuename = astman_get_header(m, "Queue");
07703    interface = astman_get_header(m, "Interface");
07704    penalty_s = astman_get_header(m, "Penalty");
07705    paused_s = astman_get_header(m, "Paused");
07706    membername = astman_get_header(m, "MemberName");
07707    state_interface = astman_get_header(m, "StateInterface");
07708 
07709    if (ast_strlen_zero(queuename)) {
07710       astman_send_error(s, m, "'Queue' not specified.");
07711       return 0;
07712    }
07713 
07714    if (ast_strlen_zero(interface)) {
07715       astman_send_error(s, m, "'Interface' not specified.");
07716       return 0;
07717    }
07718 
07719    if (ast_strlen_zero(penalty_s))
07720       penalty = 0;
07721    else if (sscanf(penalty_s, "%30d", &penalty) != 1 || penalty < 0)
07722       penalty = 0;
07723 
07724    if (ast_strlen_zero(paused_s))
07725       paused = 0;
07726    else
07727       paused = abs(ast_true(paused_s));
07728 
07729    switch (add_to_queue(queuename, interface, membername, penalty, paused, queue_persistent_members, state_interface)) {
07730    case RES_OKAY:
07731       ast_queue_log(queuename, "MANAGER", interface, "ADDMEMBER", "%s", paused ? "PAUSED" : "");
07732       astman_send_ack(s, m, "Added interface to queue");
07733       break;
07734    case RES_EXISTS:
07735       astman_send_error(s, m, "Unable to add interface: Already there");
07736       break;
07737    case RES_NOSUCHQUEUE:
07738       astman_send_error(s, m, "Unable to add interface to queue: No such queue");
07739       break;
07740    case RES_OUTOFMEMORY:
07741       astman_send_error(s, m, "Out of memory");
07742       break;
07743    }
07744 
07745    return 0;
07746 }
07747 
07748 static int manager_remove_queue_member(struct mansession *s, const struct message *m)
07749 {
07750    const char *queuename, *interface;
07751 
07752    queuename = astman_get_header(m, "Queue");
07753    interface = astman_get_header(m, "Interface");
07754 
07755    if (ast_strlen_zero(queuename) || ast_strlen_zero(interface)) {
07756       astman_send_error(s, m, "Need 'Queue' and 'Interface' parameters.");
07757       return 0;
07758    }
07759 
07760    switch (remove_from_queue(queuename, interface)) {
07761    case RES_OKAY:
07762       ast_queue_log(queuename, "MANAGER", interface, "REMOVEMEMBER", "%s", "");
07763       astman_send_ack(s, m, "Removed interface from queue");
07764       break;
07765    case RES_EXISTS:
07766       astman_send_error(s, m, "Unable to remove interface: Not there");
07767       break;
07768    case RES_NOSUCHQUEUE:
07769       astman_send_error(s, m, "Unable to remove interface from queue: No such queue");
07770       break;
07771    case RES_OUTOFMEMORY:
07772       astman_send_error(s, m, "Out of memory");
07773       break;
07774    case RES_NOT_DYNAMIC:
07775       astman_send_error(s, m, "Member not dynamic");
07776       break;
07777    }
07778 
07779    return 0;
07780 }
07781 
07782 static int manager_pause_queue_member(struct mansession *s, const struct message *m)
07783 {
07784    const char *queuename, *interface, *paused_s, *reason;
07785    int paused;
07786 
07787    interface = astman_get_header(m, "Interface");
07788    paused_s = astman_get_header(m, "Paused");
07789    queuename = astman_get_header(m, "Queue");      /* Optional - if not supplied, pause the given Interface in all queues */
07790    reason = astman_get_header(m, "Reason");        /* Optional - Only used for logging purposes */
07791 
07792    if (ast_strlen_zero(interface) || ast_strlen_zero(paused_s)) {
07793       astman_send_error(s, m, "Need 'Interface' and 'Paused' parameters.");
07794       return 0;
07795    }
07796 
07797    paused = abs(ast_true(paused_s));
07798 
07799    if (set_member_paused(queuename, interface, reason, paused))
07800       astman_send_error(s, m, "Interface not found");
07801    else
07802       astman_send_ack(s, m, paused ? "Interface paused successfully" : "Interface unpaused successfully");
07803    return 0;
07804 }
07805 
07806 static int manager_queue_log_custom(struct mansession *s, const struct message *m)
07807 {
07808    const char *queuename, *event, *message, *interface, *uniqueid;
07809 
07810    queuename = astman_get_header(m, "Queue");
07811    uniqueid = astman_get_header(m, "UniqueId");
07812    interface = astman_get_header(m, "Interface");
07813    event = astman_get_header(m, "Event");
07814    message = astman_get_header(m, "Message");
07815 
07816    if (ast_strlen_zero(queuename) || ast_strlen_zero(event)) {
07817       astman_send_error(s, m, "Need 'Queue' and 'Event' parameters.");
07818       return 0;
07819    }
07820 
07821    ast_queue_log(queuename, S_OR(uniqueid, "NONE"), interface, event, "%s", message);
07822    astman_send_ack(s, m, "Event added successfully");
07823 
07824    return 0;
07825 }
07826 
07827 static int manager_queue_reload(struct mansession *s, const struct message *m)
07828 {
07829    struct ast_flags mask = {0,};
07830    const char *queuename = NULL;
07831    int header_found = 0;
07832 
07833    queuename = astman_get_header(m, "Queue");
07834    if (!strcasecmp(S_OR(astman_get_header(m, "Members"), ""), "yes")) {
07835       ast_set_flag(&mask, QUEUE_RELOAD_MEMBER);
07836       header_found = 1;
07837    }
07838    if (!strcasecmp(S_OR(astman_get_header(m, "Rules"), ""), "yes")) {
07839       ast_set_flag(&mask, QUEUE_RELOAD_RULES);
07840       header_found = 1;
07841    }
07842    if (!strcasecmp(S_OR(astman_get_header(m, "Parameters"), ""), "yes")) {
07843       ast_set_flag(&mask, QUEUE_RELOAD_PARAMETERS);
07844       header_found = 1;
07845    }
07846 
07847    if (!header_found) {
07848       ast_set_flag(&mask, AST_FLAGS_ALL);
07849    }
07850 
07851    if (!reload_handler(1, &mask, queuename)) {
07852       astman_send_ack(s, m, "Queue reloaded successfully");
07853    } else {
07854       astman_send_error(s, m, "Error encountered while reloading queue");
07855    }
07856    return 0;
07857 }
07858 
07859 static int manager_queue_reset(struct mansession *s, const struct message *m)
07860 {
07861    const char *queuename = NULL;
07862    struct ast_flags mask = {QUEUE_RESET_STATS,};
07863    
07864    queuename = astman_get_header(m, "Queue");
07865 
07866    if (!reload_handler(1, &mask, queuename)) {
07867       astman_send_ack(s, m, "Queue stats reset successfully");
07868    } else {
07869       astman_send_error(s, m, "Error encountered while resetting queue stats");
07870    }
07871    return 0;
07872 }
07873 
07874 static char *complete_queue_add_member(const char *line, const char *word, int pos, int state)
07875 {
07876    /* 0 - queue; 1 - add; 2 - member; 3 - <interface>; 4 - to; 5 - <queue>; 6 - penalty; 7 - <penalty>; 8 - as; 9 - <membername> */
07877    switch (pos) {
07878    case 3: /* Don't attempt to complete name of interface (infinite possibilities) */
07879       return NULL;
07880    case 4: /* only one possible match, "to" */
07881       return state == 0 ? ast_strdup("to") : NULL;
07882    case 5: /* <queue> */
07883       return complete_queue(line, word, pos, state, 0);
07884    case 6: /* only one possible match, "penalty" */
07885       return state == 0 ? ast_strdup("penalty") : NULL;
07886    case 7:
07887       if (state < 100) {      /* 0-99 */
07888          char *num;
07889          if ((num = ast_malloc(3))) {
07890             sprintf(num, "%d", state);
07891          }
07892          return num;
07893       } else {
07894          return NULL;
07895       }
07896    case 8: /* only one possible match, "as" */
07897       return state == 0 ? ast_strdup("as") : NULL;
07898    case 9: /* Don't attempt to complete name of member (infinite possibilities) */
07899       return NULL;
07900    default:
07901       return NULL;
07902    }
07903 }
07904 
07905 static int manager_queue_member_penalty(struct mansession *s, const struct message *m)
07906 {
07907    const char *queuename, *interface, *penalty_s;
07908    int penalty;
07909 
07910    interface = astman_get_header(m, "Interface");
07911    penalty_s = astman_get_header(m, "Penalty");
07912    /* Optional - if not supplied, set the penalty value for the given Interface in all queues */
07913    queuename = astman_get_header(m, "Queue");
07914 
07915    if (ast_strlen_zero(interface) || ast_strlen_zero(penalty_s)) {
07916       astman_send_error(s, m, "Need 'Interface' and 'Penalty' parameters.");
07917       return 0;
07918    }
07919  
07920    penalty = atoi(penalty_s);
07921 
07922    if (set_member_penalty((char *)queuename, (char *)interface, penalty))
07923       astman_send_error(s, m, "Invalid interface, queuename or penalty");
07924    else
07925       astman_send_ack(s, m, "Interface penalty set successfully");
07926 
07927    return 0;
07928 }
07929 
07930 static char *handle_queue_add_member(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
07931 {
07932    const char *queuename, *interface, *membername = NULL, *state_interface = NULL;
07933    int penalty;
07934 
07935    switch ( cmd ) {
07936    case CLI_INIT:
07937       e->command = "queue add member";
07938       e->usage =
07939          "Usage: queue add member <channel> to <queue> [[[penalty <penalty>] as <membername>] state_interface <interface>]\n"
07940          "       Add a channel to a queue with optionally:  a penalty, membername and a state_interface\n";
07941       return NULL;
07942    case CLI_GENERATE:
07943       return complete_queue_add_member(a->line, a->word, a->pos, a->n);
07944    }
07945 
07946    if ((a->argc != 6) && (a->argc != 8) && (a->argc != 10) && (a->argc != 12)) {
07947       return CLI_SHOWUSAGE;
07948    } else if (strcmp(a->argv[4], "to")) {
07949       return CLI_SHOWUSAGE;
07950    } else if ((a->argc >= 8) && strcmp(a->argv[6], "penalty")) {
07951       return CLI_SHOWUSAGE;
07952    } else if ((a->argc >= 10) && strcmp(a->argv[8], "as")) {
07953       return CLI_SHOWUSAGE;
07954    } else if ((a->argc == 12) && strcmp(a->argv[10], "state_interface")) {
07955       return CLI_SHOWUSAGE;
07956    }
07957 
07958    queuename = a->argv[5];
07959    interface = a->argv[3];
07960    if (a->argc >= 8) {
07961       if (sscanf(a->argv[7], "%30d", &penalty) == 1) {
07962          if (penalty < 0) {
07963             ast_cli(a->fd, "Penalty must be >= 0\n");
07964             penalty = 0;
07965          }
07966       } else {
07967          ast_cli(a->fd, "Penalty must be an integer >= 0\n");
07968          penalty = 0;
07969       }
07970    } else {
07971       penalty = 0;
07972    }
07973 
07974    if (a->argc >= 10) {
07975       membername = a->argv[9];
07976    }
07977 
07978    if (a->argc >= 12) {
07979       state_interface = a->argv[11];
07980    }
07981 
07982    switch (add_to_queue(queuename, interface, membername, penalty, 0, queue_persistent_members, state_interface)) {
07983    case RES_OKAY:
07984       ast_queue_log(queuename, "CLI", interface, "ADDMEMBER", "%s", "");
07985       ast_cli(a->fd, "Added interface '%s' to queue '%s'\n", interface, queuename);
07986       return CLI_SUCCESS;
07987    case RES_EXISTS:
07988       ast_cli(a->fd, "Unable to add interface '%s' to queue '%s': Already there\n", interface, queuename);
07989       return CLI_FAILURE;
07990    case RES_NOSUCHQUEUE:
07991       ast_cli(a->fd, "Unable to add interface to queue '%s': No such queue\n", queuename);
07992       return CLI_FAILURE;
07993    case RES_OUTOFMEMORY:
07994       ast_cli(a->fd, "Out of memory\n");
07995       return CLI_FAILURE;
07996    case RES_NOT_DYNAMIC:
07997       ast_cli(a->fd, "Member not dynamic\n");
07998       return CLI_FAILURE;
07999    default:
08000       return CLI_FAILURE;
08001    }
08002 }
08003 
08004 static char *complete_queue_remove_member(const char *line, const char *word, int pos, int state)
08005 {
08006    int which = 0;
08007    struct call_queue *q;
08008    struct member *m;
08009    struct ao2_iterator queue_iter;
08010    struct ao2_iterator mem_iter;
08011    int wordlen = strlen(word);
08012 
08013    /* 0 - queue; 1 - remove; 2 - member; 3 - <member>; 4 - from; 5 - <queue> */
08014    if (pos > 5 || pos < 3)
08015       return NULL;
08016    if (pos == 4)   /* only one possible match, 'from' */
08017       return (state == 0 ? ast_strdup("from") : NULL);
08018 
08019    if (pos == 5) {  /* No need to duplicate code */
08020       return complete_queue(line, word, pos, state, 0);
08021    }
08022 
08023    /* here is the case for 3, <member> */
08024    queue_iter = ao2_iterator_init(queues, 0);
08025    while ((q = ao2_t_iterator_next(&queue_iter, "Iterate through queues"))) {
08026       ao2_lock(q);
08027       mem_iter = ao2_iterator_init(q->members, 0);
08028       while ((m = ao2_iterator_next(&mem_iter))) {
08029          if (!strncasecmp(word, m->membername, wordlen) && ++which > state) {
08030             char *tmp;
08031             tmp = ast_strdup(m->interface);
08032             ao2_ref(m, -1);
08033             ao2_iterator_destroy(&mem_iter);
08034             ao2_unlock(q);
08035             queue_t_unref(q, "Done with iterator, returning interface name");
08036             ao2_iterator_destroy(&queue_iter);
08037             return tmp;
08038          }
08039          ao2_ref(m, -1);
08040       }
08041       ao2_iterator_destroy(&mem_iter);
08042       ao2_unlock(q);
08043       queue_t_unref(q, "Done with iterator");
08044    }
08045    ao2_iterator_destroy(&queue_iter);
08046 
08047    return NULL;
08048 }
08049 
08050 static char *handle_queue_remove_member(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
08051 {
08052    const char *queuename, *interface;
08053 
08054    switch (cmd) {
08055    case CLI_INIT:
08056       e->command = "queue remove member";
08057       e->usage = 
08058          "Usage: queue remove member <channel> from <queue>\n"
08059          "       Remove a specific channel from a queue.\n";
08060       return NULL;
08061    case CLI_GENERATE:
08062       return complete_queue_remove_member(a->line, a->word, a->pos, a->n);
08063    }
08064 
08065    if (a->argc != 6) {
08066       return CLI_SHOWUSAGE;
08067    } else if (strcmp(a->argv[4], "from")) {
08068       return CLI_SHOWUSAGE;
08069    }
08070 
08071    queuename = a->argv[5];
08072    interface = a->argv[3];
08073 
08074    switch (remove_from_queue(queuename, interface)) {
08075    case RES_OKAY:
08076       ast_queue_log(queuename, "CLI", interface, "REMOVEMEMBER", "%s", "");
08077       ast_cli(a->fd, "Removed interface '%s' from queue '%s'\n", interface, queuename);
08078       return CLI_SUCCESS;
08079    case RES_EXISTS:
08080       ast_cli(a->fd, "Unable to remove interface '%s' from queue '%s': Not there\n", interface, queuename);
08081       return CLI_FAILURE;
08082    case RES_NOSUCHQUEUE:
08083       ast_cli(a->fd, "Unable to remove interface from queue '%s': No such queue\n", queuename);
08084       return CLI_FAILURE;
08085    case RES_OUTOFMEMORY:
08086       ast_cli(a->fd, "Out of memory\n");
08087       return CLI_FAILURE;
08088    case RES_NOT_DYNAMIC:
08089       ast_cli(a->fd, "Unable to remove interface '%s' from queue '%s': Member is not dynamic\n", interface, queuename);
08090       return CLI_FAILURE;
08091    default:
08092       return CLI_FAILURE;
08093    }
08094 }
08095 
08096 static char *complete_queue_pause_member(const char *line, const char *word, int pos, int state)
08097 {
08098    /* 0 - queue; 1 - pause; 2 - member; 3 - <interface>; 4 - queue; 5 - <queue>; 6 - reason; 7 - <reason> */
08099    switch (pos) {
08100    case 3:  /* Don't attempt to complete name of interface (infinite possibilities) */
08101       return NULL;
08102    case 4:  /* only one possible match, "queue" */
08103       return state == 0 ? ast_strdup("queue") : NULL;
08104    case 5:  /* <queue> */
08105       return complete_queue(line, word, pos, state, 0);
08106    case 6: /* "reason" */
08107       return state == 0 ? ast_strdup("reason") : NULL;
08108    case 7: /* Can't autocomplete a reason, since it's 100% customizeable */
08109       return NULL;
08110    default:
08111       return NULL;
08112    }
08113 }
08114 
08115 static char *handle_queue_pause_member(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
08116 {
08117    const char *queuename, *interface, *reason;
08118    int paused;
08119 
08120    switch (cmd) {
08121    case CLI_INIT:
08122       e->command = "queue {pause|unpause} member";
08123       e->usage = 
08124          "Usage: queue {pause|unpause} member <member> [queue <queue> [reason <reason>]]\n"
08125          "  Pause or unpause a queue member. Not specifying a particular queue\n"
08126          "  will pause or unpause a member across all queues to which the member\n"
08127          "  belongs.\n";
08128       return NULL;
08129    case CLI_GENERATE:
08130       return complete_queue_pause_member(a->line, a-> word, a->pos, a->n);
08131    }
08132 
08133    if (a->argc < 4 || a->argc == 5 || a->argc == 7 || a->argc > 8) {
08134       return CLI_SHOWUSAGE;
08135    } else if (a->argc >= 5 && strcmp(a->argv[4], "queue")) {
08136       return CLI_SHOWUSAGE;
08137    } else if (a->argc == 8 && strcmp(a->argv[6], "reason")) {
08138       return CLI_SHOWUSAGE;
08139    }
08140 
08141 
08142    interface = a->argv[3];
08143    queuename = a->argc >= 6 ? a->argv[5] : NULL;
08144    reason = a->argc == 8 ? a->argv[7] : NULL;
08145    paused = !strcasecmp(a->argv[1], "pause");
08146 
08147    if (set_member_paused(queuename, interface, reason, paused) == RESULT_SUCCESS) {
08148       ast_cli(a->fd, "%spaused interface '%s'", paused ? "" : "un", interface);
08149       if (!ast_strlen_zero(queuename))
08150          ast_cli(a->fd, " in queue '%s'", queuename);
08151       if (!ast_strlen_zero(reason))
08152          ast_cli(a->fd, " for reason '%s'", reason);
08153       ast_cli(a->fd, "\n");
08154       return CLI_SUCCESS;
08155    } else {
08156       ast_cli(a->fd, "Unable to %spause interface '%s'", paused ? "" : "un", interface);
08157       if (!ast_strlen_zero(queuename))
08158          ast_cli(a->fd, " in queue '%s'", queuename);
08159       if (!ast_strlen_zero(reason))
08160          ast_cli(a->fd, " for reason '%s'", reason);
08161       ast_cli(a->fd, "\n");
08162       return CLI_FAILURE;
08163    }
08164 }
08165 
08166 static char *complete_queue_set_member_penalty(const char *line, const char *word, int pos, int state)
08167 {
08168    /* 0 - queue; 1 - set; 2 - penalty; 3 - <penalty>; 4 - on; 5 - <member>; 6 - in; 7 - <queue>;*/
08169    switch (pos) {
08170    case 4:
08171       if (state == 0) {
08172          return ast_strdup("on");
08173       } else {
08174          return NULL;
08175       }
08176    case 6:
08177       if (state == 0) {
08178          return ast_strdup("in");
08179       } else {
08180          return NULL;
08181       }
08182    case 7:
08183       return complete_queue(line, word, pos, state, 0);
08184    default:
08185       return NULL;
08186    }
08187 }
08188  
08189 static char *handle_queue_set_member_penalty(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
08190 {
08191    const char *queuename = NULL, *interface;
08192    int penalty = 0;
08193 
08194    switch (cmd) {
08195    case CLI_INIT:
08196       e->command = "queue set penalty";
08197       e->usage = 
08198       "Usage: queue set penalty <penalty> on <interface> [in <queue>]\n"
08199       "  Set a member's penalty in the queue specified. If no queue is specified\n"
08200       "  then that interface's penalty is set in all queues to which that interface is a member\n";
08201       return NULL;
08202    case CLI_GENERATE:
08203       return complete_queue_set_member_penalty(a->line, a->word, a->pos, a->n);
08204    }
08205 
08206    if (a->argc != 6 && a->argc != 8) {
08207       return CLI_SHOWUSAGE;
08208    } else if (strcmp(a->argv[4], "on") || (a->argc > 6 && strcmp(a->argv[6], "in"))) {
08209       return CLI_SHOWUSAGE;
08210    }
08211 
08212    if (a->argc == 8)
08213       queuename = a->argv[7];
08214    interface = a->argv[5];
08215    penalty = atoi(a->argv[3]);
08216 
08217    switch (set_member_penalty(queuename, interface, penalty)) {
08218    case RESULT_SUCCESS:
08219       ast_cli(a->fd, "Set penalty on interface '%s' from queue '%s'\n", interface, queuename);
08220       return CLI_SUCCESS;
08221    case RESULT_FAILURE:
08222       ast_cli(a->fd, "Failed to set penalty on interface '%s' from queue '%s'\n", interface, queuename);
08223       return CLI_FAILURE;
08224    default:
08225       return CLI_FAILURE;
08226    }
08227 }
08228 
08229 static char *complete_queue_rule_show(const char *line, const char *word, int pos, int state) 
08230 {
08231    int which = 0;
08232    struct rule_list *rl_iter;
08233    int wordlen = strlen(word);
08234    char *ret = NULL;
08235    if (pos != 3) /* Wha? */ {
08236       return NULL;
08237    }
08238 
08239    AST_LIST_LOCK(&rule_lists);
08240    AST_LIST_TRAVERSE(&rule_lists, rl_iter, list) {
08241       if (!strncasecmp(word, rl_iter->name, wordlen) && ++which > state) {
08242          ret = ast_strdup(rl_iter->name);
08243          break;
08244       }
08245    }
08246    AST_LIST_UNLOCK(&rule_lists);
08247 
08248    return ret;
08249 }
08250 
08251 static char *handle_queue_rule_show(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
08252 {
08253    const char *rule;
08254    struct rule_list *rl_iter;
08255    struct penalty_rule *pr_iter;
08256    switch (cmd) {
08257    case CLI_INIT:
08258       e->command = "queue show rules";
08259       e->usage =
08260       "Usage: queue show rules [rulename]\n"
08261       "  Show the list of rules associated with rulename. If no\n"
08262       "  rulename is specified, list all rules defined in queuerules.conf\n";
08263       return NULL;
08264    case CLI_GENERATE:
08265       return complete_queue_rule_show(a->line, a->word, a->pos, a->n);
08266    }
08267 
08268    if (a->argc != 3 && a->argc != 4)
08269       return CLI_SHOWUSAGE;
08270 
08271    rule = a->argc == 4 ? a->argv[3] : "";
08272    AST_LIST_LOCK(&rule_lists);
08273    AST_LIST_TRAVERSE(&rule_lists, rl_iter, list) {
08274       if (ast_strlen_zero(rule) || !strcasecmp(rl_iter->name, rule)) {
08275          ast_cli(a->fd, "Rule: %s\n", rl_iter->name);
08276          AST_LIST_TRAVERSE(&rl_iter->rules, pr_iter, list) {
08277             ast_cli(a->fd, "\tAfter %d seconds, adjust QUEUE_MAX_PENALTY %s %d and adjust QUEUE_MIN_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);
08278          }
08279       }
08280    }
08281    AST_LIST_UNLOCK(&rule_lists);
08282    return CLI_SUCCESS; 
08283 }
08284 
08285 static char *handle_queue_reset(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
08286 {
08287    struct ast_flags mask = {QUEUE_RESET_STATS,};
08288    int i;
08289 
08290    switch (cmd) {
08291       case CLI_INIT:
08292          e->command = "queue reset stats";
08293          e->usage =
08294             "Usage: queue reset stats [<queuenames>]\n"
08295             "\n"
08296             "Issuing this command will reset statistics for\n"
08297             "<queuenames>, or for all queues if no queue is\n"
08298             "specified.\n";
08299          return NULL;
08300       case CLI_GENERATE:
08301          if (a->pos >= 3) {
08302             return complete_queue(a->line, a->word, a->pos, a->n, 17);
08303          } else {
08304             return NULL;
08305          }
08306    }
08307 
08308    if (a->argc < 3) {
08309       return CLI_SHOWUSAGE;
08310    }
08311 
08312    if (a->argc == 3) {
08313       reload_handler(1, &mask, NULL);
08314       return CLI_SUCCESS;
08315    }
08316 
08317    for (i = 3; i < a->argc; ++i) {
08318       reload_handler(1, &mask, a->argv[i]);
08319    }
08320 
08321    return CLI_SUCCESS;
08322 }
08323 
08324 static char *handle_queue_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
08325 {
08326    struct ast_flags mask = {0,};
08327    int i;
08328 
08329    switch (cmd) {
08330       case CLI_INIT:
08331          e->command = "queue reload {parameters|members|rules|all}";
08332          e->usage =
08333             "Usage: queue reload {parameters|members|rules|all} [<queuenames>]\n"
08334             "Reload queues. If <queuenames> are specified, only reload information pertaining\n"
08335             "to <queuenames>. One of 'parameters,' 'members,' 'rules,' or 'all' must be\n"
08336             "specified in order to know what information to reload. Below is an explanation\n"
08337             "of each of these qualifiers.\n"
08338             "\n"
08339             "\t'members' - reload queue members from queues.conf\n"
08340             "\t'parameters' - reload all queue options except for queue members\n"
08341             "\t'rules' - reload the queuerules.conf file\n"
08342             "\t'all' - reload queue rules, parameters, and members\n"
08343             "\n"
08344             "Note: the 'rules' qualifier here cannot actually be applied to a specific queue.\n"
08345             "Use of the 'rules' qualifier causes queuerules.conf to be reloaded. Even if only\n"
08346             "one queue is specified when using this command, reloading queue rules may cause\n"
08347             "other queues to be affected\n";
08348          return NULL;
08349       case CLI_GENERATE:
08350          if (a->pos >= 3) {
08351             /* find the point at which the list of queue names starts */
08352             const char *command_end = a->line + strlen("queue reload ");
08353             command_end = strchr(command_end, ' ');
08354             if (!command_end) {
08355                command_end = a->line + strlen(a->line);
08356             }
08357             return complete_queue(a->line, a->word, a->pos, a->n, command_end - a->line);
08358          } else {
08359             return NULL;
08360          }
08361    }
08362 
08363    if (a->argc < 3)
08364       return CLI_SHOWUSAGE;
08365 
08366    if (!strcasecmp(a->argv[2], "rules")) {
08367       ast_set_flag(&mask, QUEUE_RELOAD_RULES);
08368    } else if (!strcasecmp(a->argv[2], "members")) {
08369       ast_set_flag(&mask, QUEUE_RELOAD_MEMBER);
08370    } else if (!strcasecmp(a->argv[2], "parameters")) {
08371       ast_set_flag(&mask, QUEUE_RELOAD_PARAMETERS);
08372    } else if (!strcasecmp(a->argv[2], "all")) {
08373       ast_set_flag(&mask, AST_FLAGS_ALL);
08374    }
08375 
08376    if (a->argc == 3) {
08377       reload_handler(1, &mask, NULL);
08378       return CLI_SUCCESS;
08379    }
08380 
08381    for (i = 3; i < a->argc; ++i) {
08382       reload_handler(1, &mask, a->argv[i]);
08383    }
08384 
08385    return CLI_SUCCESS;
08386 }
08387 
08388 static const char qpm_cmd_usage[] = 
08389 "Usage: queue pause member <channel> in <queue> reason <reason>\n";
08390 
08391 static const char qum_cmd_usage[] =
08392 "Usage: queue unpause member <channel> in <queue> reason <reason>\n";
08393 
08394 static const char qsmp_cmd_usage[] =
08395 "Usage: queue set member penalty <channel> from <queue> <penalty>\n";
08396 
08397 static struct ast_cli_entry cli_queue[] = {
08398    AST_CLI_DEFINE(queue_show, "Show status of a specified queue"),
08399    AST_CLI_DEFINE(handle_queue_rule_show, "Show the rules defined in queuerules.conf"),
08400    AST_CLI_DEFINE(handle_queue_add_member, "Add a channel to a specified queue"),
08401    AST_CLI_DEFINE(handle_queue_remove_member, "Removes a channel from a specified queue"),
08402    AST_CLI_DEFINE(handle_queue_pause_member, "Pause or unpause a queue member"),
08403    AST_CLI_DEFINE(handle_queue_set_member_penalty, "Set penalty for a channel of a specified queue"),
08404    AST_CLI_DEFINE(handle_queue_reload, "Reload queues, members, queue rules, or parameters"),
08405    AST_CLI_DEFINE(handle_queue_reset, "Reset statistics for a queue"),
08406 };
08407 
08408 /* struct call_queue astdata mapping. */
08409 #define DATA_EXPORT_CALL_QUEUE(MEMBER)             \
08410    MEMBER(call_queue, name, AST_DATA_STRING)       \
08411    MEMBER(call_queue, moh, AST_DATA_STRING)        \
08412    MEMBER(call_queue, announce, AST_DATA_STRING)         \
08413    MEMBER(call_queue, context, AST_DATA_STRING)       \
08414    MEMBER(call_queue, membermacro, AST_DATA_STRING)      \
08415    MEMBER(call_queue, membergosub, AST_DATA_STRING)      \
08416    MEMBER(call_queue, defaultrule, AST_DATA_STRING)      \
08417    MEMBER(call_queue, sound_next, AST_DATA_STRING)       \
08418    MEMBER(call_queue, sound_thereare, AST_DATA_STRING)      \
08419    MEMBER(call_queue, sound_calls, AST_DATA_STRING)      \
08420    MEMBER(call_queue, queue_quantity1, AST_DATA_STRING)     \
08421    MEMBER(call_queue, queue_quantity2, AST_DATA_STRING)     \
08422    MEMBER(call_queue, sound_holdtime, AST_DATA_STRING)      \
08423    MEMBER(call_queue, sound_minutes, AST_DATA_STRING)    \
08424    MEMBER(call_queue, sound_minute, AST_DATA_STRING)     \
08425    MEMBER(call_queue, sound_seconds, AST_DATA_STRING)    \
08426    MEMBER(call_queue, sound_thanks, AST_DATA_STRING)     \
08427    MEMBER(call_queue, sound_callerannounce, AST_DATA_STRING)   \
08428    MEMBER(call_queue, sound_reporthold, AST_DATA_STRING)    \
08429    MEMBER(call_queue, dead, AST_DATA_BOOLEAN)         \
08430    MEMBER(call_queue, eventwhencalled, AST_DATA_BOOLEAN)    \
08431    MEMBER(call_queue, ringinuse, AST_DATA_BOOLEAN)       \
08432    MEMBER(call_queue, setinterfacevar, AST_DATA_BOOLEAN)    \
08433    MEMBER(call_queue, setqueuevar, AST_DATA_BOOLEAN)     \
08434    MEMBER(call_queue, setqueueentryvar, AST_DATA_BOOLEAN)      \
08435    MEMBER(call_queue, reportholdtime, AST_DATA_BOOLEAN)     \
08436    MEMBER(call_queue, wrapped, AST_DATA_BOOLEAN)         \
08437    MEMBER(call_queue, timeoutrestart, AST_DATA_BOOLEAN)     \
08438    MEMBER(call_queue, announceholdtime, AST_DATA_INTEGER)      \
08439    MEMBER(call_queue, maskmemberstatus, AST_DATA_BOOLEAN)      \
08440    MEMBER(call_queue, realtime, AST_DATA_BOOLEAN)        \
08441    MEMBER(call_queue, found, AST_DATA_BOOLEAN)        \
08442    MEMBER(call_queue, announcepositionlimit, AST_DATA_INTEGER) \
08443    MEMBER(call_queue, announcefrequency, AST_DATA_SECONDS)     \
08444    MEMBER(call_queue, minannouncefrequency, AST_DATA_SECONDS)  \
08445    MEMBER(call_queue, periodicannouncefrequency, AST_DATA_SECONDS)   \
08446    MEMBER(call_queue, numperiodicannounce, AST_DATA_INTEGER)   \
08447    MEMBER(call_queue, randomperiodicannounce, AST_DATA_INTEGER)   \
08448    MEMBER(call_queue, roundingseconds, AST_DATA_SECONDS)    \
08449    MEMBER(call_queue, holdtime, AST_DATA_SECONDS)        \
08450    MEMBER(call_queue, talktime, AST_DATA_SECONDS)        \
08451    MEMBER(call_queue, callscompleted, AST_DATA_INTEGER)     \
08452    MEMBER(call_queue, callsabandoned, AST_DATA_INTEGER)     \
08453    MEMBER(call_queue, servicelevel, AST_DATA_INTEGER)    \
08454    MEMBER(call_queue, callscompletedinsl, AST_DATA_INTEGER) \
08455    MEMBER(call_queue, monfmt, AST_DATA_STRING)        \
08456    MEMBER(call_queue, montype, AST_DATA_INTEGER)         \
08457    MEMBER(call_queue, count, AST_DATA_INTEGER)        \
08458    MEMBER(call_queue, maxlen, AST_DATA_INTEGER)       \
08459    MEMBER(call_queue, wrapuptime, AST_DATA_SECONDS)      \
08460    MEMBER(call_queue, retry, AST_DATA_SECONDS)        \
08461    MEMBER(call_queue, timeout, AST_DATA_SECONDS)         \
08462    MEMBER(call_queue, weight, AST_DATA_INTEGER)       \
08463    MEMBER(call_queue, autopause, AST_DATA_INTEGER)       \
08464    MEMBER(call_queue, timeoutpriority, AST_DATA_INTEGER)    \
08465    MEMBER(call_queue, rrpos, AST_DATA_INTEGER)        \
08466    MEMBER(call_queue, memberdelay, AST_DATA_INTEGER)     \
08467    MEMBER(call_queue, autofill, AST_DATA_INTEGER)        \
08468    MEMBER(call_queue, members, AST_DATA_CONTAINER)
08469 
08470 AST_DATA_STRUCTURE(call_queue, DATA_EXPORT_CALL_QUEUE);
08471 
08472 /* struct member astdata mapping. */
08473 #define DATA_EXPORT_MEMBER(MEMBER)              \
08474    MEMBER(member, interface, AST_DATA_STRING)         \
08475    MEMBER(member, state_interface, AST_DATA_STRING)      \
08476    MEMBER(member, membername, AST_DATA_STRING)        \
08477    MEMBER(member, penalty, AST_DATA_INTEGER)       \
08478    MEMBER(member, calls, AST_DATA_INTEGER)            \
08479    MEMBER(member, dynamic, AST_DATA_INTEGER)       \
08480    MEMBER(member, realtime, AST_DATA_INTEGER)         \
08481    MEMBER(member, status, AST_DATA_INTEGER)        \
08482    MEMBER(member, paused, AST_DATA_BOOLEAN)        \
08483    MEMBER(member, rt_uniqueid, AST_DATA_STRING)
08484 
08485 AST_DATA_STRUCTURE(member, DATA_EXPORT_MEMBER);
08486 
08487 #define DATA_EXPORT_QUEUE_ENT(MEMBER)                 \
08488    MEMBER(queue_ent, moh, AST_DATA_STRING)               \
08489    MEMBER(queue_ent, announce, AST_DATA_STRING)          \
08490    MEMBER(queue_ent, context, AST_DATA_STRING)           \
08491    MEMBER(queue_ent, digits, AST_DATA_STRING)            \
08492    MEMBER(queue_ent, valid_digits, AST_DATA_INTEGER)        \
08493    MEMBER(queue_ent, pos, AST_DATA_INTEGER)           \
08494    MEMBER(queue_ent, prio, AST_DATA_INTEGER)          \
08495    MEMBER(queue_ent, last_pos_said, AST_DATA_INTEGER)       \
08496    MEMBER(queue_ent, last_periodic_announce_time, AST_DATA_INTEGER)  \
08497    MEMBER(queue_ent, last_periodic_announce_sound, AST_DATA_INTEGER) \
08498    MEMBER(queue_ent, last_pos, AST_DATA_INTEGER)            \
08499    MEMBER(queue_ent, opos, AST_DATA_INTEGER)          \
08500    MEMBER(queue_ent, handled, AST_DATA_INTEGER)          \
08501    MEMBER(queue_ent, pending, AST_DATA_INTEGER)          \
08502    MEMBER(queue_ent, max_penalty, AST_DATA_INTEGER)         \
08503    MEMBER(queue_ent, min_penalty, AST_DATA_INTEGER)         \
08504    MEMBER(queue_ent, linpos, AST_DATA_INTEGER)           \
08505    MEMBER(queue_ent, linwrapped, AST_DATA_INTEGER)          \
08506    MEMBER(queue_ent, start, AST_DATA_INTEGER)            \
08507    MEMBER(queue_ent, expire, AST_DATA_INTEGER)           \
08508    MEMBER(queue_ent, cancel_answered_elsewhere, AST_DATA_INTEGER)
08509 
08510 AST_DATA_STRUCTURE(queue_ent, DATA_EXPORT_QUEUE_ENT);
08511 
08512 /*!
08513  * \internal
08514  * \brief Add a queue to the data_root node.
08515  * \param[in] search The search tree.
08516  * \param[in] data_root The main result node.
08517  * \param[in] queue The queue to add.
08518  */
08519 static void queues_data_provider_get_helper(const struct ast_data_search *search,
08520    struct ast_data *data_root, struct call_queue *queue)
08521 {
08522    struct ao2_iterator im;
08523    struct member *member;
08524    struct queue_ent *qe;
08525    struct ast_data *data_queue, *data_members = NULL, *enum_node;
08526    struct ast_data *data_member, *data_callers = NULL, *data_caller, *data_caller_channel;
08527 
08528    data_queue = ast_data_add_node(data_root, "queue");
08529    if (!data_queue) {
08530       return;
08531    }
08532 
08533    ast_data_add_structure(call_queue, data_queue, queue);
08534 
08535    ast_data_add_str(data_queue, "strategy", int2strat(queue->strategy));
08536    ast_data_add_int(data_queue, "membercount", ao2_container_count(queue->members));
08537 
08538    /* announce position */
08539    enum_node = ast_data_add_node(data_queue, "announceposition");
08540    if (!enum_node) {
08541       return;
08542    }
08543    switch (queue->announceposition) {
08544    case ANNOUNCEPOSITION_LIMIT:
08545       ast_data_add_str(enum_node, "text", "limit");
08546       break;
08547    case ANNOUNCEPOSITION_MORE_THAN:
08548       ast_data_add_str(enum_node, "text", "more");
08549       break;
08550    case ANNOUNCEPOSITION_YES:
08551       ast_data_add_str(enum_node, "text", "yes");
08552       break;
08553    case ANNOUNCEPOSITION_NO:
08554       ast_data_add_str(enum_node, "text", "no");
08555       break;
08556    default:
08557       ast_data_add_str(enum_node, "text", "unknown");
08558       break;
08559    }
08560    ast_data_add_int(enum_node, "value", queue->announceposition);
08561 
08562    /* add queue members */
08563    im = ao2_iterator_init(queue->members, 0);
08564    while ((member = ao2_iterator_next(&im))) {
08565       if (!data_members) {
08566          data_members = ast_data_add_node(data_queue, "members");
08567          if (!data_members) {
08568             ao2_ref(member, -1);
08569             continue;
08570          }
08571       }
08572 
08573       data_member = ast_data_add_node(data_members, "member");
08574       if (!data_member) {
08575          ao2_ref(member, -1);
08576          continue;
08577       }
08578 
08579       ast_data_add_structure(member, data_member, member);
08580 
08581       ao2_ref(member, -1);
08582    }
08583    ao2_iterator_destroy(&im);
08584 
08585    /* include the callers inside the result. */
08586    if (queue->head) {
08587       for (qe = queue->head; qe; qe = qe->next) {
08588          if (!data_callers) {
08589             data_callers = ast_data_add_node(data_queue, "callers");
08590             if (!data_callers) {
08591                continue;
08592             }
08593          }
08594 
08595          data_caller = ast_data_add_node(data_callers, "caller");
08596          if (!data_caller) {
08597             continue;
08598          }
08599 
08600          ast_data_add_structure(queue_ent, data_caller, qe);
08601 
08602          /* add the caller channel. */
08603          data_caller_channel = ast_data_add_node(data_caller, "channel");
08604          if (!data_caller_channel) {
08605             continue;
08606          }
08607 
08608          ast_channel_data_add_structure(data_caller_channel, qe->chan, 1);
08609       }
08610    }
08611 
08612    /* if this queue doesn't match remove the added queue. */
08613    if (!ast_data_search_match(search, data_queue)) {
08614       ast_data_remove_node(data_root, data_queue);
08615    }
08616 }
08617 
08618 /*!
08619  * \internal
08620  * \brief Callback used to generate the queues tree.
08621  * \param[in] search The search pattern tree.
08622  * \retval NULL on error.
08623  * \retval non-NULL The generated tree.
08624  */
08625 static int queues_data_provider_get(const struct ast_data_search *search,
08626    struct ast_data *data_root)
08627 {
08628    struct ao2_iterator i;
08629    struct call_queue *queue, *queue_realtime = NULL;
08630    struct ast_config *cfg;
08631    char *queuename;
08632 
08633    /* load realtime queues. */
08634    cfg = ast_load_realtime_multientry("queues", "name LIKE", "%", SENTINEL);
08635    if (cfg) {
08636       for (queuename = ast_category_browse(cfg, NULL);
08637             !ast_strlen_zero(queuename);
08638             queuename = ast_category_browse(cfg, queuename)) {
08639          if ((queue = load_realtime_queue(queuename))) {
08640             queue_unref(queue);
08641          }
08642       }
08643       ast_config_destroy(cfg);
08644    }
08645 
08646    /* static queues. */
08647    i = ao2_iterator_init(queues, 0);
08648    while ((queue = ao2_iterator_next(&i))) {
08649       ao2_lock(queue);
08650       if (queue->realtime) {
08651          queue_realtime = load_realtime_queue(queue->name);
08652          if (!queue_realtime) {
08653             ao2_unlock(queue);
08654             queue_unref(queue);
08655             continue;
08656          }
08657          queue_unref(queue_realtime);
08658       }
08659 
08660       queues_data_provider_get_helper(search, data_root, queue);
08661       ao2_unlock(queue);
08662       queue_unref(queue);
08663    }
08664    ao2_iterator_destroy(&i);
08665 
08666    return 0;
08667 }
08668 
08669 static const struct ast_data_handler queues_data_provider = {
08670    .version = AST_DATA_HANDLER_VERSION,
08671    .get = queues_data_provider_get
08672 };
08673 
08674 static const struct ast_data_entry queue_data_providers[] = {
08675    AST_DATA_ENTRY("asterisk/application/queue/list", &queues_data_provider),
08676 };
08677 
08678 static int unload_module(void)
08679 {
08680    int res;
08681    struct ast_context *con;
08682    struct ao2_iterator q_iter;
08683    struct call_queue *q = NULL;
08684 
08685    ast_cli_unregister_multiple(cli_queue, ARRAY_LEN(cli_queue));
08686    res = ast_manager_unregister("QueueStatus");
08687    res |= ast_manager_unregister("Queues");
08688    res |= ast_manager_unregister("QueueRule");
08689    res |= ast_manager_unregister("QueueSummary");
08690    res |= ast_manager_unregister("QueueAdd");
08691    res |= ast_manager_unregister("QueueRemove");
08692    res |= ast_manager_unregister("QueuePause");
08693    res |= ast_manager_unregister("QueueLog");
08694    res |= ast_manager_unregister("QueuePenalty");
08695    res |= ast_unregister_application(app_aqm);
08696    res |= ast_unregister_application(app_rqm);
08697    res |= ast_unregister_application(app_pqm);
08698    res |= ast_unregister_application(app_upqm);
08699    res |= ast_unregister_application(app_ql);
08700    res |= ast_unregister_application(app);
08701    res |= ast_custom_function_unregister(&queueexists_function);
08702    res |= ast_custom_function_unregister(&queuevar_function);
08703    res |= ast_custom_function_unregister(&queuemembercount_function);
08704    res |= ast_custom_function_unregister(&queuemembercount_dep);
08705    res |= ast_custom_function_unregister(&queuememberlist_function);
08706    res |= ast_custom_function_unregister(&queuewaitingcount_function);
08707    res |= ast_custom_function_unregister(&queuememberpenalty_function);
08708 
08709    res |= ast_data_unregister(NULL);
08710 
08711    if (device_state_sub)
08712       ast_event_unsubscribe(device_state_sub);
08713 
08714    ast_extension_state_del(0, extension_state_cb);
08715 
08716    if ((con = ast_context_find("app_queue_gosub_virtual_context"))) {
08717       ast_context_remove_extension2(con, "s", 1, NULL, 0);
08718       ast_context_destroy(con, "app_queue"); /* leave no trace */
08719    }
08720 
08721    q_iter = ao2_iterator_init(queues, 0);
08722    while ((q = ao2_t_iterator_next(&q_iter, "Iterate through queues"))) {
08723       queues_t_unlink(queues, q, "Remove queue from container due to unload");
08724       queue_t_unref(q, "Done with iterator");
08725    }
08726    ao2_iterator_destroy(&q_iter);
08727    devicestate_tps = ast_taskprocessor_unreference(devicestate_tps);
08728    ao2_ref(queues, -1);
08729    ast_unload_realtime("queue_members");
08730    return res;
08731 }
08732 
08733 static int load_module(void)
08734 {
08735    int res;
08736    struct ast_context *con;
08737    struct ast_flags mask = {AST_FLAGS_ALL, };
08738 
08739    queues = ao2_container_alloc(MAX_QUEUE_BUCKETS, queue_hash_cb, queue_cmp_cb);
08740 
08741    use_weight = 0;
08742 
08743    if (reload_handler(0, &mask, NULL))
08744       return AST_MODULE_LOAD_DECLINE;
08745 
08746    con = ast_context_find_or_create(NULL, NULL, "app_queue_gosub_virtual_context", "app_queue");
08747    if (!con)
08748       ast_log(LOG_ERROR, "Queue virtual context 'app_queue_gosub_virtual_context' does not exist and unable to create\n");
08749    else
08750       ast_add_extension2(con, 1, "s", 1, NULL, NULL, "NoOp", ast_strdup(""), ast_free_ptr, "app_queue");
08751 
08752    if (queue_persistent_members)
08753       reload_queue_members();
08754 
08755    ast_data_register_multiple(queue_data_providers, ARRAY_LEN(queue_data_providers));
08756 
08757    ast_cli_register_multiple(cli_queue, ARRAY_LEN(cli_queue));
08758    res = ast_register_application_xml(app, queue_exec);
08759    res |= ast_register_application_xml(app_aqm, aqm_exec);
08760    res |= ast_register_application_xml(app_rqm, rqm_exec);
08761    res |= ast_register_application_xml(app_pqm, pqm_exec);
08762    res |= ast_register_application_xml(app_upqm, upqm_exec);
08763    res |= ast_register_application_xml(app_ql, ql_exec);
08764    res |= ast_manager_register_xml("Queues", 0, manager_queues_show);
08765    res |= ast_manager_register_xml("QueueStatus", 0, manager_queues_status);
08766    res |= ast_manager_register_xml("QueueSummary", 0, manager_queues_summary);
08767    res |= ast_manager_register_xml("QueueAdd", EVENT_FLAG_AGENT, manager_add_queue_member);
08768    res |= ast_manager_register_xml("QueueRemove", EVENT_FLAG_AGENT, manager_remove_queue_member);
08769    res |= ast_manager_register_xml("QueuePause", EVENT_FLAG_AGENT, manager_pause_queue_member);
08770    res |= ast_manager_register_xml("QueueLog", EVENT_FLAG_AGENT, manager_queue_log_custom);
08771    res |= ast_manager_register_xml("QueuePenalty", EVENT_FLAG_AGENT, manager_queue_member_penalty);
08772    res |= ast_manager_register_xml("QueueRule", 0, manager_queue_rule_show);
08773    res |= ast_manager_register_xml("QueueReload", 0, manager_queue_reload);
08774    res |= ast_manager_register_xml("QueueReset", 0, manager_queue_reset);
08775    res |= ast_custom_function_register(&queuevar_function);
08776    res |= ast_custom_function_register(&queueexists_function);
08777    res |= ast_custom_function_register(&queuemembercount_function);
08778    res |= ast_custom_function_register(&queuemembercount_dep);
08779    res |= ast_custom_function_register(&queuememberlist_function);
08780    res |= ast_custom_function_register(&queuewaitingcount_function);
08781    res |= ast_custom_function_register(&queuememberpenalty_function);
08782 
08783    if (!(devicestate_tps = ast_taskprocessor_get("app_queue", 0))) {
08784       ast_log(LOG_WARNING, "devicestate taskprocessor reference failed - devicestate notifications will not occur\n");
08785    }
08786 
08787    /* in the following subscribe call, do I use DEVICE_STATE, or DEVICE_STATE_CHANGE? */
08788    if (!(device_state_sub = ast_event_subscribe(AST_EVENT_DEVICE_STATE, device_state_cb, "AppQueue Device state", NULL, AST_EVENT_IE_END))) {
08789       res = -1;
08790    }
08791 
08792    ast_extension_state_add(NULL, NULL, extension_state_cb, NULL);
08793 
08794    ast_realtime_require_field("queue_members", "paused", RQ_INTEGER1, 1, "uniqueid", RQ_UINTEGER2, 5, SENTINEL);
08795 
08796    return res ? AST_MODULE_LOAD_DECLINE : 0;
08797 }
08798 
08799 static int reload(void)
08800 {
08801    struct ast_flags mask = {AST_FLAGS_ALL & ~QUEUE_RESET_STATS,};
08802    ast_unload_realtime("queue_members");
08803    reload_handler(1, &mask, NULL);
08804    return 0;
08805 }
08806 
08807 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "True Call Queueing",
08808       .load = load_module,
08809       .unload = unload_module,
08810       .reload = reload,
08811       .load_pri = AST_MODPRI_DEVSTATE_CONSUMER,
08812       .nonoptreq = "res_monitor",
08813           );
08814 

Generated on 18 Jan 2013 for Asterisk - The Open Source Telephony Project by  doxygen 1.6.1