Fri Jul 3 20:35:32 2009

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         <depend>res_monitor</depend>
00061  ***/
00062 
00063 #include "asterisk.h"
00064 
00065 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
00066 
00067 #include <stdlib.h>
00068 #include <errno.h>
00069 #include <unistd.h>
00070 #include <string.h>
00071 #include <stdlib.h>
00072 #include <stdio.h>
00073 #include <sys/time.h>
00074 #include <sys/signal.h>
00075 #include <netinet/in.h>
00076 
00077 #include "asterisk/lock.h"
00078 #include "asterisk/file.h"
00079 #include "asterisk/logger.h"
00080 #include "asterisk/channel.h"
00081 #include "asterisk/pbx.h"
00082 #include "asterisk/options.h"
00083 #include "asterisk/app.h"
00084 #include "asterisk/linkedlists.h"
00085 #include "asterisk/module.h"
00086 #include "asterisk/translate.h"
00087 #include "asterisk/say.h"
00088 #include "asterisk/features.h"
00089 #include "asterisk/musiconhold.h"
00090 #include "asterisk/cli.h"
00091 #include "asterisk/manager.h"
00092 #include "asterisk/config.h"
00093 #include "asterisk/monitor.h"
00094 #include "asterisk/utils.h"
00095 #include "asterisk/causes.h"
00096 #include "asterisk/astdb.h"
00097 #include "asterisk/devicestate.h"
00098 #include "asterisk/stringfields.h"
00099 #include "asterisk/astobj2.h"
00100 #include "asterisk/global_datastores.h"
00101 
00102 /* Please read before modifying this file.
00103  * There are three locks which are regularly used
00104  * throughout this file, the queue list lock, the lock
00105  * for each individual queue, and the interface list lock.
00106  * Please be extra careful to always lock in the following order
00107  * 1) queue list lock
00108  * 2) individual queue lock
00109  * 3) interface list lock
00110  * This order has sort of "evolved" over the lifetime of this
00111  * application, but it is now in place this way, so please adhere
00112  * to this order!
00113  */
00114 
00115 
00116 enum {
00117    QUEUE_STRATEGY_RINGALL = 0,
00118    QUEUE_STRATEGY_ROUNDROBIN,
00119    QUEUE_STRATEGY_LEASTRECENT,
00120    QUEUE_STRATEGY_FEWESTCALLS,
00121    QUEUE_STRATEGY_RANDOM,
00122    QUEUE_STRATEGY_RRMEMORY
00123 };
00124 
00125 static struct strategy {
00126    int strategy;
00127    char *name;
00128 } strategies[] = {
00129    { QUEUE_STRATEGY_RINGALL, "ringall" },
00130    { QUEUE_STRATEGY_ROUNDROBIN, "roundrobin" },
00131    { QUEUE_STRATEGY_LEASTRECENT, "leastrecent" },
00132    { QUEUE_STRATEGY_FEWESTCALLS, "fewestcalls" },
00133    { QUEUE_STRATEGY_RANDOM, "random" },
00134    { QUEUE_STRATEGY_RRMEMORY, "rrmemory" },
00135 };
00136 
00137 #define DEFAULT_RETRY      5
00138 #define DEFAULT_TIMEOUT    15
00139 #define RECHECK         1     /* Recheck every second to see we we're at the top yet */
00140 #define MAX_PERIODIC_ANNOUNCEMENTS 10 /* The maximum periodic announcements we can have */
00141 
00142 #define  RES_OKAY 0     /* Action completed */
00143 #define  RES_EXISTS  (-1)     /* Entry already exists */
00144 #define  RES_OUTOFMEMORY   (-2)     /* Out of memory */
00145 #define  RES_NOSUCHQUEUE   (-3)     /* No such queue */
00146 #define RES_NOT_DYNAMIC (-4)     /* Member is not dynamic */
00147 
00148 static char *app = "Queue";
00149 
00150 static char *synopsis = "Queue a call for a call queue";
00151 
00152 static char *descrip =
00153 "  Queue(queuename[|options[|URL][|announceoverride][|timeout][|AGI]):\n"
00154 "Queues an incoming call in a particular call queue as defined in queues.conf.\n"
00155 "This application will return to the dialplan if the queue does not exist, or\n"
00156 "any of the join options cause the caller to not enter the queue.\n"
00157 "The option string may contain zero or more of the following characters:\n"
00158 "      'd' -- data-quality (modem) call (minimum delay).\n"
00159 "      'h' -- allow callee to hang up by hitting '*', or whatver disconnect sequence\n"
00160 "             defined in the featuremap section in features.conf.\n"
00161 "      'H' -- allow caller to hang up by hitting '*', or whatever disconnect sequence\n"
00162 "             defined in the featuremap section in features.conf.\n"
00163 "      'n' -- no retries on the timeout; will exit this application and \n"
00164 "             go to the next step.\n"
00165 "      'i' -- ignore call forward requests from queue members and do nothing\n"
00166 "             when they are requested.\n"
00167 "      'r' -- ring instead of playing MOH\n"
00168 "      't' -- allow the called user transfer the calling user by pressing '#' or\n"
00169 "             whatever blindxfer sequence defined in the featuremap section in\n"
00170 "             features.conf\n"
00171 "      'T' -- to allow the calling user to transfer the call by pressing '#' or\n"
00172 "             whatever blindxfer sequence defined in the featuremap section in\n"
00173 "             features.conf\n"
00174 "      'w' -- allow the called user to write the conversation to disk via Monitor\n"
00175 "             by pressing the automon sequence defined in the featuremap section in\n"
00176 "             features.conf\n"
00177 "      'W' -- allow the calling user to write the conversation to disk via Monitor\n"
00178 "             by pressing the automon sequence defined in the featuremap section in\n"
00179 "             features.conf\n"
00180 "  In addition to transferring the call, a call may be parked and then picked\n"
00181 "up by another user, by transferring to the parking lot extension. See features.conf.\n"
00182 "  The optional URL will be sent to the called party if the channel supports\n"
00183 "it.\n"
00184 "  The optional AGI parameter will setup an AGI script to be executed on the \n"
00185 "calling party's channel once they are connected to a queue member.\n"
00186 "  The timeout will cause the queue to fail out after a specified number of\n"
00187 "seconds, checked between each queues.conf 'timeout' and 'retry' cycle.\n"
00188 "  This application sets the following channel variable upon completion:\n"
00189 "      QUEUESTATUS    The status of the call as a text string, one of\n"
00190 "             TIMEOUT | FULL | JOINEMPTY | LEAVEEMPTY | JOINUNAVAIL | LEAVEUNAVAIL\n";
00191 
00192 static char *app_aqm = "AddQueueMember" ;
00193 static char *app_aqm_synopsis = "Dynamically adds queue members" ;
00194 static char *app_aqm_descrip =
00195 "   AddQueueMember(queuename[|interface[|penalty[|options[|membername]]]]):\n"
00196 "Dynamically adds interface to an existing queue.\n"
00197 "If the interface is already in the queue and there exists an n+101 priority\n"
00198 "then it will then jump to this priority.  Otherwise it will return an error\n"
00199 "The option string may contain zero or more of the following characters:\n"
00200 "       'j' -- jump to +101 priority when appropriate.\n"
00201 "  This application sets the following channel variable upon completion:\n"
00202 "     AQMSTATUS    The status of the attempt to add a queue member as a \n"
00203 "                     text string, one of\n"
00204 "           ADDED | MEMBERALREADY | NOSUCHQUEUE \n"
00205 "Example: AddQueueMember(techsupport|SIP/3000)\n"
00206 "";
00207 
00208 static char *app_rqm = "RemoveQueueMember" ;
00209 static char *app_rqm_synopsis = "Dynamically removes queue members" ;
00210 static char *app_rqm_descrip =
00211 "   RemoveQueueMember(queuename[|interface[|options]]):\n"
00212 "Dynamically removes interface to an existing queue\n"
00213 "If the interface is NOT in the queue and there exists an n+101 priority\n"
00214 "then it will then jump to this priority.  Otherwise it will return an error\n"
00215 "The option string may contain zero or more of the following characters:\n"
00216 "       'j' -- jump to +101 priority when appropriate.\n"
00217 "  This application sets the following channel variable upon completion:\n"
00218 "     RQMSTATUS      The status of the attempt to remove a queue member as a\n"
00219 "                     text string, one of\n"
00220 "           REMOVED | NOTINQUEUE | NOSUCHQUEUE \n"
00221 "Example: RemoveQueueMember(techsupport|SIP/3000)\n"
00222 "";
00223 
00224 static char *app_pqm = "PauseQueueMember" ;
00225 static char *app_pqm_synopsis = "Pauses a queue member" ;
00226 static char *app_pqm_descrip =
00227 "   PauseQueueMember([queuename]|interface[|options]):\n"
00228 "Pauses (blocks calls for) a queue member.\n"
00229 "The given interface will be paused in the given queue.  This prevents\n"
00230 "any calls from being sent from the queue to the interface until it is\n"
00231 "unpaused with UnpauseQueueMember or the manager interface.  If no\n"
00232 "queuename is given, the interface is paused in every queue it is a\n"
00233 "member of.  If the interface is not in the named queue, or if no queue\n"
00234 "is given and the interface is not in any queue, it will jump to\n"
00235 "priority n+101, if it exists and the appropriate options are set.\n"
00236 "The application will fail if the interface is not found and no extension\n"
00237 "to jump to exists.\n"
00238 "The option string may contain zero or more of the following characters:\n"
00239 "       'j' -- jump to +101 priority when appropriate.\n"
00240 "  This application sets the following channel variable upon completion:\n"
00241 "     PQMSTATUS      The status of the attempt to pause a queue member as a\n"
00242 "                     text string, one of\n"
00243 "           PAUSED | NOTFOUND\n"
00244 "Example: PauseQueueMember(|SIP/3000)\n";
00245 
00246 static char *app_upqm = "UnpauseQueueMember" ;
00247 static char *app_upqm_synopsis = "Unpauses a queue member" ;
00248 static char *app_upqm_descrip =
00249 "   UnpauseQueueMember([queuename]|interface[|options]):\n"
00250 "Unpauses (resumes calls to) a queue member.\n"
00251 "This is the counterpart to PauseQueueMember and operates exactly the\n"
00252 "same way, except it unpauses instead of pausing the given interface.\n"
00253 "The option string may contain zero or more of the following characters:\n"
00254 "       'j' -- jump to +101 priority when appropriate.\n"
00255 "  This application sets the following channel variable upon completion:\n"
00256 "     UPQMSTATUS       The status of the attempt to unpause a queue \n"
00257 "                      member as a text string, one of\n"
00258 "            UNPAUSED | NOTFOUND\n"
00259 "Example: UnpauseQueueMember(|SIP/3000)\n";
00260 
00261 static char *app_ql = "QueueLog" ;
00262 static char *app_ql_synopsis = "Writes to the queue_log" ;
00263 static char *app_ql_descrip =
00264 "   QueueLog(queuename|uniqueid|agent|event[|additionalinfo]):\n"
00265 "Allows you to write your own events into the queue log\n"
00266 "Example: QueueLog(101|${UNIQUEID}|${AGENT}|WENTONBREAK|600)\n";
00267 
00268 /*! \brief Persistent Members astdb family */
00269 static const char *pm_family = "Queue/PersistentMembers";
00270 /* The maximum length of each persistent member queue database entry */
00271 #define PM_MAX_LEN 8192
00272 
00273 /*! \brief queues.conf [general] option */
00274 static int queue_persistent_members = 0;
00275 
00276 /*! \brief queues.conf per-queue weight option */
00277 static int use_weight = 0;
00278 
00279 /*! \brief queues.conf [general] option */
00280 static int autofill_default = 0;
00281 
00282 /*! \brief queues.conf [general] option */
00283 static int montype_default = 0;
00284 
00285 enum queue_result {
00286    QUEUE_UNKNOWN = 0,
00287    QUEUE_TIMEOUT = 1,
00288    QUEUE_JOINEMPTY = 2,
00289    QUEUE_LEAVEEMPTY = 3,
00290    QUEUE_JOINUNAVAIL = 4,
00291    QUEUE_LEAVEUNAVAIL = 5,
00292    QUEUE_FULL = 6,
00293 };
00294 
00295 const struct {
00296    enum queue_result id;
00297    char *text;
00298 } queue_results[] = {
00299    { QUEUE_UNKNOWN, "UNKNOWN" },
00300    { QUEUE_TIMEOUT, "TIMEOUT" },
00301    { QUEUE_JOINEMPTY,"JOINEMPTY" },
00302    { QUEUE_LEAVEEMPTY, "LEAVEEMPTY" },
00303    { QUEUE_JOINUNAVAIL, "JOINUNAVAIL" },
00304    { QUEUE_LEAVEUNAVAIL, "LEAVEUNAVAIL" },
00305    { QUEUE_FULL, "FULL" },
00306 };
00307 
00308 /*! \brief We define a custom "local user" structure because we
00309    use it not only for keeping track of what is in use but
00310    also for keeping track of who we're dialing.
00311 
00312    There are two "links" defined in this structure, q_next and call_next.
00313    q_next links ALL defined callattempt structures into a linked list. call_next is
00314    a link which allows for a subset of the callattempts to be traversed. This subset
00315    is used in wait_for_answer so that irrelevant callattempts are not traversed. This
00316    also is helpful so that queue logs are always accurate in the case where a call to 
00317    a member times out, especially if using the ringall strategy. */
00318 
00319 struct callattempt {
00320    struct callattempt *q_next;
00321    struct callattempt *call_next;
00322    struct ast_channel *chan;
00323    char interface[256];
00324    int stillgoing;
00325    int metric;
00326    int oldstatus;
00327    time_t lastcall;
00328    struct member *member;
00329 };
00330 
00331 
00332 struct queue_ent {
00333    struct call_queue *parent;          /*!< What queue is our parent */
00334    char moh[80];                       /*!< Name of musiconhold to be used */
00335    char announce[80];                  /*!< Announcement to play for member when call is answered */
00336    char context[AST_MAX_CONTEXT];      /*!< Context when user exits queue */
00337    char digits[AST_MAX_EXTENSION];     /*!< Digits entered while in queue */
00338    int valid_digits;        /*!< Digits entered correspond to valid extension. Exited */
00339    int pos;                            /*!< Where we are in the queue */
00340    int prio;                           /*!< Our priority */
00341    int last_pos_said;                  /*!< Last position we told the user */
00342    time_t last_periodic_announce_time; /*!< The last time we played a periodic announcement */
00343    int last_periodic_announce_sound;   /*!< The last periodic announcement we made */
00344    time_t last_pos;                    /*!< Last time we told the user their position */
00345    int opos;                           /*!< Where we started in the queue */
00346    int handled;                        /*!< Whether our call was handled */
00347    int pending;                        /*!< Non-zero if we are attempting to call a member */
00348    int max_penalty;                    /*!< Limit the members that can take this call to this penalty or lower */
00349    time_t start;                       /*!< When we started holding */
00350    time_t expire;                      /*!< When this entry should expire (time out of queue) */
00351    struct ast_channel *chan;           /*!< Our channel */
00352    struct queue_ent *next;             /*!< The next queue entry */
00353 };
00354 
00355 struct member {
00356    char interface[80];                 /*!< Technology/Location */
00357    char membername[80];                /*!< Member name to use in queue logs */
00358    int penalty;                        /*!< Are we a last resort? */
00359    int calls;                          /*!< Number of calls serviced by this member */
00360    int dynamic;                        /*!< Are we dynamically added? */
00361    int realtime;                       /*!< Is this member realtime? */
00362    int status;                         /*!< Status of queue member */
00363    int paused;                         /*!< Are we paused (not accepting calls)? */
00364    time_t lastcall;                    /*!< When last successful call was hungup */
00365    unsigned int dead:1;                /*!< Used to detect members deleted in realtime */
00366    unsigned int delme:1;               /*!< Flag to delete entry on reload */
00367 };
00368 
00369 struct member_interface {
00370    char interface[80];
00371    AST_LIST_ENTRY(member_interface) list;    /*!< Next call queue */
00372 };
00373 
00374 static AST_LIST_HEAD_STATIC(interfaces, member_interface);
00375 
00376 /* values used in multi-bit flags in call_queue */
00377 #define QUEUE_EMPTY_NORMAL 1
00378 #define QUEUE_EMPTY_STRICT 2
00379 #define ANNOUNCEHOLDTIME_ALWAYS 1
00380 #define ANNOUNCEHOLDTIME_ONCE 2
00381 #define QUEUE_EVENT_VARIABLES 3
00382 
00383 struct call_queue {
00384    ast_mutex_t lock; 
00385    char name[80];                      /*!< Name */
00386    char moh[80];                       /*!< Music On Hold class to be used */
00387    char announce[80];                  /*!< Announcement to play when call is answered */
00388    char context[AST_MAX_CONTEXT];      /*!< Exit context */
00389    unsigned int monjoin:1;
00390    unsigned int dead:1;
00391    unsigned int joinempty:2;
00392    unsigned int eventwhencalled:2;
00393    unsigned int leavewhenempty:2;
00394    unsigned int ringinuse:1;
00395    unsigned int setinterfacevar:1;
00396    unsigned int reportholdtime:1;
00397    unsigned int wrapped:1;
00398    unsigned int timeoutrestart:1;
00399    unsigned int announceholdtime:2;
00400    int strategy:4;
00401    unsigned int maskmemberstatus:1;
00402    unsigned int realtime:1;
00403    unsigned int found:1;
00404    int announcefrequency;              /*!< How often to announce their position */
00405    int periodicannouncefrequency;      /*!< How often to play periodic announcement */
00406    int roundingseconds;                /*!< How many seconds do we round to? */
00407    int holdtime;                       /*!< Current avg holdtime, based on an exponential average */
00408    int callscompleted;                 /*!< Number of queue calls completed */
00409    int callsabandoned;                 /*!< Number of queue calls abandoned */
00410    int servicelevel;                   /*!< seconds setting for servicelevel*/
00411    int callscompletedinsl;             /*!< Number of calls answered with servicelevel*/
00412    char monfmt[8];                     /*!< Format to use when recording calls */
00413    int montype;                        /*!< Monitor type  Monitor vs. MixMonitor */
00414    char sound_next[80];                /*!< Sound file: "Your call is now first in line" (def. queue-youarenext) */
00415    char sound_thereare[80];            /*!< Sound file: "There are currently" (def. queue-thereare) */
00416    char sound_calls[80];               /*!< Sound file: "calls waiting to speak to a representative." (def. queue-callswaiting)*/
00417    char sound_holdtime[80];            /*!< Sound file: "The current estimated total holdtime is" (def. queue-holdtime) */
00418    char sound_minutes[80];             /*!< Sound file: "minutes." (def. queue-minutes) */
00419    char sound_lessthan[80];            /*!< Sound file: "less-than" (def. queue-lessthan) */
00420    char sound_seconds[80];             /*!< Sound file: "seconds." (def. queue-seconds) */
00421    char sound_thanks[80];              /*!< Sound file: "Thank you for your patience." (def. queue-thankyou) */
00422    char sound_reporthold[80];          /*!< Sound file: "Hold time" (def. queue-reporthold) */
00423    char sound_periodicannounce[MAX_PERIODIC_ANNOUNCEMENTS][80];/*!< Sound files: Custom announce, no default */
00424 
00425    int count;                          /*!< How many entries */
00426    int maxlen;                         /*!< Max number of entries */
00427    int wrapuptime;                     /*!< Wrapup Time */
00428 
00429    int retry;                          /*!< Retry calling everyone after this amount of time */
00430    int timeout;                        /*!< How long to wait for an answer */
00431    int weight;                         /*!< Respective weight */
00432    int autopause;                      /*!< Auto pause queue members if they fail to answer */
00433 
00434    /* Queue strategy things */
00435    int rrpos;                          /*!< Round Robin - position */
00436    int memberdelay;                    /*!< Seconds to delay connecting member to caller */
00437    int autofill;                       /*!< Ignore the head call status and ring an available agent */
00438    
00439    struct ao2_container *members;             /*!< Head of the list of members */
00440    /*! 
00441     * \brief Number of members _logged in_
00442     * \note There will be members in the members container that are not logged
00443     *       in, so this can not simply be replaced with ao2_container_count(). 
00444     */
00445    int membercount;
00446    struct queue_ent *head;             /*!< Head of the list of callers */
00447    AST_LIST_ENTRY(call_queue) list;    /*!< Next call queue */
00448 };
00449 
00450 static AST_LIST_HEAD_STATIC(queues, call_queue);
00451 
00452 static int set_member_paused(const char *queuename, const char *interface, int paused);
00453 
00454 static void queue_transfer_fixup(void *data, struct ast_channel *old_chan, struct ast_channel *new_chan); 
00455 
00456 static void rr_dep_warning(void)
00457 {
00458    static unsigned int warned = 0;
00459 
00460    if (!warned) {
00461       ast_log(LOG_NOTICE, "The 'roundrobin' queue strategy is deprecated. Please use the 'rrmemory' strategy instead.\n");
00462       warned = 1;
00463    }
00464 }
00465 
00466 static void monjoin_dep_warning(void)
00467 {
00468    static unsigned int warned = 0;
00469    if (!warned) {
00470       ast_log(LOG_NOTICE, "The 'monitor-join' queue option is deprecated. Please use monitor-type=mixmonitor instead.\n");
00471       warned = 1;
00472    }
00473 }
00474 /*! \brief sets the QUEUESTATUS channel variable */
00475 static void set_queue_result(struct ast_channel *chan, enum queue_result res)
00476 {
00477    int i;
00478 
00479    for (i = 0; i < sizeof(queue_results) / sizeof(queue_results[0]); i++) {
00480       if (queue_results[i].id == res) {
00481          pbx_builtin_setvar_helper(chan, "QUEUESTATUS", queue_results[i].text);
00482          return;
00483       }
00484    }
00485 }
00486 
00487 static char *int2strat(int strategy)
00488 {
00489    int x;
00490 
00491    for (x = 0; x < sizeof(strategies) / sizeof(strategies[0]); x++) {
00492       if (strategy == strategies[x].strategy)
00493          return strategies[x].name;
00494    }
00495 
00496    return "<unknown>";
00497 }
00498 
00499 static int strat2int(const char *strategy)
00500 {
00501    int x;
00502 
00503    for (x = 0; x < sizeof(strategies) / sizeof(strategies[0]); x++) {
00504       if (!strcasecmp(strategy, strategies[x].name))
00505          return strategies[x].strategy;
00506    }
00507 
00508    return -1;
00509 }
00510 
00511 /*! \brief Insert the 'new' entry after the 'prev' entry of queue 'q' */
00512 static inline void insert_entry(struct call_queue *q, struct queue_ent *prev, struct queue_ent *new, int *pos)
00513 {
00514    struct queue_ent *cur;
00515 
00516    if (!q || !new)
00517       return;
00518    if (prev) {
00519       cur = prev->next;
00520       prev->next = new;
00521    } else {
00522       cur = q->head;
00523       q->head = new;
00524    }
00525    new->next = cur;
00526    new->parent = q;
00527    new->pos = ++(*pos);
00528    new->opos = *pos;
00529 }
00530 
00531 enum queue_member_status {
00532    QUEUE_NO_MEMBERS,
00533    QUEUE_NO_REACHABLE_MEMBERS,
00534    QUEUE_NORMAL
00535 };
00536 
00537 /*! \brief Check if members are available
00538  *
00539  * This function checks to see if members are available to be called. If any member
00540  * is available, the function immediately returns QUEUE_NORMAL. If no members are available,
00541  * the appropriate reason why is returned
00542  */
00543 static enum queue_member_status get_member_status(struct call_queue *q, int max_penalty)
00544 {
00545    struct member *member;
00546    struct ao2_iterator mem_iter;
00547    enum queue_member_status result = QUEUE_NO_MEMBERS;
00548 
00549    ast_mutex_lock(&q->lock);
00550    mem_iter = ao2_iterator_init(q->members, 0);
00551    while ((member = ao2_iterator_next(&mem_iter))) {
00552       if (max_penalty && (member->penalty > max_penalty)) {
00553          ao2_ref(member, -1);
00554          continue;
00555       }
00556 
00557       if (member->paused) {
00558          ao2_ref(member, -1);
00559          continue;
00560       }
00561 
00562       switch (member->status) {
00563       case AST_DEVICE_INVALID:
00564          /* nothing to do */
00565          ao2_ref(member, -1);
00566          break;
00567       case AST_DEVICE_UNAVAILABLE:
00568          result = QUEUE_NO_REACHABLE_MEMBERS;
00569          ao2_ref(member, -1);
00570          break;
00571       default:
00572          ast_mutex_unlock(&q->lock);
00573          ao2_ref(member, -1);
00574          return QUEUE_NORMAL;
00575       }
00576    }
00577 
00578    ast_mutex_unlock(&q->lock);
00579    return result;
00580 }
00581 
00582 struct statechange {
00583    AST_LIST_ENTRY(statechange) entry;
00584    int state;
00585    char dev[0];
00586 };
00587 
00588 static int update_status(const char *interface, const int status)
00589 {
00590    struct member *cur;
00591    struct ao2_iterator mem_iter;
00592    struct call_queue *q;
00593 
00594    AST_LIST_LOCK(&queues);
00595    AST_LIST_TRAVERSE(&queues, q, list) {
00596       ast_mutex_lock(&q->lock);
00597       mem_iter = ao2_iterator_init(q->members, 0);
00598       while ((cur = ao2_iterator_next(&mem_iter))) {
00599          char *tmp_interface;
00600          char *slash_pos;
00601          tmp_interface = ast_strdupa(cur->interface);
00602          if ((slash_pos = strchr(tmp_interface, '/')))
00603             if ((slash_pos = strchr(slash_pos + 1, '/')))
00604                *slash_pos = '\0';
00605 
00606          if (strcasecmp(interface, tmp_interface)) {
00607             ao2_ref(cur, -1);
00608             continue;
00609          }
00610 
00611          if (cur->status != status) {
00612             cur->status = status;
00613             if (q->maskmemberstatus) {
00614                ao2_ref(cur, -1);
00615                continue;
00616             }
00617 
00618             manager_event(EVENT_FLAG_AGENT, "QueueMemberStatus",
00619                "Queue: %s\r\n"
00620                "Location: %s\r\n"
00621                "MemberName: %s\r\n"
00622                "Membership: %s\r\n"
00623                "Penalty: %d\r\n"
00624                "CallsTaken: %d\r\n"
00625                "LastCall: %d\r\n"
00626                "Status: %d\r\n"
00627                "Paused: %d\r\n",
00628                q->name, cur->interface, cur->membername, cur->dynamic ? "dynamic" : cur->realtime ? "realtime" : "static",
00629                cur->penalty, cur->calls, (int)cur->lastcall, cur->status, cur->paused);
00630          }
00631          ao2_ref(cur, -1);
00632       }
00633       ast_mutex_unlock(&q->lock);
00634    }
00635    AST_LIST_UNLOCK(&queues);
00636 
00637    return 0;
00638 }
00639 
00640 /*! \brief set a member's status based on device state of that member's interface*/
00641 static void *handle_statechange(struct statechange *sc)
00642 {
00643    struct member_interface *curint;
00644    char *loc;
00645    char *technology;
00646 
00647    technology = ast_strdupa(sc->dev);
00648    loc = strchr(technology, '/');
00649    if (loc) {
00650       *loc++ = '\0';
00651    } else {
00652       return NULL;
00653    }
00654 
00655    AST_LIST_LOCK(&interfaces);
00656    AST_LIST_TRAVERSE(&interfaces, curint, list) {
00657       char *interface;
00658       char *slash_pos;
00659       interface = ast_strdupa(curint->interface);
00660       if ((slash_pos = strchr(interface, '/')))
00661          if ((slash_pos = strchr(slash_pos + 1, '/')))
00662             *slash_pos = '\0';
00663 
00664       if (!strcasecmp(interface, sc->dev))
00665          break;
00666    }
00667    AST_LIST_UNLOCK(&interfaces);
00668 
00669    if (!curint) {
00670       if (option_debug > 2)
00671          ast_log(LOG_DEBUG, "Device '%s/%s' changed to state '%d' (%s) but we don't care because they're not a member of any queue.\n", technology, loc, sc->state, devstate2str(sc->state));
00672       return NULL;
00673    }
00674 
00675    if (option_debug)
00676       ast_log(LOG_DEBUG, "Device '%s/%s' changed to state '%d' (%s)\n", technology, loc, sc->state, devstate2str(sc->state));
00677 
00678    update_status(sc->dev, sc->state);
00679 
00680    return NULL;
00681 }
00682 
00683 /*!
00684  * \brief Data used by the device state thread
00685  */
00686 static struct {
00687    /*! Set to 1 to stop the thread */
00688    unsigned int stop:1;
00689    /*! The device state monitoring thread */
00690    pthread_t thread;
00691    /*! Lock for the state change queue */
00692    ast_mutex_t lock;
00693    /*! Condition for the state change queue */
00694    ast_cond_t cond;
00695    /*! Queue of state changes */
00696    AST_LIST_HEAD_NOLOCK(, statechange) state_change_q;
00697 } device_state = {
00698    .thread = AST_PTHREADT_NULL,
00699 };
00700 
00701 /*! \brief Consumer of the statechange queue */
00702 static void *device_state_thread(void *data)
00703 {
00704    struct statechange *sc = NULL;
00705 
00706    while (!device_state.stop) {
00707       ast_mutex_lock(&device_state.lock);
00708       if (!(sc = AST_LIST_REMOVE_HEAD(&device_state.state_change_q, entry))) {
00709          ast_cond_wait(&device_state.cond, &device_state.lock);
00710          sc = AST_LIST_REMOVE_HEAD(&device_state.state_change_q, entry);
00711       }
00712       ast_mutex_unlock(&device_state.lock);
00713 
00714       /* Check to see if we were woken up to see the request to stop */
00715       if (device_state.stop)
00716          break;
00717 
00718       if (!sc)
00719          continue;
00720 
00721       handle_statechange(sc);
00722 
00723       free(sc);
00724       sc = NULL;
00725    }
00726 
00727    if (sc)
00728       free(sc);
00729 
00730    while ((sc = AST_LIST_REMOVE_HEAD(&device_state.state_change_q, entry)))
00731       free(sc);
00732 
00733    return NULL;
00734 }
00735 /*! \brief Producer of the statechange queue */
00736 static int statechange_queue(const char *dev, int state, void *ign)
00737 {
00738    struct statechange *sc;
00739 
00740    if (!(sc = ast_calloc(1, sizeof(*sc) + strlen(dev) + 1)))
00741       return 0;
00742 
00743    sc->state = state;
00744    strcpy(sc->dev, dev);
00745 
00746    ast_mutex_lock(&device_state.lock);
00747    AST_LIST_INSERT_TAIL(&device_state.state_change_q, sc, entry);
00748    ast_cond_signal(&device_state.cond);
00749    ast_mutex_unlock(&device_state.lock);
00750 
00751    return 0;
00752 }
00753 /*! \brief allocate space for new queue member and set fields based on parameters passed */
00754 static struct member *create_queue_member(const char *interface, const char *membername, int penalty, int paused)
00755 {
00756    struct member *cur;
00757    
00758    if ((cur = ao2_alloc(sizeof(*cur), NULL))) {
00759       cur->penalty = penalty;
00760       cur->paused = paused;
00761       ast_copy_string(cur->interface, interface, sizeof(cur->interface));
00762       if (!ast_strlen_zero(membername))
00763          ast_copy_string(cur->membername, membername, sizeof(cur->membername));
00764       else
00765          ast_copy_string(cur->membername, interface, sizeof(cur->membername));
00766       if (!strchr(cur->interface, '/'))
00767          ast_log(LOG_WARNING, "No location at interface '%s'\n", interface);
00768       cur->status = ast_device_state(interface);
00769    }
00770 
00771    return cur;
00772 }
00773 
00774 static struct call_queue *alloc_queue(const char *queuename)
00775 {
00776    struct call_queue *q;
00777 
00778    if ((q = ast_calloc(1, sizeof(*q)))) {
00779       ast_mutex_init(&q->lock);
00780       ast_copy_string(q->name, queuename, sizeof(q->name));
00781    }
00782    return q;
00783 }
00784 
00785 static int compress_char(const char c)
00786 {
00787    if (c < 32)
00788       return 0;
00789    else if (c > 96)
00790       return c - 64;
00791    else
00792       return c - 32;
00793 }
00794 
00795 static int member_hash_fn(const void *obj, const int flags)
00796 {
00797    const struct member *mem = obj;
00798    const char *chname = strchr(mem->interface, '/');
00799    int ret = 0, i;
00800    if (!chname)
00801       chname = mem->interface;
00802    for (i = 0; i < 5 && chname[i]; i++)
00803       ret += compress_char(chname[i]) << (i * 6);
00804    return ret;
00805 }
00806 
00807 static int member_cmp_fn(void *obj1, void *obj2, int flags)
00808 {
00809    struct member *mem1 = obj1, *mem2 = obj2;
00810    return strcmp(mem1->interface, mem2->interface) ? 0 : CMP_MATCH | CMP_STOP;
00811 }
00812 
00813 static void init_queue(struct call_queue *q)
00814 {
00815    int i;
00816 
00817    q->dead = 0;
00818    q->retry = DEFAULT_RETRY;
00819    q->timeout = -1;
00820    q->maxlen = 0;
00821    q->announcefrequency = 0;
00822    q->announceholdtime = 0;
00823    q->roundingseconds = 0; /* Default - don't announce seconds */
00824    q->servicelevel = 0;
00825    q->ringinuse = 1;
00826    q->setinterfacevar = 0;
00827    q->autofill = autofill_default;
00828    q->montype = montype_default;
00829    q->moh[0] = '\0';
00830    q->announce[0] = '\0';
00831    q->context[0] = '\0';
00832    q->monfmt[0] = '\0';
00833    q->periodicannouncefrequency = 0;
00834    q->reportholdtime = 0;
00835    q->monjoin = 0;
00836    q->wrapuptime = 0;
00837    q->joinempty = 0;
00838    q->leavewhenempty = 0;
00839    q->memberdelay = 0;
00840    q->maskmemberstatus = 0;
00841    q->eventwhencalled = 0;
00842    q->weight = 0;
00843    q->timeoutrestart = 0;
00844    if (!q->members)
00845       q->members = ao2_container_alloc(37, member_hash_fn, member_cmp_fn);
00846    q->membercount = 0;
00847    q->found = 1;
00848    ast_copy_string(q->sound_next, "queue-youarenext", sizeof(q->sound_next));
00849    ast_copy_string(q->sound_thereare, "queue-thereare", sizeof(q->sound_thereare));
00850    ast_copy_string(q->sound_calls, "queue-callswaiting", sizeof(q->sound_calls));
00851    ast_copy_string(q->sound_holdtime, "queue-holdtime", sizeof(q->sound_holdtime));
00852    ast_copy_string(q->sound_minutes, "queue-minutes", sizeof(q->sound_minutes));
00853    ast_copy_string(q->sound_seconds, "queue-seconds", sizeof(q->sound_seconds));
00854    ast_copy_string(q->sound_thanks, "queue-thankyou", sizeof(q->sound_thanks));
00855    ast_copy_string(q->sound_lessthan, "queue-less-than", sizeof(q->sound_lessthan));
00856    ast_copy_string(q->sound_reporthold, "queue-reporthold", sizeof(q->sound_reporthold));
00857    ast_copy_string(q->sound_periodicannounce[0], "queue-periodic-announce", sizeof(q->sound_periodicannounce[0]));
00858    for (i = 1; i < MAX_PERIODIC_ANNOUNCEMENTS; i++) {
00859       q->sound_periodicannounce[i][0]='\0';
00860    }
00861 }
00862 
00863 static void clear_queue(struct call_queue *q)
00864 {
00865    q->holdtime = 0;
00866    q->callscompleted = 0;
00867    q->callsabandoned = 0;
00868    q->callscompletedinsl = 0;
00869    q->wrapuptime = 0;
00870 }
00871 
00872 static int add_to_interfaces(const char *interface)
00873 {
00874    struct member_interface *curint;
00875 
00876    AST_LIST_LOCK(&interfaces);
00877    AST_LIST_TRAVERSE(&interfaces, curint, list) {
00878       if (!strcasecmp(curint->interface, interface))
00879          break;
00880    }
00881 
00882    if (curint) {
00883       AST_LIST_UNLOCK(&interfaces);
00884       return 0;
00885    }
00886 
00887    if (option_debug)
00888       ast_log(LOG_DEBUG, "Adding %s to the list of interfaces that make up all of our queue members.\n", interface);
00889    
00890    if ((curint = ast_calloc(1, sizeof(*curint)))) {
00891       ast_copy_string(curint->interface, interface, sizeof(curint->interface));
00892       AST_LIST_INSERT_HEAD(&interfaces, curint, list);
00893    }
00894    AST_LIST_UNLOCK(&interfaces);
00895 
00896    return 0;
00897 }
00898 
00899 static int interface_exists_global(const char *interface)
00900 {
00901    struct call_queue *q;
00902    struct member *mem, tmpmem;
00903    int ret = 0;
00904 
00905    ast_copy_string(tmpmem.interface, interface, sizeof(tmpmem.interface));
00906 
00907    AST_LIST_LOCK(&queues);
00908    AST_LIST_TRAVERSE(&queues, q, list) {
00909       ast_mutex_lock(&q->lock);
00910       if ((mem = ao2_find(q->members, &tmpmem, OBJ_POINTER))) {
00911          ao2_ref(mem, -1);
00912          ret = 1;
00913       }
00914       ast_mutex_unlock(&q->lock);
00915       if (ret)
00916          break;
00917    }
00918    AST_LIST_UNLOCK(&queues);
00919 
00920    return ret;
00921 }
00922 
00923 static int remove_from_interfaces(const char *interface)
00924 {
00925    struct member_interface *curint;
00926 
00927    if (interface_exists_global(interface))
00928       return 0;
00929 
00930    AST_LIST_LOCK(&interfaces);
00931    AST_LIST_TRAVERSE_SAFE_BEGIN(&interfaces, curint, list) {
00932       if (!strcasecmp(curint->interface, interface)) {
00933          if (option_debug)
00934             ast_log(LOG_DEBUG, "Removing %s from the list of interfaces that make up all of our queue members.\n", interface);
00935          AST_LIST_REMOVE_CURRENT(&interfaces, list);
00936          free(curint);
00937          break;
00938       }
00939    }
00940    AST_LIST_TRAVERSE_SAFE_END;
00941    AST_LIST_UNLOCK(&interfaces);
00942 
00943    return 0;
00944 }
00945 
00946 static void clear_and_free_interfaces(void)
00947 {
00948    struct member_interface *curint;
00949 
00950    AST_LIST_LOCK(&interfaces);
00951    while ((curint = AST_LIST_REMOVE_HEAD(&interfaces, list)))
00952       free(curint);
00953    AST_LIST_UNLOCK(&interfaces);
00954 }
00955 
00956 /*! \brief Configure a queue parameter.
00957 \par
00958    For error reporting, line number is passed for .conf static configuration.
00959    For Realtime queues, linenum is -1.
00960    The failunknown flag is set for config files (and static realtime) to show
00961    errors for unknown parameters. It is cleared for dynamic realtime to allow
00962    extra fields in the tables. */
00963 static void queue_set_param(struct call_queue *q, const char *param, const char *val, int linenum, int failunknown)
00964 {
00965    if (!strcasecmp(param, "musicclass") || 
00966       !strcasecmp(param, "music") || !strcasecmp(param, "musiconhold")) {
00967       ast_copy_string(q->moh, val, sizeof(q->moh));
00968    } else if (!strcasecmp(param, "announce")) {
00969       ast_copy_string(q->announce, val, sizeof(q->announce));
00970    } else if (!strcasecmp(param, "context")) {
00971       ast_copy_string(q->context, val, sizeof(q->context));
00972    } else if (!strcasecmp(param, "timeout")) {
00973       q->timeout = atoi(val);
00974       if (q->timeout < 0)
00975          q->timeout = DEFAULT_TIMEOUT;
00976    } else if (!strcasecmp(param, "ringinuse")) {
00977       q->ringinuse = ast_true(val);
00978    } else if (!strcasecmp(param, "setinterfacevar")) {
00979       q->setinterfacevar = ast_true(val);
00980    } else if (!strcasecmp(param, "monitor-join")) {
00981       monjoin_dep_warning();
00982       q->monjoin = ast_true(val);
00983    } else if (!strcasecmp(param, "monitor-format")) {
00984       ast_copy_string(q->monfmt, val, sizeof(q->monfmt));
00985    } else if (!strcasecmp(param, "queue-youarenext")) {
00986       ast_copy_string(q->sound_next, val, sizeof(q->sound_next));
00987    } else if (!strcasecmp(param, "queue-thereare")) {
00988       ast_copy_string(q->sound_thereare, val, sizeof(q->sound_thereare));
00989    } else if (!strcasecmp(param, "queue-callswaiting")) {
00990       ast_copy_string(q->sound_calls, val, sizeof(q->sound_calls));
00991    } else if (!strcasecmp(param, "queue-holdtime")) {
00992       ast_copy_string(q->sound_holdtime, val, sizeof(q->sound_holdtime));
00993    } else if (!strcasecmp(param, "queue-minutes")) {
00994       ast_copy_string(q->sound_minutes, val, sizeof(q->sound_minutes));
00995    } else if (!strcasecmp(param, "queue-seconds")) {
00996       ast_copy_string(q->sound_seconds, val, sizeof(q->sound_seconds));
00997    } else if (!strcasecmp(param, "queue-lessthan")) {
00998       ast_copy_string(q->sound_lessthan, val, sizeof(q->sound_lessthan));
00999    } else if (!strcasecmp(param, "queue-thankyou")) {
01000       ast_copy_string(q->sound_thanks, val, sizeof(q->sound_thanks));
01001    } else if (!strcasecmp(param, "queue-reporthold")) {
01002       ast_copy_string(q->sound_reporthold, val, sizeof(q->sound_reporthold));
01003    } else if (!strcasecmp(param, "announce-frequency")) {
01004       q->announcefrequency = atoi(val);
01005    } else if (!strcasecmp(param, "announce-round-seconds")) {
01006       q->roundingseconds = atoi(val);
01007       if (q->roundingseconds>60 || q->roundingseconds<0) {
01008          if (linenum >= 0) {
01009             ast_log(LOG_WARNING, "'%s' isn't a valid value for %s "
01010                "using 0 instead for queue '%s' at line %d of queues.conf\n",
01011                val, param, q->name, linenum);
01012          } else {
01013             ast_log(LOG_WARNING, "'%s' isn't a valid value for %s "
01014                "using 0 instead for queue '%s'\n", val, param, q->name);
01015          }
01016          q->roundingseconds=0;
01017       }
01018    } else if (!strcasecmp(param, "announce-holdtime")) {
01019       if (!strcasecmp(val, "once"))
01020          q->announceholdtime = ANNOUNCEHOLDTIME_ONCE;
01021       else if (ast_true(val))
01022          q->announceholdtime = ANNOUNCEHOLDTIME_ALWAYS;
01023       else
01024          q->announceholdtime = 0;
01025    } else if (!strcasecmp(param, "periodic-announce")) {
01026       if (strchr(val, '|')) {
01027          char *s, *buf = ast_strdupa(val);
01028          unsigned int i = 0;
01029 
01030          while ((s = strsep(&buf, "|"))) {
01031             ast_copy_string(q->sound_periodicannounce[i], s, sizeof(q->sound_periodicannounce[i]));
01032             i++;
01033             if (i == MAX_PERIODIC_ANNOUNCEMENTS)
01034                break;
01035          }
01036       } else {
01037          ast_copy_string(q->sound_periodicannounce[0], val, sizeof(q->sound_periodicannounce[0]));
01038       }
01039    } else if (!strcasecmp(param, "periodic-announce-frequency")) {
01040       q->periodicannouncefrequency = atoi(val);
01041    } else if (!strcasecmp(param, "retry")) {
01042       q->retry = atoi(val);
01043       if (q->retry <= 0)
01044          q->retry = DEFAULT_RETRY;
01045    } else if (!strcasecmp(param, "wrapuptime")) {
01046       q->wrapuptime = atoi(val);
01047    } else if (!strcasecmp(param, "autofill")) {
01048       q->autofill = ast_true(val);
01049    } else if (!strcasecmp(param, "monitor-type")) {
01050       if (!strcasecmp(val, "mixmonitor"))
01051          q->montype = 1;
01052    } else if (!strcasecmp(param, "autopause")) {
01053       q->autopause = ast_true(val);
01054    } else if (!strcasecmp(param, "maxlen")) {
01055       q->maxlen = atoi(val);
01056       if (q->maxlen < 0)
01057          q->maxlen = 0;
01058    } else if (!strcasecmp(param, "servicelevel")) {
01059       q->servicelevel= atoi(val);
01060    } else if (!strcasecmp(param, "strategy")) {
01061       q->strategy = strat2int(val);
01062       if (q->strategy < 0) {
01063          ast_log(LOG_WARNING, "'%s' isn't a valid strategy for queue '%s', using ringall instead\n",
01064             val, q->name);
01065          q->strategy = QUEUE_STRATEGY_RINGALL;
01066       }
01067    } else if (!strcasecmp(param, "joinempty")) {
01068       if (!strcasecmp(val, "strict"))
01069          q->joinempty = QUEUE_EMPTY_STRICT;
01070       else if (ast_true(val))
01071          q->joinempty = QUEUE_EMPTY_NORMAL;
01072       else
01073          q->joinempty = 0;
01074    } else if (!strcasecmp(param, "leavewhenempty")) {
01075       if (!strcasecmp(val, "strict"))
01076          q->leavewhenempty = QUEUE_EMPTY_STRICT;
01077       else if (ast_true(val))
01078          q->leavewhenempty = QUEUE_EMPTY_NORMAL;
01079       else
01080          q->leavewhenempty = 0;
01081    } else if (!strcasecmp(param, "eventmemberstatus")) {
01082       q->maskmemberstatus = !ast_true(val);
01083    } else if (!strcasecmp(param, "eventwhencalled")) {
01084       if (!strcasecmp(val, "vars")) {
01085          q->eventwhencalled = QUEUE_EVENT_VARIABLES;
01086       } else {
01087          q->eventwhencalled = ast_true(val) ? 1 : 0;
01088       }
01089    } else if (!strcasecmp(param, "reportholdtime")) {
01090       q->reportholdtime = ast_true(val);
01091    } else if (!strcasecmp(param, "memberdelay")) {
01092       q->memberdelay = atoi(val);
01093    } else if (!strcasecmp(param, "weight")) {
01094       q->weight = atoi(val);
01095       if (q->weight)
01096          use_weight++;
01097       /* With Realtime queues, if the last queue using weights is deleted in realtime,
01098          we will not see any effect on use_weight until next reload. */
01099    } else if (!strcasecmp(param, "timeoutrestart")) {
01100       q->timeoutrestart = ast_true(val);
01101    } else if (failunknown) {
01102       if (linenum >= 0) {
01103          ast_log(LOG_WARNING, "Unknown keyword in queue '%s': %s at line %d of queues.conf\n",
01104             q->name, param, linenum);
01105       } else {
01106          ast_log(LOG_WARNING, "Unknown keyword in queue '%s': %s\n", q->name, param);
01107       }
01108    }
01109 }
01110 
01111 static void rt_handle_member_record(struct call_queue *q, char *interface, const char *membername, const char *penalty_str, const char *paused_str)
01112 {
01113    struct member *m, tmpmem;
01114    int penalty = 0;
01115    int paused  = 0;
01116 
01117    if (penalty_str) {
01118       penalty = atoi(penalty_str);
01119       if (penalty < 0)
01120          penalty = 0;
01121    }
01122 
01123    if (paused_str) {
01124       paused = atoi(paused_str);
01125       if (paused < 0)
01126          paused = 0;
01127    }
01128 
01129    /* Find the member, or the place to put a new one. */
01130    ast_copy_string(tmpmem.interface, interface, sizeof(tmpmem.interface));
01131    m = ao2_find(q->members, &tmpmem, OBJ_POINTER);
01132 
01133    /* Create a new one if not found, else update penalty */
01134    if (!m) {
01135       if ((m = create_queue_member(interface, membername, penalty, paused))) {
01136          m->dead = 0;
01137          m->realtime = 1;
01138          add_to_interfaces(interface);
01139          ao2_link(q->members, m);
01140          ao2_ref(m, -1);
01141          m = NULL;
01142          q->membercount++;
01143       }
01144    } else {
01145       m->dead = 0;   /* Do not delete this one. */
01146       if (paused_str)
01147          m->paused = paused;
01148       m->penalty = penalty;
01149       ao2_ref(m, -1);
01150    }
01151 }
01152 
01153 static void free_members(struct call_queue *q, int all)
01154 {
01155    /* Free non-dynamic members */
01156    struct member *cur;
01157    struct ao2_iterator mem_iter = ao2_iterator_init(q->members, 0);
01158 
01159    while ((cur = ao2_iterator_next(&mem_iter))) {
01160       if (all || !cur->dynamic) {
01161          ao2_unlink(q->members, cur);
01162          remove_from_interfaces(cur->interface);
01163          q->membercount--;
01164       }
01165       ao2_ref(cur, -1);
01166    }
01167 }
01168 
01169 static void destroy_queue(struct call_queue *q)
01170 {
01171    free_members(q, 1);
01172    ast_mutex_destroy(&q->lock);
01173    ao2_ref(q->members, -1);
01174    free(q);
01175 }
01176 
01177 /*!\brief Reload a single queue via realtime.
01178    \return Return the queue, or NULL if it doesn't exist.
01179    \note Should be called with the global qlock locked. */
01180 static struct call_queue *find_queue_by_name_rt(const char *queuename, struct ast_variable *queue_vars, struct ast_config *member_config)
01181 {
01182    struct ast_variable *v;
01183    struct call_queue *q;
01184    struct member *m;
01185    struct ao2_iterator mem_iter;
01186    char *interface = NULL;
01187    char *tmp, *tmp_name;
01188    char tmpbuf[64];  /* Must be longer than the longest queue param name. */
01189 
01190    /* Find the queue in the in-core list (we will create a new one if not found). */
01191    AST_LIST_TRAVERSE(&queues, q, list) {
01192       if (!strcasecmp(q->name, queuename))
01193          break;
01194    }
01195 
01196    /* Static queues override realtime. */
01197    if (q) {
01198       ast_mutex_lock(&q->lock);
01199       if (!q->realtime) {
01200          if (q->dead) {
01201             ast_mutex_unlock(&q->lock);
01202             return NULL;
01203          } else {
01204             ast_log(LOG_WARNING, "Static queue '%s' already exists. Not loading from realtime\n", q->name);
01205             ast_mutex_unlock(&q->lock);
01206             return q;
01207          }
01208       }
01209    } else if (!member_config)
01210       /* Not found in the list, and it's not realtime ... */
01211       return NULL;
01212 
01213    /* Check if queue is defined in realtime. */
01214    if (!queue_vars) {
01215       /* Delete queue from in-core list if it has been deleted in realtime. */
01216       if (q) {
01217          /*! \note Hmm, can't seem to distinguish a DB failure from a not
01218             found condition... So we might delete an in-core queue
01219             in case of DB failure. */
01220          ast_log(LOG_DEBUG, "Queue %s not found in realtime.\n", queuename);
01221 
01222          q->dead = 1;
01223          /* Delete if unused (else will be deleted when last caller leaves). */
01224          if (!q->count) {
01225             /* Delete. */
01226             AST_LIST_REMOVE(&queues, q, list);
01227             ast_mutex_unlock(&q->lock);
01228             destroy_queue(q);
01229          } else
01230             ast_mutex_unlock(&q->lock);
01231       }
01232       return NULL;
01233    }
01234 
01235    /* Create a new queue if an in-core entry does not exist yet. */
01236    if (!q) {
01237       if (!(q = alloc_queue(queuename)))
01238          return NULL;
01239       ast_mutex_lock(&q->lock);
01240       clear_queue(q);
01241       q->realtime = 1;
01242       AST_LIST_INSERT_HEAD(&queues, q, list);
01243    }
01244    init_queue(q);    /* Ensure defaults for all parameters not set explicitly. */
01245 
01246    memset(tmpbuf, 0, sizeof(tmpbuf));
01247    for (v = queue_vars; v; v = v->next) {
01248       /* Convert to dashes `-' from underscores `_' as the latter are more SQL friendly. */
01249       if ((tmp = strchr(v->name, '_'))) {
01250          ast_copy_string(tmpbuf, v->name, sizeof(tmpbuf));
01251          tmp_name = tmpbuf;
01252          tmp = tmp_name;
01253          while ((tmp = strchr(tmp, '_')))
01254             *tmp++ = '-';
01255       } else
01256          tmp_name = v->name;
01257 
01258       if (!ast_strlen_zero(v->value)) {
01259          /* Don't want to try to set the option if the value is empty */
01260          queue_set_param(q, tmp_name, v->value, -1, 0);
01261       }
01262    }
01263 
01264    if (q->strategy == QUEUE_STRATEGY_ROUNDROBIN)
01265       rr_dep_warning();
01266 
01267    /* Temporarily set realtime members dead so we can detect deleted ones. 
01268     * Also set the membercount correctly for realtime*/
01269    mem_iter = ao2_iterator_init(q->members, 0);
01270    while ((m = ao2_iterator_next(&mem_iter))) {
01271       q->membercount++;
01272       if (m->realtime)
01273          m->dead = 1;
01274       ao2_ref(m, -1);
01275    }
01276 
01277    while ((interface = ast_category_browse(member_config, interface))) {
01278       rt_handle_member_record(q, interface,
01279          ast_variable_retrieve(member_config, interface, "membername"),
01280          ast_variable_retrieve(member_config, interface, "penalty"),
01281          ast_variable_retrieve(member_config, interface, "paused"));
01282    }
01283 
01284    /* Delete all realtime members that have been deleted in DB. */
01285    mem_iter = ao2_iterator_init(q->members, 0);
01286    while ((m = ao2_iterator_next(&mem_iter))) {
01287       if (m->dead) {
01288          ao2_unlink(q->members, m);
01289          ast_mutex_unlock(&q->lock);
01290          remove_from_interfaces(m->interface);
01291          ast_mutex_lock(&q->lock);
01292          q->membercount--;
01293       }
01294       ao2_ref(m, -1);
01295    }
01296 
01297    ast_mutex_unlock(&q->lock);
01298 
01299    return q;
01300 }
01301 
01302 static int update_realtime_member_field(struct member *mem, const char *queue_name, const char *field, const char *value)
01303 {
01304    struct ast_variable *var, *save;
01305    int ret = -1;
01306 
01307    if (!(var = ast_load_realtime("queue_members", "interface", mem->interface, "queue_name", queue_name, NULL))) 
01308       return ret;
01309    save = var;
01310    while (var) {
01311       if (!strcmp(var->name, "uniqueid"))
01312          break;
01313       var = var->next;
01314    }
01315    if (var && !ast_strlen_zero(var->value)) {
01316       if ((ast_update_realtime("queue_members", "uniqueid", var->value, field, value, NULL)) > -1)
01317          ret = 0;
01318    }
01319    ast_variables_destroy(save);
01320    return ret;
01321 }
01322 
01323 static void update_realtime_members(struct call_queue *q)
01324 {
01325    struct ast_config *member_config = NULL;
01326    struct member *m;
01327    char *interface = NULL;
01328    struct ao2_iterator mem_iter;
01329 
01330    if (!(member_config = ast_load_realtime_multientry("queue_members", "interface LIKE", "%", "queue_name", q->name , NULL))) {
01331       /*This queue doesn't have realtime members*/
01332       if (option_debug > 2)
01333          ast_log(LOG_DEBUG, "Queue %s has no realtime members defined. No need for update\n", q->name);
01334       return;
01335    }
01336 
01337    ast_mutex_lock(&q->lock);
01338    
01339    /* Temporarily set realtime  members dead so we can detect deleted ones.*/ 
01340    mem_iter = ao2_iterator_init(q->members, 0);
01341    while ((m = ao2_iterator_next(&mem_iter))) {
01342       if (m->realtime)
01343          m->dead = 1;
01344       ao2_ref(m, -1);
01345    }
01346 
01347    while ((interface = ast_category_browse(member_config, interface))) {
01348       rt_handle_member_record(q, interface,
01349          S_OR(ast_variable_retrieve(member_config, interface, "membername"), interface),
01350          ast_variable_retrieve(member_config, interface, "penalty"),
01351          ast_variable_retrieve(member_config, interface, "paused"));
01352    }
01353 
01354    /* Delete all realtime members that have been deleted in DB. */
01355    mem_iter = ao2_iterator_init(q->members, 0);
01356    while ((m = ao2_iterator_next(&mem_iter))) {
01357       if (m->dead) {
01358          ao2_unlink(q->members, m);
01359          ast_mutex_unlock(&q->lock);
01360          remove_from_interfaces(m->interface);
01361          ast_mutex_lock(&q->lock);
01362          q->membercount--;
01363       }
01364       ao2_ref(m, -1);
01365    }
01366    ast_mutex_unlock(&q->lock);
01367    ast_config_destroy(member_config);
01368 }
01369 
01370 static struct call_queue *load_realtime_queue(const char *queuename)
01371 {
01372    struct ast_variable *queue_vars;
01373    struct ast_config *member_config = NULL;
01374    struct call_queue *q;
01375 
01376    /* Find the queue in the in-core list first. */
01377    AST_LIST_LOCK(&queues);
01378    AST_LIST_TRAVERSE(&queues, q, list) {
01379       if (!strcasecmp(q->name, queuename)) {
01380          break;
01381       }
01382    }
01383    AST_LIST_UNLOCK(&queues);
01384 
01385    if (!q || q->realtime) {
01386       /*! \note Load from realtime before taking the global qlock, to avoid blocking all
01387          queue operations while waiting for the DB.
01388 
01389          This will be two separate database transactions, so we might
01390          see queue parameters as they were before another process
01391          changed the queue and member list as it was after the change.
01392          Thus we might see an empty member list when a queue is
01393          deleted. In practise, this is unlikely to cause a problem. */
01394 
01395       queue_vars = ast_load_realtime("queues", "name", queuename, NULL);
01396       if (queue_vars) {
01397          member_config = ast_load_realtime_multientry("queue_members", "interface LIKE", "%", "queue_name", queuename, NULL);
01398          if (!member_config) {
01399             ast_log(LOG_ERROR, "no queue_members defined in your config (extconfig.conf).\n");
01400             ast_variables_destroy(queue_vars);
01401             return NULL;
01402          }
01403       }
01404 
01405       AST_LIST_LOCK(&queues);
01406 
01407       q = find_queue_by_name_rt(queuename, queue_vars, member_config);
01408       if (member_config)
01409          ast_config_destroy(member_config);
01410       if (queue_vars)
01411          ast_variables_destroy(queue_vars);
01412 
01413       AST_LIST_UNLOCK(&queues);
01414    } else { 
01415       update_realtime_members(q);
01416    }
01417    return q;
01418 }
01419 
01420 static int join_queue(char *queuename, struct queue_ent *qe, enum queue_result *reason)
01421 {
01422    struct call_queue *q;
01423    struct queue_ent *cur, *prev = NULL;
01424    int res = -1;
01425    int pos = 0;
01426    int inserted = 0;
01427    enum queue_member_status stat;
01428 
01429    if (!(q = load_realtime_queue(queuename)))
01430       return res;
01431 
01432    AST_LIST_LOCK(&queues);
01433    ast_mutex_lock(&q->lock);
01434 
01435    /* This is our one */
01436    stat = get_member_status(q, qe->max_penalty);
01437    if (!q->joinempty && (stat == QUEUE_NO_MEMBERS))
01438       *reason = QUEUE_JOINEMPTY;
01439    else if ((q->joinempty == QUEUE_EMPTY_STRICT) && (stat == QUEUE_NO_REACHABLE_MEMBERS || stat == QUEUE_NO_MEMBERS))
01440       *reason = QUEUE_JOINUNAVAIL;
01441    else if (q->maxlen && (q->count >= q->maxlen))
01442       *reason = QUEUE_FULL;
01443    else {
01444       /* There's space for us, put us at the right position inside
01445        * the queue.
01446        * Take into account the priority of the calling user */
01447       inserted = 0;
01448       prev = NULL;
01449       cur = q->head;
01450       while (cur) {
01451          /* We have higher priority than the current user, enter
01452           * before him, after all the other users with priority
01453           * higher or equal to our priority. */
01454          if ((!inserted) && (qe->prio > cur->prio)) {
01455             insert_entry(q, prev, qe, &pos);
01456             inserted = 1;
01457          }
01458          cur->pos = ++pos;
01459          prev = cur;
01460          cur = cur->next;
01461       }
01462       /* No luck, join at the end of the queue */
01463       if (!inserted)
01464          insert_entry(q, prev, qe, &pos);
01465       ast_copy_string(qe->moh, q->moh, sizeof(qe->moh));
01466       ast_copy_string(qe->announce, q->announce, sizeof(qe->announce));
01467       ast_copy_string(qe->context, q->context, sizeof(qe->context));
01468       q->count++;
01469       res = 0;
01470       manager_event(EVENT_FLAG_CALL, "Join",
01471          "Channel: %s\r\nCallerID: %s\r\nCallerIDName: %s\r\nQueue: %s\r\nPosition: %d\r\nCount: %d\r\nUniqueid: %s\r\n",
01472          qe->chan->name,
01473          S_OR(qe->chan->cid.cid_num, "unknown"), /* XXX somewhere else it is <unknown> */
01474          S_OR(qe->chan->cid.cid_name, "unknown"),
01475          q->name, qe->pos, q->count, qe->chan->uniqueid );
01476       if (option_debug)
01477          ast_log(LOG_DEBUG, "Queue '%s' Join, Channel '%s', Position '%d'\n", q->name, qe->chan->name, qe->pos );
01478    }
01479    ast_mutex_unlock(&q->lock);
01480    AST_LIST_UNLOCK(&queues);
01481 
01482    return res;
01483 }
01484 
01485 static int play_file(struct ast_channel *chan, char *filename)
01486 {
01487    int res;
01488 
01489    ast_stopstream(chan);
01490 
01491    res = ast_streamfile(chan, filename, chan->language);
01492    if (!res)
01493       res = ast_waitstream(chan, AST_DIGIT_ANY);
01494 
01495    ast_stopstream(chan);
01496 
01497    return res;
01498 }
01499 
01500 static int valid_exit(struct queue_ent *qe, char digit)
01501 {
01502    int digitlen = strlen(qe->digits);
01503 
01504    /* Prevent possible buffer overflow */
01505    if (digitlen < sizeof(qe->digits) - 2) {
01506       qe->digits[digitlen] = digit;
01507       qe->digits[digitlen + 1] = '\0';
01508    } else {
01509       qe->digits[0] = '\0';
01510       return 0;
01511    }
01512 
01513    /* If there's no context to goto, short-circuit */
01514    if (ast_strlen_zero(qe->context))
01515       return 0;
01516 
01517    /* If the extension is bad, then reset the digits to blank */
01518    if (!ast_canmatch_extension(qe->chan, qe->context, qe->digits, 1, qe->chan->cid.cid_num)) {
01519       qe->digits[0] = '\0';
01520       return 0;
01521    }
01522 
01523    /* We have an exact match */
01524    if (!ast_goto_if_exists(qe->chan, qe->context, qe->digits, 1)) {
01525       qe->valid_digits = 1;
01526       /* Return 1 on a successful goto */
01527       return 1;
01528    }
01529 
01530    return 0;
01531 }
01532 
01533 static int say_position(struct queue_ent *qe)
01534 {
01535    int res = 0, avgholdmins, avgholdsecs;
01536    time_t now;
01537 
01538    /* Check to see if this is ludicrous -- if we just announced position, don't do it again*/
01539    time(&now);
01540    if ((now - qe->last_pos) < 15)
01541       return 0;
01542 
01543    /* If either our position has changed, or we are over the freq timer, say position */
01544    if ((qe->last_pos_said == qe->pos) && ((now - qe->last_pos) < qe->parent->announcefrequency))
01545       return 0;
01546 
01547    ast_moh_stop(qe->chan);
01548    /* Say we're next, if we are */
01549    if (qe->pos == 1) {
01550       res = play_file(qe->chan, qe->parent->sound_next);
01551       if (res)
01552          goto playout;
01553       else
01554          goto posout;
01555    } else {
01556       res = play_file(qe->chan, qe->parent->sound_thereare);
01557       if (res)
01558          goto playout;
01559       res = ast_say_number(qe->chan, qe->pos, AST_DIGIT_ANY, qe->chan->language, (char *) NULL); /* Needs gender */
01560       if (res)
01561          goto playout;
01562       res = play_file(qe->chan, qe->parent->sound_calls);
01563       if (res)
01564          goto playout;
01565    }
01566    /* Round hold time to nearest minute */
01567    avgholdmins = abs(((qe->parent->holdtime + 30) - (now - qe->start)) / 60);
01568 
01569    /* If they have specified a rounding then round the seconds as well */
01570    if (qe->parent->roundingseconds) {
01571       avgholdsecs = (abs(((qe->parent->holdtime + 30) - (now - qe->start))) - 60 * avgholdmins) / qe->parent->roundingseconds;
01572       avgholdsecs *= qe->parent->roundingseconds;
01573    } else {
01574       avgholdsecs = 0;
01575    }
01576 
01577    if (option_verbose > 2)
01578       ast_verbose(VERBOSE_PREFIX_3 "Hold time for %s is %d minutes %d seconds\n", qe->parent->name, avgholdmins, avgholdsecs);
01579 
01580    /* If the hold time is >1 min, if it's enabled, and if it's not
01581       supposed to be only once and we have already said it, say it */
01582     if ((avgholdmins+avgholdsecs) > 0 && qe->parent->announceholdtime &&
01583         ((qe->parent->announceholdtime == ANNOUNCEHOLDTIME_ONCE && !qe->last_pos) ||
01584         !(qe->parent->announceholdtime == ANNOUNCEHOLDTIME_ONCE))) {
01585       res = play_file(qe->chan, qe->parent->sound_holdtime);
01586       if (res)
01587          goto playout;
01588 
01589       if (avgholdmins > 0) {
01590          if (avgholdmins < 2) {
01591             res = play_file(qe->chan, qe->parent->sound_lessthan);
01592             if (res)
01593                goto playout;
01594 
01595             res = ast_say_number(qe->chan, 2, AST_DIGIT_ANY, qe->chan->language, NULL);
01596             if (res)
01597                goto playout;
01598          } else {
01599             res = ast_say_number(qe->chan, avgholdmins, AST_DIGIT_ANY, qe->chan->language, NULL);
01600             if (res)
01601                goto playout;
01602          }
01603          
01604          res = play_file(qe->chan, qe->parent->sound_minutes);
01605          if (res)
01606             goto playout;
01607       }
01608       if (avgholdsecs>0) {
01609          res = ast_say_number(qe->chan, avgholdsecs, AST_DIGIT_ANY, qe->chan->language, NULL);
01610          if (res)
01611             goto playout;
01612 
01613          res = play_file(qe->chan, qe->parent->sound_seconds);
01614          if (res)
01615             goto playout;
01616       }
01617 
01618    }
01619 
01620 posout:
01621    if (option_verbose > 2)
01622       ast_verbose(VERBOSE_PREFIX_3 "Told %s in %s their queue position (which was %d)\n",
01623          qe->chan->name, qe->parent->name, qe->pos);
01624    res = play_file(qe->chan, qe->parent->sound_thanks);
01625 
01626 playout:
01627    if ((res > 0 && !valid_exit(qe, res)) || res < 0)
01628       res = 0;
01629 
01630    /* Set our last_pos indicators */
01631    qe->last_pos = now;
01632    qe->last_pos_said = qe->pos;
01633 
01634    /* Don't restart music on hold if we're about to exit the caller from the queue */
01635    if (!res)
01636       ast_moh_start(qe->chan, qe->moh, NULL);
01637 
01638    return res;
01639 }
01640 
01641 static void recalc_holdtime(struct queue_ent *qe, int newholdtime)
01642 {
01643    int oldvalue;
01644 
01645    /* Calculate holdtime using an exponential average */
01646    /* Thanks to SRT for this contribution */
01647    /* 2^2 (4) is the filter coefficient; a higher exponent would give old entries more weight */
01648 
01649    ast_mutex_lock(&qe->parent->lock);
01650    oldvalue = qe->parent->holdtime;
01651    qe->parent->holdtime = (((oldvalue << 2) - oldvalue) + newholdtime) >> 2;
01652    ast_mutex_unlock(&qe->parent->lock);
01653 }
01654 
01655 
01656 static void leave_queue(struct queue_ent *qe)
01657 {
01658    struct call_queue *q;
01659    struct queue_ent *cur, *prev = NULL;
01660    int pos = 0;
01661 
01662    if (!(q = qe->parent))
01663       return;
01664    ast_mutex_lock(&q->lock);
01665 
01666    prev = NULL;
01667    for (cur = q->head; cur; cur = cur->next) {
01668       if (cur == qe) {
01669          q->count--;
01670 
01671          /* Take us out of the queue */
01672          manager_event(EVENT_FLAG_CALL, "Leave",
01673             "Channel: %s\r\nQueue: %s\r\nCount: %d\r\nUniqueid: %s\r\n",
01674             qe->chan->name, q->name,  q->count, qe->chan->uniqueid);
01675          if (option_debug)
01676             ast_log(LOG_DEBUG, "Queue '%s' Leave, Channel '%s'\n", q->name, qe->chan->name );
01677          /* Take us out of the queue */
01678          if (prev)
01679             prev->next = cur->next;
01680          else
01681             q->head = cur->next;
01682       } else {
01683          /* Renumber the people after us in the queue based on a new count */
01684          cur->pos = ++pos;
01685          prev = cur;
01686       }
01687    }
01688    ast_mutex_unlock(&q->lock);
01689 
01690    if (q->dead && !q->count) {   
01691       /* It's dead and nobody is in it, so kill it */
01692       AST_LIST_LOCK(&queues);
01693       AST_LIST_REMOVE(&queues, q, list);
01694       AST_LIST_UNLOCK(&queues);
01695       destroy_queue(q);
01696    }
01697 }
01698 
01699 /* Hang up a list of outgoing calls */
01700 static void hangupcalls(struct callattempt *outgoing, struct ast_channel *exception)
01701 {
01702    struct callattempt *oo;
01703 
01704    while (outgoing) {
01705       /* Hangup any existing lines we have open */
01706       if (outgoing->chan && (outgoing->chan != exception))
01707          ast_hangup(outgoing->chan);
01708       oo = outgoing;
01709       outgoing = outgoing->q_next;
01710       if (oo->member)
01711          ao2_ref(oo->member, -1);
01712       free(oo);
01713    }
01714 }
01715 
01716 
01717 /* traverse all defined queues which have calls waiting and contain this member
01718    return 0 if no other queue has precedence (higher weight) or 1 if found  */
01719 static int compare_weight(struct call_queue *rq, struct member *member)
01720 {
01721    struct call_queue *q;
01722    struct member *mem;
01723    int found = 0;
01724    
01725    /* &qlock and &rq->lock already set by try_calling()
01726     * to solve deadlock */
01727    AST_LIST_TRAVERSE(&queues, q, list) {
01728       if (q == rq) /* don't check myself, could deadlock */
01729          continue;
01730       ast_mutex_lock(&q->lock);
01731       if (q->count && q->members) {
01732          if ((mem = ao2_find(q->members, member, OBJ_POINTER))) {
01733             ast_log(LOG_DEBUG, "Found matching member %s in queue '%s'\n", mem->interface, q->name);
01734             if (q->weight > rq->weight) {
01735                ast_log(LOG_DEBUG, "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);
01736                found = 1;
01737             }
01738             ao2_ref(mem, -1);
01739          }
01740       }
01741       ast_mutex_unlock(&q->lock);
01742       if (found)
01743          break;
01744    }
01745    return found;
01746 }
01747 
01748 /*! \brief common hangup actions */
01749 static void do_hang(struct callattempt *o)
01750 {
01751    o->stillgoing = 0;
01752    ast_hangup(o->chan);
01753    o->chan = NULL;
01754 }
01755 
01756 static char *vars2manager(struct ast_channel *chan, char *vars, size_t len)
01757 {
01758    char *tmp = alloca(len);
01759 
01760    if (pbx_builtin_serialize_variables(chan, tmp, len)) {
01761       int i, j;
01762 
01763       /* convert "\n" to "\nVariable: " */
01764       strcpy(vars, "Variable: ");
01765 
01766       for (i = 0, j = 10; (i < len - 1) && (j < len - 1); i++, j++) {
01767          vars[j] = tmp[i];
01768 
01769          if (tmp[i + 1] == '\0')
01770             break;
01771          if (tmp[i] == '\n') {
01772             vars[j++] = '\r';
01773             vars[j++] = '\n';
01774 
01775             ast_copy_string(&(vars[j]), "Variable: ", len - j);
01776             j += 9;
01777          }
01778       }
01779       if (j > len - 3)
01780          j = len - 3;
01781       vars[j++] = '\r';
01782       vars[j++] = '\n';
01783       vars[j] = '\0';
01784    } else {
01785       /* there are no channel variables; leave it blank */
01786       *vars = '\0';
01787    }
01788    return vars;
01789 }
01790 
01791 /*! \brief Part 2 of ring_one
01792  *
01793  * Does error checking before attempting to request a channel and call a member. This
01794  * function is only called from ring_one
01795  */
01796 static int ring_entry(struct queue_ent *qe, struct callattempt *tmp, int *busies)
01797 {
01798    int res;
01799    int status;
01800    char tech[256];
01801    char *location;
01802    const char *macrocontext, *macroexten;
01803 
01804    /* on entry here, we know that tmp->chan == NULL */
01805    if (qe->parent->wrapuptime && (time(NULL) - tmp->lastcall < qe->parent->wrapuptime)) {
01806       if (option_debug)
01807          ast_log(LOG_DEBUG, "Wrapuptime not yet expired for %s\n", tmp->interface);
01808       if (qe->chan->cdr)
01809          ast_cdr_busy(qe->chan->cdr);
01810       tmp->stillgoing = 0;
01811       (*busies)++;
01812       return 0;
01813    }
01814 
01815    if (!qe->parent->ringinuse && (tmp->member->status != AST_DEVICE_NOT_INUSE) && (tmp->member->status != AST_DEVICE_UNKNOWN)) {
01816       if (option_debug)
01817          ast_log(LOG_DEBUG, "%s in use, can't receive call\n", tmp->interface);
01818       if (qe->chan->cdr)
01819          ast_cdr_busy(qe->chan->cdr);
01820       tmp->stillgoing = 0;
01821       return 0;
01822    }
01823 
01824    if (tmp->member->paused) {
01825       if (option_debug)
01826          ast_log(LOG_DEBUG, "%s paused, can't receive call\n", tmp->interface);
01827       if (qe->chan->cdr)
01828          ast_cdr_busy(qe->chan->cdr);
01829       tmp->stillgoing = 0;
01830       return 0;
01831    }
01832    if (use_weight && compare_weight(qe->parent,tmp->member)) {
01833       ast_log(LOG_DEBUG, "Priority queue delaying call to %s:%s\n", qe->parent->name, tmp->interface);
01834       if (qe->chan->cdr)
01835          ast_cdr_busy(qe->chan->cdr);
01836       tmp->stillgoing = 0;
01837       (*busies)++;
01838       return 0;
01839    }
01840 
01841    ast_copy_string(tech, tmp->interface, sizeof(tech));
01842    if ((location = strchr(tech, '/')))
01843       *location++ = '\0';
01844    else
01845       location = "";
01846 
01847    /* Request the peer */
01848    tmp->chan = ast_request(tech, qe->chan->nativeformats, location, &status);
01849    if (!tmp->chan) {       /* If we can't, just go on to the next call */
01850       if (qe->chan->cdr)
01851          ast_cdr_busy(qe->chan->cdr);
01852       tmp->stillgoing = 0;
01853 
01854       update_status(tmp->member->interface, ast_device_state(tmp->member->interface));
01855 
01856       ast_mutex_lock(&qe->parent->lock);
01857       qe->parent->rrpos++;
01858       ast_mutex_unlock(&qe->parent->lock);
01859 
01860       (*busies)++;
01861       return 0;
01862    }
01863    
01864    tmp->chan->appl = "AppQueue";
01865    tmp->chan->data = "(Outgoing Line)";
01866    tmp->chan->whentohangup = 0;
01867    if (tmp->chan->cid.cid_num)
01868       free(tmp->chan->cid.cid_num);
01869    tmp->chan->cid.cid_num = ast_strdup(qe->chan->cid.cid_num);
01870    if (tmp->chan->cid.cid_name)
01871       free(tmp->chan->cid.cid_name);
01872    tmp->chan->cid.cid_name = ast_strdup(qe->chan->cid.cid_name);
01873    if (tmp->chan->cid.cid_ani)
01874       free(tmp->chan->cid.cid_ani);
01875    tmp->chan->cid.cid_ani = ast_strdup(qe->chan->cid.cid_ani);
01876 
01877    /* Inherit specially named variables from parent channel */
01878    ast_channel_inherit_variables(qe->chan, tmp->chan);
01879 
01880    /* Presense of ADSI CPE on outgoing channel follows ours */
01881    tmp->chan->adsicpe = qe->chan->adsicpe;
01882 
01883    /* Inherit context and extension */
01884    ast_channel_lock(qe->chan);
01885    macrocontext = pbx_builtin_getvar_helper(qe->chan, "MACRO_CONTEXT");
01886    if (!ast_strlen_zero(macrocontext))
01887       ast_copy_string(tmp->chan->dialcontext, macrocontext, sizeof(tmp->chan->dialcontext));
01888    else
01889       ast_copy_string(tmp->chan->dialcontext, qe->chan->context, sizeof(tmp->chan->dialcontext));
01890    macroexten = pbx_builtin_getvar_helper(qe->chan, "MACRO_EXTEN");
01891    if (!ast_strlen_zero(macroexten))
01892       ast_copy_string(tmp->chan->exten, macroexten, sizeof(tmp->chan->exten));
01893    else
01894       ast_copy_string(tmp->chan->exten, qe->chan->exten, sizeof(tmp->chan->exten));
01895    ast_channel_unlock(qe->chan);
01896 
01897    /* Place the call, but don't wait on the answer */
01898    if ((res = ast_call(tmp->chan, location, 0))) {
01899       /* Again, keep going even if there's an error */
01900       if (option_debug)
01901          ast_log(LOG_DEBUG, "ast call on peer returned %d\n", res);
01902       if (option_verbose > 2)
01903          ast_verbose(VERBOSE_PREFIX_3 "Couldn't call %s\n", tmp->interface);
01904       do_hang(tmp);
01905       (*busies)++;
01906       update_status(tmp->member->interface, ast_device_state(tmp->member->interface));
01907       return 0;
01908    } else if (qe->parent->eventwhencalled) {
01909       char vars[2048];
01910 
01911       manager_event(EVENT_FLAG_AGENT, "AgentCalled",
01912                "AgentCalled: %s\r\n"
01913                "AgentName: %s\r\n"
01914                "ChannelCalling: %s\r\n"
01915                "CallerID: %s\r\n"
01916                "CallerIDName: %s\r\n"
01917                "Context: %s\r\n"
01918                "Extension: %s\r\n"
01919                "Priority: %d\r\n"
01920                "%s",
01921                tmp->interface, tmp->member->membername, qe->chan->name,
01922                tmp->chan->cid.cid_num ? tmp->chan->cid.cid_num : "unknown",
01923                tmp->chan->cid.cid_name ? tmp->chan->cid.cid_name : "unknown",
01924                qe->chan->context, qe->chan->exten, qe->chan->priority,
01925                qe->parent->eventwhencalled == QUEUE_EVENT_VARIABLES ? vars2manager(qe->chan, vars, sizeof(vars)) : "");
01926       if (option_verbose > 2)
01927          ast_verbose(VERBOSE_PREFIX_3 "Called %s\n", tmp->interface);
01928    }
01929 
01930    update_status(tmp->member->interface, ast_device_state(tmp->member->interface));
01931    return 1;
01932 }
01933 
01934 /*! \brief find the entry with the best metric, or NULL */
01935 static struct callattempt *find_best(struct callattempt *outgoing)
01936 {
01937    struct callattempt *best = NULL, *cur;
01938 
01939    for (cur = outgoing; cur; cur = cur->q_next) {
01940       if (cur->stillgoing &&              /* Not already done */
01941          !cur->chan &&              /* Isn't already going */
01942          (!best || cur->metric < best->metric)) {     /* We haven't found one yet, or it's better */
01943          best = cur;
01944       }
01945    }
01946 
01947    return best;
01948 }
01949 
01950 /*! \brief Place a call to a queue member
01951  *
01952  * Once metrics have been calculated for each member, this function is used
01953  * to place a call to the appropriate member (or members). The low-level
01954  * channel-handling and error detection is handled in ring_entry
01955  *
01956  * Returns 1 if a member was called successfully, 0 otherwise
01957  */
01958 static int ring_one(struct queue_ent *qe, struct callattempt *outgoing, int *busies)
01959 {
01960    int ret = 0;
01961 
01962    while (ret == 0) {
01963       struct callattempt *best = find_best(outgoing);
01964       if (!best) {
01965          if (option_debug)
01966             ast_log(LOG_DEBUG, "Nobody left to try ringing in queue\n");
01967          break;
01968       }
01969       if (qe->parent->strategy == QUEUE_STRATEGY_RINGALL) {
01970          struct callattempt *cur;
01971          /* Ring everyone who shares this best metric (for ringall) */
01972          for (cur = outgoing; cur; cur = cur->q_next) {
01973             if (cur->stillgoing && !cur->chan && cur->metric <= best->metric) {
01974                if (option_debug)
01975                   ast_log(LOG_DEBUG, "(Parallel) Trying '%s' with metric %d\n", cur->interface, cur->metric);
01976                ret |= ring_entry(qe, cur, busies);
01977             }
01978          }
01979       } else {
01980          /* Ring just the best channel */
01981          if (option_debug)
01982             ast_log(LOG_DEBUG, "Trying '%s' with metric %d\n", best->interface, best->metric);
01983          ret = ring_entry(qe, best, busies);
01984       }
01985    }
01986 
01987    return ret;
01988 }
01989 
01990 static int store_next(struct queue_ent *qe, struct callattempt *outgoing)
01991 {
01992    struct callattempt *best = find_best(outgoing);
01993 
01994    if (best) {
01995       /* Ring just the best channel */
01996       if (option_debug)
01997          ast_log(LOG_DEBUG, "Next is '%s' with metric %d\n", best->interface, best->metric);
01998       qe->parent->rrpos = best->metric % 1000;
01999    } else {
02000       /* Just increment rrpos */
02001       if (qe->parent->wrapped) {
02002          /* No more channels, start over */
02003          qe->parent->rrpos = 0;
02004       } else {
02005          /* Prioritize next entry */
02006          qe->parent->rrpos++;
02007       }
02008    }
02009    qe->parent->wrapped = 0;
02010 
02011    return 0;
02012 }
02013 
02014 static int say_periodic_announcement(struct queue_ent *qe)
02015 {
02016    int res = 0;
02017    time_t now;
02018 
02019    /* Get the current time */
02020    time(&now);
02021 
02022    /* Check to see if it is time to announce */
02023    if ((now - qe->last_periodic_announce_time) < qe->parent->periodicannouncefrequency)
02024       return 0;
02025 
02026    /* Stop the music on hold so we can play our own file */
02027    ast_moh_stop(qe->chan);
02028 
02029    if (option_verbose > 2)
02030       ast_verbose(VERBOSE_PREFIX_3 "Playing periodic announcement\n");
02031 
02032    /* Check to make sure we have a sound file. If not, reset to the first sound file */
02033    if (qe->last_periodic_announce_sound >= MAX_PERIODIC_ANNOUNCEMENTS || !strlen(qe->parent->sound_periodicannounce[qe->last_periodic_announce_sound])) {
02034       qe->last_periodic_announce_sound = 0;
02035    }
02036    
02037    /* play the announcement */
02038    res = play_file(qe->chan, qe->parent->sound_periodicannounce[qe->last_periodic_announce_sound]);
02039 
02040    if ((res > 0 && !valid_exit(qe, res)) || res < 0)
02041       res = 0;
02042 
02043    /* Resume Music on Hold if the caller is going to stay in the queue */
02044    if (!res)
02045       ast_moh_start(qe->chan, qe->moh, NULL);
02046 
02047    /* update last_periodic_announce_time */
02048    qe->last_periodic_announce_time = now;
02049 
02050    /* Update the current periodic announcement to the next announcement */
02051    qe->last_periodic_announce_sound++;
02052    
02053    return res;
02054 }
02055 
02056 static void record_abandoned(struct queue_ent *qe)
02057 {
02058    ast_mutex_lock(&qe->parent->lock);
02059    manager_event(EVENT_FLAG_AGENT, "QueueCallerAbandon",
02060       "Queue: %s\r\n"
02061       "Uniqueid: %s\r\n"
02062       "Position: %d\r\n"
02063       "OriginalPosition: %d\r\n"
02064       "HoldTime: %d\r\n",
02065       qe->parent->name, qe->chan->uniqueid, qe->pos, qe->opos, (int)(time(NULL) - qe->start));
02066 
02067    qe->parent->callsabandoned++;
02068    ast_mutex_unlock(&qe->parent->lock);
02069 }
02070 
02071 /*! \brief RNA == Ring No Answer. Common code that is executed when we try a queue member and they don't answer. */
02072 static void rna(int rnatime, struct queue_ent *qe, char *interface, char *membername)
02073 {
02074    if (option_verbose > 2)
02075       ast_verbose( VERBOSE_PREFIX_3 "Nobody picked up in %d ms\n", rnatime);
02076    ast_queue_log(qe->parent->name, qe->chan->uniqueid, membername, "RINGNOANSWER", "%d", rnatime);
02077    if (qe->parent->autopause) {
02078       if (!set_member_paused(qe->parent->name, interface, 1)) {
02079          if (option_verbose > 2)
02080             ast_verbose( VERBOSE_PREFIX_3 "Auto-Pausing Queue Member %s in queue %s since they failed to answer.\n", interface, qe->parent->name);
02081       } else {
02082          if (option_verbose > 2)
02083             ast_verbose( VERBOSE_PREFIX_3 "Failed to pause Queue Member %s in queue %s!\n", interface, qe->parent->name);
02084       }
02085    }
02086    return;
02087 }
02088 
02089 #define AST_MAX_WATCHERS 256
02090 /*! \brief Wait for a member to answer the call
02091  *
02092  * \param[in] qe the queue_ent corresponding to the caller in the queue
02093  * \param[in] outgoing the list of callattempts. Relevant ones will have their chan and stillgoing parameters non-zero
02094  * \param[in] to the amount of time (in milliseconds) to wait for a response
02095  * \param[out] digit if a user presses a digit to exit the queue, this is the digit the caller pressed
02096  * \param[in] prebusies number of busy members calculated prior to calling wait_for_answer
02097  * \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
02098  * \param[in] forwardsallowed used to detect if we should allow call forwarding, based on the 'i' option to Queue()
02099  */
02100 static struct callattempt *wait_for_answer(struct queue_ent *qe, struct callattempt *outgoing, int *to, char *digit, int prebusies, int caller_disconnect, int forwardsallowed)
02101 {
02102    char *queue = qe->parent->name;
02103    struct callattempt *o, *start = NULL, *prev = NULL;
02104    int status;
02105    int numbusies = prebusies;
02106    int numnochan = 0;
02107    int stillgoing = 0;
02108    int orig = *to;
02109    struct ast_frame *f;
02110    struct callattempt *peer = NULL;
02111    struct ast_channel *winner;
02112    struct ast_channel *in = qe->chan;
02113    char on[80] = "";
02114    char membername[80] = "";
02115    long starttime = 0;
02116    long endtime = 0; 
02117 
02118    starttime = (long) time(NULL);
02119    
02120    while (*to && !peer) {
02121       int numlines, retry, pos = 1;
02122       struct ast_channel *watchers[AST_MAX_WATCHERS];
02123       watchers[0] = in;
02124       start = NULL;
02125 
02126       for (retry = 0; retry < 2; retry++) {
02127          numlines = 0;
02128          for (o = outgoing; o; o = o->q_next) { /* Keep track of important channels */
02129             if (o->stillgoing) { /* Keep track of important channels */
02130                stillgoing = 1;
02131                if (o->chan) {
02132                   watchers[pos++] = o->chan;
02133                   if (!start)
02134                      start = o;
02135                   else
02136                      prev->call_next = o;
02137                   prev = o;
02138                }
02139             }
02140             numlines++;
02141          }
02142          if (pos > 1 /* found */ || !stillgoing /* nobody listening */ ||
02143             (qe->parent->strategy != QUEUE_STRATEGY_RINGALL) /* ring would not be delivered */)
02144             break;
02145          /* On "ringall" strategy we only move to the next penalty level
02146             when *all* ringing phones are done in the current penalty level */
02147          ring_one(qe, outgoing, &numbusies);
02148          /* and retry... */
02149       }
02150       if (pos == 1 /* not found */) {
02151          if (numlines == (numbusies + numnochan)) {
02152             ast_log(LOG_DEBUG, "Everyone is busy at this time\n");
02153          } else {
02154             ast_log(LOG_NOTICE, "No one is answering queue '%s' (%d/%d/%d)\n", queue, numlines, numbusies, numnochan);
02155          }
02156          *to = 0;
02157          return NULL;
02158       }
02159       winner = ast_waitfor_n(watchers, pos, to);
02160       for (o = start; o; o = o->call_next) {
02161          if (o->stillgoing && (o->chan) &&  (o->chan->_state == AST_STATE_UP)) {
02162             if (!peer) {
02163                if (option_verbose > 2)
02164                   ast_verbose( VERBOSE_PREFIX_3 "%s answered %s\n", o->chan->name, in->name);
02165                peer = o;
02166             }
02167          } else if (o->chan && (o->chan == winner)) {
02168 
02169             ast_copy_string(on, o->member->interface, sizeof(on));
02170             ast_copy_string(membername, o->member->membername, sizeof(membername));
02171 
02172             if (!ast_strlen_zero(o->chan->call_forward) && !forwardsallowed) {
02173                if (option_verbose > 2)
02174                   ast_verbose(VERBOSE_PREFIX_3 "Forwarding %s to '%s' prevented.\n", in->name, o->chan->call_forward);
02175                numnochan++;
02176                do_hang(o);
02177                winner = NULL;
02178                continue;
02179             } else if (!ast_strlen_zero(o->chan->call_forward)) {
02180                char tmpchan[256];
02181                char *stuff;
02182                char *tech;
02183 
02184                ast_copy_string(tmpchan, o->chan->call_forward, sizeof(tmpchan));
02185                if ((stuff = strchr(tmpchan, '/'))) {
02186                   *stuff++ = '\0';
02187                   tech = tmpchan;
02188                } else {
02189                   snprintf(tmpchan, sizeof(tmpchan), "%s@%s", o->chan->call_forward, o->chan->context);
02190                   stuff = tmpchan;
02191                   tech = "Local";
02192                }
02193                /* Before processing channel, go ahead and check for forwarding */
02194                if (option_verbose > 2)
02195                   ast_verbose(VERBOSE_PREFIX_3 "Now forwarding %s to '%s/%s' (thanks to %s)\n", in->name, tech, stuff, o->chan->name);
02196                /* Setup parameters */
02197                o->chan = ast_request(tech, in->nativeformats, stuff, &status);
02198                if (!o->chan) {
02199                   ast_log(LOG_NOTICE, "Unable to create local channel for call forward to '%s/%s'\n", tech, stuff);
02200                   o->stillgoing = 0;
02201                   numnochan++;
02202                } else {
02203                   ast_channel_inherit_variables(in, o->chan);
02204                   ast_channel_datastore_inherit(in, o->chan);
02205                   if (o->chan->cid.cid_num)
02206                      free(o->chan->cid.cid_num);
02207                   o->chan->cid.cid_num = ast_strdup(in->cid.cid_num);
02208 
02209                   if (o->chan->cid.cid_name)
02210                      free(o->chan->cid.cid_name);
02211                   o->chan->cid.cid_name = ast_strdup(in->cid.cid_name);
02212 
02213                   ast_string_field_set(o->chan, accountcode, in->accountcode);
02214                   o->chan->cdrflags = in->cdrflags;
02215 
02216                   if (in->cid.cid_ani) {
02217                      if (o->chan->cid.cid_ani)
02218                         free(o->chan->cid.cid_ani);
02219                      o->chan->cid.cid_ani = ast_strdup(in->cid.cid_ani);
02220                   }
02221                   if (o->chan->cid.cid_rdnis)
02222                      free(o->chan->cid.cid_rdnis);
02223                   o->chan->cid.cid_rdnis = ast_strdup(S_OR(in->macroexten, in->exten));
02224                   if (ast_call(o->chan, tmpchan, 0)) {
02225                      ast_log(LOG_NOTICE, "Failed to dial on local channel for call forward to '%s'\n", tmpchan);
02226                      do_hang(o);
02227                      numnochan++;
02228                   }
02229                }
02230                /* Hangup the original channel now, in case we needed it */
02231                ast_hangup(winner);
02232                continue;
02233             }
02234             f = ast_read(winner);
02235             if (f) {
02236                if (f->frametype == AST_FRAME_CONTROL) {
02237                   switch (f->subclass) {
02238                   case AST_CONTROL_ANSWER:
02239                      /* This is our guy if someone answered. */
02240                      if (!peer) {
02241                         if (option_verbose > 2)
02242                            ast_verbose( VERBOSE_PREFIX_3 "%s answered %s\n", o->chan->name, in->name);
02243                         peer = o;
02244                      }
02245                      break;
02246                   case AST_CONTROL_BUSY:
02247                      if (option_verbose > 2)
02248                         ast_verbose( VERBOSE_PREFIX_3 "%s is busy\n", o->chan->name);
02249                      if (in->cdr)
02250                         ast_cdr_busy(in->cdr);
02251                      do_hang(o);
02252                      endtime = (long)time(NULL);
02253                      endtime -= starttime;
02254                      rna(endtime*1000, qe, on, membername);
02255                      if (qe->parent->strategy != QUEUE_STRATEGY_RINGALL) {
02256                         if (qe->parent->timeoutrestart)
02257                            *to = orig;
02258                         ring_one(qe, outgoing, &numbusies);
02259                      }
02260                      numbusies++;
02261                      break;
02262                   case AST_CONTROL_CONGESTION:
02263                      if (option_verbose > 2)
02264                         ast_verbose( VERBOSE_PREFIX_3 "%s is circuit-busy\n", o->chan->name);
02265                      if (in->cdr)
02266                         ast_cdr_busy(in->cdr);
02267                      endtime = (long)time(NULL);
02268                      endtime -= starttime;
02269                      rna(endtime*1000, qe, on, membername);
02270                      do_hang(o);
02271                      if (qe->parent->strategy != QUEUE_STRATEGY_RINGALL) {
02272                         if (qe->parent->timeoutrestart)
02273                            *to = orig;
02274                         ring_one(qe, outgoing, &numbusies);
02275                      }
02276                      numbusies++;
02277                      break;
02278                   case AST_CONTROL_RINGING:
02279                      if (option_verbose > 2)
02280                         ast_verbose( VERBOSE_PREFIX_3 "%s is ringing\n", o->chan->name);
02281                      break;
02282                   case AST_CONTROL_OFFHOOK:
02283                      /* Ignore going off hook */
02284                      break;
02285                   default:
02286                      ast_log(LOG_DEBUG, "Dunno what to do with control type %d\n", f->subclass);
02287                   }
02288                }
02289                ast_frfree(f);
02290             } else {
02291                endtime = (long) time(NULL) - starttime;
02292                rna(endtime * 1000, qe, on, membername);
02293                do_hang(o);
02294                if (qe->parent->strategy != QUEUE_STRATEGY_RINGALL) {
02295                   if (qe->parent->timeoutrestart)
02296                      *to = orig;
02297                   ring_one(qe, outgoing, &numbusies);
02298                }
02299             }
02300          }
02301       }
02302       if (winner == in) {
02303          f = ast_read(in);
02304          if (!f || ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_HANGUP))) {
02305             /* Got hung up */
02306             *to = -1;
02307             if (f)
02308                ast_frfree(f);
02309             return NULL;
02310          }
02311          if ((f->frametype == AST_FRAME_DTMF) && caller_disconnect && (f->subclass == '*')) {
02312             if (option_verbose > 3)
02313                ast_verbose(VERBOSE_PREFIX_3 "User hit %c to disconnect call.\n", f->subclass);
02314             *to = 0;
02315             ast_frfree(f);
02316             return NULL;
02317          }
02318          if ((f->frametype == AST_FRAME_DTMF) && valid_exit(qe, f->subclass)) {
02319             if (option_verbose > 3)
02320                ast_verbose(VERBOSE_PREFIX_3 "User pressed digit: %c\n", f->subclass);
02321             *to = 0;
02322             *digit = f->subclass;
02323             ast_frfree(f);
02324             return NULL;
02325          }
02326          ast_frfree(f);
02327       }
02328       if (!*to) {
02329          for (o = start; o; o = o->call_next)
02330             rna(orig, qe, o->interface, o->member->membername);
02331       }
02332    }
02333 
02334    return peer;
02335 }
02336 /*! \brief Check if we should start attempting to call queue members
02337  *
02338  * The behavior of this function is dependent first on whether autofill is enabled
02339  * and second on whether the ring strategy is ringall. If autofill is not enabled,
02340  * then return true if we're the head of the queue. If autofill is enabled, then
02341  * we count the available members and see if the number of available members is enough
02342  * that given our position in the queue, we would theoretically be able to connect to
02343  * one of those available members
02344  */
02345 static int is_our_turn(struct queue_ent *qe)
02346 {
02347    struct queue_ent *ch;
02348    struct member *cur;
02349    int avl = 0;
02350    int idx = 0;
02351    int res;
02352 
02353    if (!qe->parent->autofill) {
02354       /* Atomically read the parent head -- does not need a lock */
02355       ch = qe->parent->head;
02356       /* If we are now at the top of the head, break out */
02357       if (ch == qe) {
02358          if (option_debug)
02359             ast_log(LOG_DEBUG, "It's our turn (%s).\n", qe->chan->name);
02360          res = 1;
02361       } else {
02362          if (option_debug)
02363             ast_log(LOG_DEBUG, "It's not our turn (%s).\n", qe->chan->name);
02364          res = 0;
02365       }  
02366 
02367    } else {
02368       /* This needs a lock. How many members are available to be served? */
02369       ast_mutex_lock(&qe->parent->lock);
02370          
02371       ch = qe->parent->head;
02372    
02373       if (qe->parent->strategy == QUEUE_STRATEGY_RINGALL) {
02374          if (option_debug)
02375             ast_log(LOG_DEBUG, "Even though there may be multiple members available, the strategy is ringall so only the head call is allowed in\n");
02376          avl = 1;
02377       } else {
02378          struct ao2_iterator mem_iter = ao2_iterator_init(qe->parent->members, 0);
02379          while ((cur = ao2_iterator_next(&mem_iter))) {
02380             switch (cur->status) {
02381             case AST_DEVICE_INUSE:
02382                if (!qe->parent->ringinuse)
02383                   break;
02384                /* else fall through */
02385             case AST_DEVICE_NOT_INUSE:
02386             case AST_DEVICE_UNKNOWN:
02387                if (!cur->paused)
02388                   avl++;
02389                break;
02390             }
02391             ao2_ref(cur, -1);
02392          }
02393       }
02394 
02395       if (option_debug)
02396          ast_log(LOG_DEBUG, "There are %d available members.\n", avl);
02397    
02398       while ((idx < avl) && (ch) && (ch != qe)) {
02399          if (!ch->pending)
02400             idx++;
02401          ch = ch->next;       
02402       }
02403    
02404       /* If the queue entry is within avl [the number of available members] calls from the top ... */
02405       if (ch && idx < avl) {
02406          if (option_debug)
02407             ast_log(LOG_DEBUG, "It's our turn (%s).\n", qe->chan->name);
02408          res = 1;
02409       } else {
02410          if (option_debug)
02411             ast_log(LOG_DEBUG, "It's not our turn (%s).\n", qe->chan->name);
02412          res = 0;
02413       }
02414       
02415       ast_mutex_unlock(&qe->parent->lock);
02416    }
02417 
02418    return res;
02419 }
02420 /*! \brief The waiting areas for callers who are not actively calling members
02421  *
02422  * This function is one large loop. This function will return if a caller
02423  * either exits the queue or it becomes that caller's turn to attempt calling
02424  * queue members. Inside the loop, we service the caller with periodic announcements,
02425  * holdtime announcements, etc. as configured in queues.conf
02426  *
02427  * \retval  0 if the caller's turn has arrived
02428  * \retval -1 if the caller should exit the queue.
02429  */
02430 static int wait_our_turn(struct queue_ent *qe, int ringing, enum queue_result *reason)
02431 {
02432    int res = 0;
02433 
02434    /* This is the holding pen for callers 2 through maxlen */
02435    for (;;) {
02436       enum queue_member_status stat;
02437 
02438       if (is_our_turn(qe))
02439          break;
02440 
02441       /* If we have timed out, break out */
02442       if (qe->expire && (time(NULL) >= qe->expire)) {
02443          *reason = QUEUE_TIMEOUT;
02444          break;
02445       }
02446 
02447       stat = get_member_status(qe->parent, qe->max_penalty);
02448 
02449       /* leave the queue if no agents, if enabled */
02450       if (qe->parent->leavewhenempty && (stat == QUEUE_NO_MEMBERS)) {
02451          *reason = QUEUE_LEAVEEMPTY;
02452          ast_queue_log(qe->parent->name, qe->chan->uniqueid, "NONE", "EXITEMPTY", "%d|%d|%ld", qe->pos, qe->opos, (long)time(NULL) - qe->start);
02453          leave_queue(qe);
02454          break;
02455       }
02456 
02457       /* leave the queue if no reachable agents, if enabled */
02458       if ((qe->parent->leavewhenempty == QUEUE_EMPTY_STRICT) && (stat == QUEUE_NO_REACHABLE_MEMBERS)) {
02459          *reason = QUEUE_LEAVEUNAVAIL;
02460          ast_queue_log(qe->parent->name, qe->chan->uniqueid, "NONE", "EXITEMPTY", "%d|%d|%ld", qe->pos, qe->opos, (long)time(NULL) - qe->start);
02461          leave_queue(qe);
02462          break;
02463       }
02464 
02465       /* Make a position announcement, if enabled */
02466       if (qe->parent->announcefrequency && !ringing &&
02467          (res = say_position(qe)))
02468          break;
02469 
02470       /* If we have timed out, break out */
02471       if (qe->expire && (time(NULL) >= qe->expire)) {
02472          *reason = QUEUE_TIMEOUT;
02473          break;
02474       }
02475 
02476       /* Make a periodic announcement, if enabled */
02477       if (qe->parent->periodicannouncefrequency && !ringing &&
02478          (res = say_periodic_announcement(qe)))
02479          break;
02480 
02481       /* If we have timed out, break out */
02482       if (qe->expire && (time(NULL) >= qe->expire)) {
02483          *reason = QUEUE_TIMEOUT;
02484          break;
02485       }
02486       
02487       /* Wait a second before checking again */
02488       if ((res = ast_waitfordigit(qe->chan, RECHECK * 1000))) {
02489          if (res > 0 && !valid_exit(qe, res))
02490             res = 0;
02491          else
02492             break;
02493       }
02494       
02495       /* If we have timed out, break out */
02496       if (qe->expire && (time(NULL) >= qe->expire)) {
02497          *reason = QUEUE_TIMEOUT;
02498          break;
02499       }
02500    }
02501 
02502    return res;
02503 }
02504 
02505 static int update_queue(struct call_queue *q, struct member *member, int callcompletedinsl)
02506 {
02507    ast_mutex_lock(&q->lock);
02508    time(&member->lastcall);
02509    member->calls++;
02510    q->callscompleted++;
02511    if (callcompletedinsl)
02512       q->callscompletedinsl++;
02513    ast_mutex_unlock(&q->lock);
02514    return 0;
02515 }
02516 
02517 /*! \brief Calculate the metric of each member in the outgoing callattempts
02518  *
02519  * A numeric metric is given to each member depending on the ring strategy used
02520  * by the queue. Members with lower metrics will be called before members with
02521  * higher metrics
02522  */
02523 static int calc_metric(struct call_queue *q, struct member *mem, int pos, struct queue_ent *qe, struct callattempt *tmp)
02524 {
02525    if (qe->max_penalty && (mem->penalty > qe->max_penalty))
02526       return -1;
02527 
02528    switch (q->strategy) {
02529    case QUEUE_STRATEGY_RINGALL:
02530       /* Everyone equal, except for penalty */
02531       tmp->metric = mem->penalty * 1000000;
02532       break;
02533    case QUEUE_STRATEGY_ROUNDROBIN:
02534       if (!pos) {
02535          if (!q->wrapped) {
02536             /* No more channels, start over */
02537             q->rrpos = 0;
02538          } else {
02539             /* Prioritize next entry */
02540             q->rrpos++;
02541          }
02542          q->wrapped = 0;
02543       }
02544       /* Fall through */
02545    case QUEUE_STRATEGY_RRMEMORY:
02546       if (pos < q->rrpos) {
02547          tmp->metric = 1000 + pos;
02548       } else {
02549          if (pos > q->rrpos)
02550             /* Indicate there is another priority */
02551             q->wrapped = 1;
02552          tmp->metric = pos;
02553       }
02554       tmp->metric += mem->penalty * 1000000;
02555       break;
02556    case QUEUE_STRATEGY_RANDOM:
02557       tmp->metric = ast_random() % 1000;
02558       tmp->metric += mem->penalty * 1000000;
02559       break;
02560    case QUEUE_STRATEGY_FEWESTCALLS:
02561       tmp->metric = mem->calls;
02562       tmp->metric += mem->penalty * 1000000;
02563       break;
02564    case QUEUE_STRATEGY_LEASTRECENT:
02565       if (!mem->lastcall)
02566          tmp->metric = 0;
02567       else
02568          tmp->metric = 1000000 - (time(NULL) - mem->lastcall);
02569       tmp->metric += mem->penalty * 1000000;
02570       break;
02571    default:
02572       ast_log(LOG_WARNING, "Can't calculate metric for unknown strategy %d\n", q->strategy);
02573       break;
02574    }
02575    return 0;
02576 }
02577 
02578 struct queue_transfer_ds {
02579    struct queue_ent *qe;
02580    struct member *member;
02581    time_t starttime;
02582    int callcompletedinsl;
02583 };
02584 
02585 static void queue_transfer_destroy(void *data)
02586 {
02587    struct queue_transfer_ds *qtds = data;
02588    ast_free(qtds);
02589 }
02590 
02591 /*! \brief a datastore used to help correctly log attended transfers of queue callers
02592  */
02593 static const struct ast_datastore_info queue_transfer_info = {
02594    .type = "queue_transfer",
02595    .chan_fixup = queue_transfer_fixup,
02596    .destroy = queue_transfer_destroy,
02597 };
02598 
02599 /*! \brief Log an attended transfer when a queue caller channel is masqueraded
02600  *
02601  * When a caller is masqueraded, we want to log a transfer. Fixup time is the closest we can come to when
02602  * the actual transfer occurs. This happens during the masquerade after datastores are moved from old_chan
02603  * to new_chan. This is why new_chan is referenced for exten, context, and datastore information.
02604  *
02605  * At the end of this, we want to remove the datastore so that this fixup function is not called on any
02606  * future masquerades of the caller during the current call.
02607  */
02608 static void queue_transfer_fixup(void *data, struct ast_channel *old_chan, struct ast_channel *new_chan)
02609 {
02610    struct queue_transfer_ds *qtds = data;
02611    struct queue_ent *qe = qtds->qe;
02612    struct member *member = qtds->member;
02613    time_t callstart = qtds->starttime;
02614    int callcompletedinsl = qtds->callcompletedinsl;
02615    struct ast_datastore *datastore;
02616 
02617    ast_queue_log(qe->parent->name, qe->chan->uniqueid, member->membername, "TRANSFER", "%s|%s|%ld|%ld",
02618             new_chan->exten, new_chan->context, (long) (callstart - qe->start),
02619             (long) (time(NULL) - callstart));
02620 
02621    update_queue(qe->parent, member, callcompletedinsl);
02622    
02623    if ((datastore = ast_channel_datastore_find(new_chan, &queue_transfer_info, NULL))) {
02624       ast_channel_datastore_remove(new_chan, datastore);
02625    } else {
02626       ast_log(LOG_WARNING, "Can't find the queue_transfer datastore.\n");
02627    }
02628 }
02629 
02630 /*! \brief mechanism to tell if a queue caller was atxferred by a queue member.
02631  *
02632  * When a caller is atxferred, then the queue_transfer_info datastore
02633  * is removed from the channel. If it's still there after the bridge is
02634  * broken, then the caller was not atxferred.
02635  */
02636 static int attended_transfer_occurred(struct ast_channel *chan)
02637 {
02638    return ast_channel_datastore_find(chan, &queue_transfer_info, NULL) ? 0 : 1;
02639 }
02640 
02641 /*! \brief create a datastore for storing relevant info to log attended transfers in the queue_log
02642  */
02643 static struct ast_datastore *setup_transfer_datastore(struct queue_ent *qe, struct member *member, time_t starttime, int callcompletedinsl)
02644 {
02645    struct ast_datastore *ds;
02646    struct queue_transfer_ds *qtds = ast_calloc(1, sizeof(*qtds));
02647 
02648    if (!qtds) {
02649       ast_log(LOG_WARNING, "Memory allocation error!\n");
02650       return NULL;
02651    }
02652 
02653    ast_channel_lock(qe->chan);
02654    if (!(ds = ast_channel_datastore_alloc(&queue_transfer_info, NULL))) {
02655       ast_channel_unlock(qe->chan);
02656       ast_log(LOG_WARNING, "Unable to create transfer datastore. queue_log will not show attended transfer\n");
02657       return NULL;
02658    }
02659 
02660    qtds->qe = qe;
02661    /* This member is refcounted in try_calling, so no need to add it here, too */
02662    qtds->member = member;
02663    qtds->starttime = starttime;
02664    qtds->callcompletedinsl = callcompletedinsl;
02665    ds->data = qtds;
02666    ast_channel_datastore_add(qe->chan, ds);
02667    ast_channel_unlock(qe->chan);
02668    return ds;
02669 }
02670 
02671 
02672 /*! \brief A large function which calls members, updates statistics, and bridges the caller and a member
02673  * 
02674  * Here is the process of this function
02675  * 1. Process any options passed to the Queue() application. Options here mean the third argument to Queue()
02676  * 2. Iterate trough the members of the queue, creating a callattempt corresponding to each member. During this
02677  *    iteration, we also check the dialed_interfaces datastore to see if we have already attempted calling this
02678  *    member. If we have, we do not create a callattempt. This is in place to prevent call forwarding loops. Also
02679  *    during each iteration, we call calc_metric to determine which members should be rung when.
02680  * 3. Call ring_one to place a call to the appropriate member(s)
02681  * 4. Call wait_for_answer to wait for an answer. If no one answers, return.
02682  * 5. Take care of any holdtime announcements, member delays, or other options which occur after a call has been answered.
02683  * 6. Start the monitor or mixmonitor if the option is set
02684  * 7. Remove the caller from the queue to allow other callers to advance
02685  * 8. Bridge the call.
02686  * 9. Do any post processing after the call has disconnected.
02687  *
02688  * \param[in] qe the queue_ent structure which corresponds to the caller attempting to reach members
02689  * \param[in] options the options passed as the third parameter to the Queue() application
02690  * \param[in] url the url passed as the fourth parameter to the Queue() application
02691  * \param[in,out] tries the number of times we have tried calling queue members
02692  * \param[out] noption set if the call to Queue() has the 'n' option set.
02693  * \param[in] agi the agi passed as the fifth parameter to the Queue() application
02694  */
02695 
02696 static int try_calling(struct queue_ent *qe, const char *options, char *announceoverride, const char *url, int *tries, int *noption, const char *agi)
02697 {
02698    struct member *cur;
02699    struct callattempt *outgoing = NULL; /* the list of calls we are building */
02700    int to;
02701    char oldexten[AST_MAX_EXTENSION]="";
02702    char oldcontext[AST_MAX_CONTEXT]="";
02703    char queuename[256]="";
02704    struct ast_channel *peer;
02705    struct ast_channel *which;
02706    struct callattempt *lpeer;
02707    struct member *member;
02708    struct ast_app *app;
02709    int res = 0, bridge = 0;
02710    int numbusies = 0;
02711    int x=0;
02712    char *announce = NULL;
02713    char digit = 0;
02714    time_t callstart;
02715    time_t now = time(NULL);
02716    struct ast_bridge_config bridge_config;
02717    char nondataquality = 1;
02718    char *agiexec = NULL;
02719    int ret = 0;
02720    const char *monitorfilename;
02721    const char *monitor_exec;
02722    const char *monitor_options;
02723    char tmpid[256], tmpid2[256];
02724    char meid[1024], meid2[1024];
02725    char mixmonargs[1512];
02726    struct ast_app *mixmonapp = NULL;
02727    char *p;
02728    char vars[2048];
02729    int forwardsallowed = 1;
02730    int callcompletedinsl;
02731    struct ao2_iterator memi;
02732    struct ast_datastore *datastore, *transfer_ds;
02733 
02734    ast_channel_lock(qe->chan);
02735    datastore = ast_channel_datastore_find(qe->chan, &dialed_interface_info, NULL);
02736    ast_channel_unlock(qe->chan);
02737 
02738    memset(&bridge_config, 0, sizeof(bridge_config));
02739    time(&now);
02740 
02741    /* If we've already exceeded our timeout, then just stop
02742     * This should be extremely rare. queue_exec will take care
02743     * of removing the caller and reporting the timeout as the reason.
02744     */
02745    if (qe->expire && now >= qe->expire) {
02746       res = 0;
02747       goto out;
02748    }
02749       
02750    for (; options && *options; options++)
02751       switch (*options) {
02752       case 't':
02753          ast_set_flag(&(bridge_config.features_callee), AST_FEATURE_REDIRECT);
02754          break;
02755       case 'T':
02756          ast_set_flag(&(bridge_config.features_caller), AST_FEATURE_REDIRECT);
02757          break;
02758       case 'w':
02759          ast_set_flag(&(bridge_config.features_callee), AST_FEATURE_AUTOMON);
02760          break;
02761       case 'W':
02762          ast_set_flag(&(bridge_config.features_caller), AST_FEATURE_AUTOMON);
02763          break;
02764       case 'd':
02765          nondataquality = 0;
02766          break;
02767       case 'h':
02768          ast_set_flag(&(bridge_config.features_callee), AST_FEATURE_DISCONNECT);
02769          break;
02770       case 'H':
02771          ast_set_flag(&(bridge_config.features_caller), AST_FEATURE_DISCONNECT);
02772          break;
02773       case 'n':
02774          if (qe->parent->strategy == QUEUE_STRATEGY_ROUNDROBIN || qe->parent->strategy == QUEUE_STRATEGY_RRMEMORY)
02775             (*tries)++;
02776          else
02777             *tries = qe->parent->membercount;
02778          *noption = 1;
02779          break;
02780       case 'i':
02781          forwardsallowed = 0;
02782          break;
02783       }
02784 
02785    /* Hold the lock while we setup the outgoing calls */
02786    if (use_weight)
02787       AST_LIST_LOCK(&queues);
02788    ast_mutex_lock(&qe->parent->lock);
02789    if (option_debug)
02790       ast_log(LOG_DEBUG, "%s is trying to call a queue member.\n",
02791                      qe->chan->name);
02792    ast_copy_string(queuename, qe->parent->name, sizeof(queuename));
02793    if (!ast_strlen_zero(qe->announce))
02794       announce = qe->announce;
02795    if (!ast_strlen_zero(announceoverride))
02796       announce = announceoverride;
02797 
02798    memi = ao2_iterator_init(qe->parent->members, 0);
02799    while ((cur = ao2_iterator_next(&memi))) {
02800       struct callattempt *tmp = ast_calloc(1, sizeof(*tmp));
02801       struct ast_dialed_interface *di;
02802       AST_LIST_HEAD(, ast_dialed_interface) *dialed_interfaces;
02803       if (!tmp) {
02804          ao2_ref(cur, -1);
02805          ast_mutex_unlock(&qe->parent->lock);
02806          if (use_weight)
02807             AST_LIST_UNLOCK(&queues);
02808          goto out;
02809       }
02810       if (!datastore) {
02811          if (!(datastore = ast_channel_datastore_alloc(&dialed_interface_info, NULL))) {
02812             ao2_ref(cur, -1);
02813             ast_mutex_unlock(&qe->parent->lock);
02814             if (use_weight)
02815                AST_LIST_UNLOCK(&queues);
02816             free(tmp);
02817             goto out;
02818          }
02819          datastore->inheritance = DATASTORE_INHERIT_FOREVER;
02820          if (!(dialed_interfaces = ast_calloc(1, sizeof(*dialed_interfaces)))) {
02821             ao2_ref(cur, -1);
02822             ast_mutex_unlock(&qe->parent->lock);
02823             if (use_weight)
02824                AST_LIST_UNLOCK(&queues);
02825             free(tmp);
02826             goto out;
02827          }
02828          datastore->data = dialed_interfaces;
02829          AST_LIST_HEAD_INIT(dialed_interfaces);
02830 
02831          ast_channel_lock(qe->chan);
02832          ast_channel_datastore_add(qe->chan, datastore);
02833          ast_channel_unlock(qe->chan);
02834       } else
02835          dialed_interfaces = datastore->data;
02836 
02837       AST_LIST_LOCK(dialed_interfaces);
02838       AST_LIST_TRAVERSE(dialed_interfaces, di, list) {
02839          if (!strcasecmp(cur->interface, di->interface)) {
02840             ast_log(LOG_DEBUG, "Skipping dialing interface '%s' since it has already been dialed\n", 
02841                di->interface);
02842             break;
02843          }
02844       }
02845       AST_LIST_UNLOCK(dialed_interfaces);
02846       
02847       if (di) {
02848          free(tmp);
02849          continue;
02850       }
02851 
02852       /* It is always ok to dial a Local interface.  We only keep track of
02853        * which "real" interfaces have been dialed.  The Local channel will
02854        * inherit this list so that if it ends up dialing a real interface,
02855        * it won't call one that has already been called. */
02856       if (strncasecmp(cur->interface, "Local/", 6)) {
02857          if (!(di = ast_calloc(1, sizeof(*di) + strlen(cur->interface)))) {
02858             ao2_ref(cur, -1);
02859             ast_mutex_unlock(&qe->parent->lock);
02860             if (use_weight)
02861                AST_LIST_UNLOCK(&queues);
02862             free(tmp);
02863             goto out;
02864          }
02865          strcpy(di->interface, cur->interface);
02866 
02867          AST_LIST_LOCK(dialed_interfaces);
02868          AST_LIST_INSERT_TAIL(dialed_interfaces, di, list);
02869          AST_LIST_UNLOCK(dialed_interfaces);
02870       }
02871 
02872       tmp->stillgoing = -1;
02873       tmp->member = cur;
02874       tmp->oldstatus = cur->status;
02875       tmp->lastcall = cur->lastcall;
02876       ast_copy_string(tmp->interface, cur->interface, sizeof(tmp->interface));
02877       /* Special case: If we ring everyone, go ahead and ring them, otherwise
02878          just calculate their metric for the appropriate strategy */
02879       if (!calc_metric(qe->parent, cur, x++, qe, tmp)) {
02880          /* Put them in the list of outgoing thingies...  We're ready now.
02881             XXX If we're forcibly removed, these outgoing calls won't get
02882             hung up XXX */
02883          tmp->q_next = outgoing;
02884          outgoing = tmp;      
02885          /* If this line is up, don't try anybody else */
02886          if (outgoing->chan && (outgoing->chan->_state == AST_STATE_UP))
02887             break;
02888       } else {
02889          ao2_ref(cur, -1);
02890          free(tmp);
02891       }
02892    }
02893    if (qe->expire && (!qe->parent->timeout || (qe->expire - now) <= qe->parent->timeout))
02894       to = (qe->expire - now) * 1000;
02895    else
02896       to = (qe->parent->timeout) ? qe->parent->timeout * 1000 : -1;
02897    ++qe->pending;
02898    ast_mutex_unlock(&qe->parent->lock);
02899    ring_one(qe, outgoing, &numbusies);
02900    if (use_weight)
02901       AST_LIST_UNLOCK(&queues);
02902    lpeer = wait_for_answer(qe, outgoing, &to, &digit, numbusies, ast_test_flag(&(bridge_config.features_caller), AST_FEATURE_DISCONNECT), forwardsallowed);
02903    /* The ast_channel_datastore_remove() function could fail here if the
02904     * datastore was moved to another channel during a masquerade. If this is
02905     * the case, don't free the datastore here because later, when the channel
02906     * to which the datastore was moved hangs up, it will attempt to free this
02907     * datastore again, causing a crash
02908     */
02909    if (datastore && !ast_channel_datastore_remove(qe->chan, datastore)) {
02910       ast_channel_datastore_free(datastore);
02911    }
02912    ast_mutex_lock(&qe->parent->lock);
02913    if (qe->parent->strategy == QUEUE_STRATEGY_RRMEMORY) {
02914       store_next(qe, outgoing);
02915    }
02916    ast_mutex_unlock(&qe->parent->lock);
02917    peer = lpeer ? lpeer->chan : NULL;
02918    if (!peer) {
02919       qe->pending = 0;
02920       if (to) {
02921          /* Must gotten hung up */
02922          res = -1;
02923       } else {
02924          /* User exited by pressing a digit */
02925          res = digit;
02926       }
02927       if (option_debug && res == -1)
02928          ast_log(LOG_DEBUG, "%s: Nobody answered.\n", qe->chan->name);
02929    } else { /* peer is valid */
02930       /* Ah ha!  Someone answered within the desired timeframe.  Of course after this
02931          we will always return with -1 so that it is hung up properly after the
02932          conversation.  */
02933       if (!strcmp(qe->chan->tech->type, "Zap"))
02934          ast_channel_setoption(qe->chan, AST_OPTION_TONE_VERIFY, &nondataquality, sizeof(nondataquality), 0);
02935       if (!strcmp(peer->tech->type, "Zap"))
02936          ast_channel_setoption(peer, AST_OPTION_TONE_VERIFY, &nondataquality, sizeof(nondataquality), 0);
02937       /* Update parameters for the queue */
02938       time(&now);
02939       recalc_holdtime(qe, (now - qe->start));
02940       ast_mutex_lock(&qe->parent->lock);
02941       callcompletedinsl = ((now - qe->start) <= qe->parent->servicelevel);
02942       ast_mutex_unlock(&qe->parent->lock);
02943       member = lpeer->member;
02944       /* Increment the refcount for this member, since we're going to be using it for awhile in here. */
02945       ao2_ref(member, 1);
02946       hangupcalls(outgoing, peer);
02947       outgoing = NULL;
02948       if (announce || qe->parent->reportholdtime || qe->parent->memberdelay) {
02949          int res2;
02950 
02951          res2 = ast_autoservice_start(qe->chan);
02952          if (!res2) {
02953             if (qe->parent->memberdelay) {
02954                ast_log(LOG_NOTICE, "Delaying member connect for %d seconds\n", qe->parent->memberdelay);
02955                res2 |= ast_safe_sleep(peer, qe->parent->memberdelay * 1000);
02956             }
02957             if (!res2 && announce) {
02958                play_file(peer, announce);
02959             }
02960             if (!res2 && qe->parent->reportholdtime) {
02961                if (!play_file(peer, qe->parent->sound_reporthold)) {
02962                   int holdtime;
02963 
02964                   time(&now);
02965                   holdtime = abs((now - qe->start) / 60);
02966                   if (holdtime < 2) {
02967                      play_file(peer, qe->parent->sound_lessthan);
02968                      ast_say_number(peer, 2, AST_DIGIT_ANY, peer->language, NULL);
02969                   } else
02970                      ast_say_number(peer, holdtime, AST_DIGIT_ANY, peer->language, NULL);
02971                   play_file(peer, qe->parent->sound_minutes);
02972                }
02973             }
02974          }
02975          res2 |= ast_autoservice_stop(qe->chan);
02976          if (peer->_softhangup) {
02977             /* Agent must have hung up */
02978             ast_log(LOG_WARNING, "Agent on %s hungup on the customer.\n", peer->name);
02979             ast_queue_log(queuename, qe->chan->uniqueid, member->membername, "AGENTDUMP", "%s", "");
02980             if (qe->parent->eventwhencalled)
02981                manager_event(EVENT_FLAG_AGENT, "AgentDump",
02982                      "Queue: %s\r\n"
02983                      "Uniqueid: %s\r\n"
02984                      "Channel: %s\r\n"
02985                      "Member: %s\r\n"
02986                      "MemberName: %s\r\n"
02987                      "%s",
02988                      queuename, qe->chan->uniqueid, peer->name, member->interface, member->membername,
02989                      qe->parent->eventwhencalled == QUEUE_EVENT_VARIABLES ? vars2manager(qe->chan, vars, sizeof(vars)) : "");
02990             ast_hangup(peer);
02991             ao2_ref(member, -1);
02992             goto out;
02993          } else if (res2) {
02994             /* Caller must have hung up just before being connected*/
02995             ast_log(LOG_NOTICE, "Caller was about to talk to agent on %s but the caller hungup.\n", peer->name);
02996             ast_queue_log(queuename, qe->chan->uniqueid, member->membername, "ABANDON", "%d|%d|%ld", qe->pos, qe->opos, (long)time(NULL) - qe->start);
02997             record_abandoned(qe);
02998             ast_hangup(peer);
02999             ao2_ref(member, -1);
03000             return -1;
03001          }
03002       }
03003       /* Stop music on hold */
03004       ast_moh_stop(qe->chan);
03005       /* If appropriate, log that we have a destination channel */
03006       if (qe->chan->cdr)
03007          ast_cdr_setdestchan(qe->chan->cdr, peer->name);
03008       /* Make sure channels are compatible */
03009       res = ast_channel_make_compatible(qe->chan, peer);
03010       if (res < 0) {
03011          ast_queue_log(queuename, qe->chan->uniqueid, member->membername, "SYSCOMPAT", "%s", "");
03012          ast_log(LOG_WARNING, "Had to drop call because I couldn't make %s compatible with %s\n", qe->chan->name, peer->name);
03013          record_abandoned(qe);
03014          ast_hangup(peer);
03015          ao2_ref(member, -1);
03016          return -1;
03017       }
03018 
03019       if (qe->parent->setinterfacevar)
03020             pbx_builtin_setvar_helper(qe->chan, "MEMBERINTERFACE", member->interface);
03021 
03022       /* Begin Monitoring */
03023       if (qe->parent->monfmt && *qe->parent->monfmt) {
03024          if (!qe->parent->montype) {
03025             if (option_debug)
03026                ast_log(LOG_DEBUG, "Starting Monitor as requested.\n");
03027             monitorfilename = pbx_builtin_getvar_helper(qe->chan, "MONITOR_FILENAME");
03028             if (pbx_builtin_getvar_helper(qe->chan, "MONITOR_EXEC") || pbx_builtin_getvar_helper(qe->chan, "MONITOR_EXEC_ARGS"))
03029                which = qe->chan;
03030             else
03031                which = peer;
03032             if (monitorfilename)
03033                ast_monitor_start(which, qe->parent->monfmt, monitorfilename, 1 );
03034             else if (qe->chan->cdr)
03035                ast_monitor_start(which, qe->parent->monfmt, qe->chan->cdr->uniqueid, 1 );
03036             else {
03037                /* Last ditch effort -- no CDR, make up something */
03038                snprintf(tmpid, sizeof(tmpid), "chan-%lx", ast_random());
03039                ast_monitor_start(which, qe->parent->monfmt, tmpid, 1 );
03040             }
03041             if (qe->parent->monjoin)
03042                ast_monitor_setjoinfiles(which, 1);
03043          } else {
03044             if (option_debug)
03045                ast_log(LOG_DEBUG, "Starting MixMonitor as requested.\n");
03046             monitorfilename = pbx_builtin_getvar_helper(qe->chan, "MONITOR_FILENAME");
03047             if (!monitorfilename) {
03048                if (qe->chan->cdr)
03049                   ast_copy_string(tmpid, qe->chan->cdr->uniqueid, sizeof(tmpid)-1);
03050                else
03051                   snprintf(tmpid, sizeof(tmpid), "chan-%lx", ast_random());
03052             } else {
03053                ast_copy_string(tmpid2, monitorfilename, sizeof(tmpid2)-1);
03054                for (p = tmpid2; *p ; p++) {
03055                   if (*p == '^' && *(p+1) == '{') {
03056                      *p = '$';
03057                   }
03058                }
03059 
03060                memset(tmpid, 0, sizeof(tmpid));
03061                pbx_substitute_variables_helper(qe->chan, tmpid2, tmpid, sizeof(tmpid) - 1);
03062             }
03063 
03064             monitor_exec = pbx_builtin_getvar_helper(qe->chan, "MONITOR_EXEC");
03065             monitor_options = pbx_builtin_getvar_helper(qe->chan, "MONITOR_OPTIONS");
03066 
03067             if (monitor_exec) {
03068                ast_copy_string(meid2, monitor_exec, sizeof(meid2)-1);
03069                for (p = meid2; *p ; p++) {
03070                   if (*p == '^' && *(p+1) == '{') {
03071                      *p = '$';
03072                   }
03073                }
03074 
03075                memset(meid, 0, sizeof(meid));
03076                pbx_substitute_variables_helper(qe->chan, meid2, meid, sizeof(meid) - 1);
03077             }
03078    
03079             snprintf(tmpid2, sizeof(tmpid2)-1, "%s.%s", tmpid, qe->parent->monfmt);
03080 
03081             mixmonapp = pbx_findapp("MixMonitor");
03082 
03083             if (strchr(tmpid2, '|')) {
03084                ast_log(LOG_WARNING, "monitor-format (in queues.conf) and MONITOR_FILENAME cannot contain a '|'! Not recording.\n");
03085                mixmonapp = NULL;
03086             }
03087 
03088             if (!monitor_options)
03089                monitor_options = "";
03090             
03091             if (strchr(monitor_options, '|')) {
03092                ast_log(LOG_WARNING, "MONITOR_OPTIONS cannot contain a '|'! Not recording.\n");
03093                mixmonapp = NULL;
03094             }
03095 
03096             if (mixmonapp) {
03097                if (!ast_strlen_zero(monitor_exec))
03098                   snprintf(mixmonargs, sizeof(mixmonargs)-1, "%s|b%s|%s", tmpid2, monitor_options, monitor_exec);
03099                else
03100                   snprintf(mixmonargs, sizeof(mixmonargs)-1, "%s|b%s", tmpid2, monitor_options);
03101                   
03102                if (option_debug)
03103                   ast_log(LOG_DEBUG, "Arguments being passed to MixMonitor: %s\n", mixmonargs);
03104                /* We purposely lock the CDR so that pbx_exec does not update the application data */
03105                if (qe->chan->cdr)
03106                   ast_set_flag(qe->chan->cdr, AST_CDR_FLAG_LOCKED);
03107                ret = pbx_exec(qe->chan, mixmonapp, mixmonargs);
03108                if (qe->chan->cdr)
03109                   ast_clear_flag(qe->chan->cdr, AST_CDR_FLAG_LOCKED);
03110 
03111             } else
03112                ast_log(LOG_WARNING, "Asked to run MixMonitor on this call, but cannot find the MixMonitor app!\n");
03113 
03114          }
03115       }
03116       /* Drop out of the queue at this point, to prepare for next caller */
03117       leave_queue(qe);        
03118       if (!ast_strlen_zero(url) && ast_channel_supports_html(peer)) {
03119          if (option_debug)
03120             ast_log(LOG_DEBUG, "app_queue: sendurl=%s.\n", url);
03121          ast_channel_sendurl(peer, url);
03122       }
03123       if (!ast_strlen_zero(agi)) {
03124          if (option_debug)
03125             ast_log(LOG_DEBUG, "app_queue: agi=%s.\n", agi);
03126          app = pbx_findapp("agi");
03127          if (app) {
03128             agiexec = ast_strdupa(agi);
03129             ret = pbx_exec(qe->chan, app, agiexec);
03130          } else
03131             ast_log(LOG_WARNING, "Asked to execute an AGI on this channel, but could not find application (agi)!\n");
03132       }
03133       qe->handled++;
03134       ast_queue_log(queuename, qe->chan->uniqueid, member->membername, "CONNECT", "%ld|%s", (long)time(NULL) - qe->start, peer->uniqueid);
03135       if (qe->parent->eventwhencalled)
03136          manager_event(EVENT_FLAG_AGENT, "AgentConnect",
03137                "Queue: %s\r\n"
03138                "Uniqueid: %s\r\n"
03139                "Channel: %s\r\n"
03140                "Member: %s\r\n"
03141                "MemberName: %s\r\n"
03142                "Holdtime: %ld\r\n"
03143                "BridgedChannel: %s\r\n"
03144                "%s",
03145                queuename, qe->chan->uniqueid, peer->name, member->interface, member->membername,
03146                (long)time(NULL) - qe->start, peer->uniqueid,
03147                qe->parent->eventwhencalled == QUEUE_EVENT_VARIABLES ? vars2manager(qe->chan, vars, sizeof(vars)) : "");
03148       ast_copy_string(oldcontext, qe->chan->context, sizeof(oldcontext));
03149       ast_copy_string(oldexten, qe->chan->exten, sizeof(oldexten));
03150       time(&callstart);
03151 
03152       if (member->status == AST_DEVICE_NOT_INUSE)
03153          ast_log(LOG_WARNING, "The device state of this queue member, %s, is still 'Not in Use' when it probably should not be! Please check UPGRADE.txt for correct configuration settings.\n", member->membername);
03154          
03155       transfer_ds = setup_transfer_datastore(qe, member, callstart, callcompletedinsl);
03156       bridge = ast_bridge_call(qe->chan,peer, &bridge_config);
03157 
03158       if (bridge != AST_PBX_KEEPALIVE && !attended_transfer_occurred(qe->chan)) {
03159          struct ast_datastore *tds;
03160          if (strcasecmp(oldcontext, qe->chan->context) || strcasecmp(oldexten, qe->chan->exten)) {
03161             ast_queue_log(queuename, qe->chan->uniqueid, member->membername, "TRANSFER", "%s|%s|%ld|%ld",
03162                qe->chan->exten, qe->chan->context, (long) (callstart - qe->start),
03163                (long) (time(NULL) - callstart));
03164          } else if (qe->chan->_softhangup) {
03165             ast_queue_log(queuename, qe->chan->uniqueid, member->membername, "COMPLETECALLER", "%ld|%ld|%d",
03166                (long) (callstart - qe->start), (long) (time(NULL) - callstart), qe->opos);
03167             if (bridge != AST_PBX_NO_HANGUP_PEER && bridge != AST_PBX_NO_HANGUP_PEER_PARKED && qe->parent->eventwhencalled)
03168                manager_event(EVENT_FLAG_AGENT, "AgentComplete",
03169                      "Queue: %s\r\n"
03170                      "Uniqueid: %s\r\n"
03171                      "Channel: %s\r\n"
03172                      "Member: %s\r\n"
03173                      "MemberName: %s\r\n"
03174                      "HoldTime: %ld\r\n"
03175                      "TalkTime: %ld\r\n"
03176                      "Reason: caller\r\n"
03177                      "%s",
03178                      queuename, qe->chan->uniqueid, peer->name, member->interface, member->membername,
03179                      (long)(callstart - qe->start), (long)(time(NULL) - callstart),
03180                      qe->parent->eventwhencalled == QUEUE_EVENT_VARIABLES ? vars2manager(qe->chan, vars, sizeof(vars)) : "");
03181          } else {
03182             ast_queue_log(queuename, qe->chan->uniqueid, member->membername, "COMPLETEAGENT", "%ld|%ld|%d",
03183                (long) (callstart - qe->start), (long) (time(NULL) - callstart), qe->opos);
03184             if (bridge != AST_PBX_NO_HANGUP_PEER && bridge != AST_PBX_NO_HANGUP_PEER_PARKED && qe->parent->eventwhencalled)
03185                manager_event(EVENT_FLAG_AGENT, "AgentComplete",
03186                      "Queue: %s\r\n"
03187                      "Uniqueid: %s\r\n"
03188                      "Channel: %s\r\n"
03189                      "MemberName: %s\r\n"
03190                      "HoldTime: %ld\r\n"
03191                      "TalkTime: %ld\r\n"
03192                      "Reason: agent\r\n"
03193                      "%s",
03194                      queuename, qe->chan->uniqueid, peer->name, member->membername, (long)(callstart - qe->start),
03195                      (long)(time(NULL) - callstart),
03196                      qe->parent->eventwhencalled == QUEUE_EVENT_VARIABLES ? vars2manager(qe->chan, vars, sizeof(vars)) : "");
03197          }
03198          ast_channel_lock(qe->chan);
03199          if ((tds = ast_channel_datastore_find(qe->chan, &queue_transfer_info, NULL))) {
03200             ast_channel_datastore_remove(qe->chan, tds);
03201          }
03202          ast_channel_unlock(qe->chan);
03203          update_queue(qe->parent, member, callcompletedinsl);
03204       }
03205 
03206       if (transfer_ds) {
03207          ast_channel_datastore_free(transfer_ds);
03208       }
03209       if (bridge != AST_PBX_NO_HANGUP_PEER && bridge != AST_PBX_NO_HANGUP_PEER_PARKED)
03210          ast_hangup(peer);
03211       res = bridge ? bridge : 1;
03212       ao2_ref(member, -1);
03213    }
03214 out:
03215    hangupcalls(outgoing, NULL);
03216 
03217    return res;
03218 }
03219 
03220 static int wait_a_bit(struct queue_ent *qe)
03221 {
03222    /* Don't need to hold the lock while we setup the outgoing calls */
03223    int retrywait = qe->parent->retry * 1000;
03224 
03225    int res = ast_waitfordigit(qe->chan, retrywait);
03226    if (res > 0 && !valid_exit(qe, res))
03227       res = 0;
03228 
03229    return res;
03230 }
03231 
03232 static struct member *interface_exists(struct call_queue *q, const char *interface)
03233 {
03234    struct member *mem;
03235    struct ao2_iterator mem_iter;
03236 
03237    if (!q)
03238       return NULL;
03239 
03240    mem_iter = ao2_iterator_init(q->members, 0);
03241    while ((mem = ao2_iterator_next(&mem_iter))) {
03242       if (!strcasecmp(interface, mem->interface))
03243          return mem;
03244       ao2_ref(mem, -1);
03245    }
03246 
03247    return NULL;
03248 }
03249 
03250 
03251 /* Dump all members in a specific queue to the database
03252  *
03253  * <pm_family>/<queuename> = <interface>;<penalty>;<paused>[|...]
03254  *
03255  */
03256 static void dump_queue_members(struct call_queue *pm_queue)
03257 {
03258    struct member *cur_member;
03259    char value[PM_MAX_LEN];
03260    int value_len = 0;
03261    int res;
03262    struct ao2_iterator mem_iter;
03263 
03264    memset(value, 0, sizeof(value));
03265 
03266    if (!pm_queue)
03267       return;
03268 
03269    mem_iter = ao2_iterator_init(pm_queue->members, 0);
03270    while ((cur_member = ao2_iterator_next(&mem_iter))) {
03271       if (!cur_member->dynamic) {
03272          ao2_ref(cur_member, -1);
03273          continue;
03274       }
03275 
03276       res = snprintf(value + value_len, sizeof(value) - value_len, "%s%s;%d;%d;%s",
03277          value_len ? "|" : "", cur_member->interface, cur_member->penalty, cur_member->paused, cur_member->membername);
03278 
03279       ao2_ref(cur_member, -1);
03280 
03281       if (res != strlen(value + value_len)) {
03282          ast_log(LOG_WARNING, "Could not create persistent member string, out of space\n");
03283          break;
03284       }
03285       value_len += res;
03286    }
03287    
03288    if (value_len && !cur_member) {
03289       if (ast_db_put(pm_family, pm_queue->name, value))
03290          ast_log(LOG_WARNING, "failed to create persistent dynamic entry!\n");
03291    } else
03292       /* Delete the entry if the queue is empty or there is an error */
03293       ast_db_del(pm_family, pm_queue->name);
03294 }
03295 
03296 static int remove_from_queue(const char *queuename, const char *interface)
03297 {
03298    struct call_queue *q;
03299    struct member *mem, tmpmem;
03300    int res = RES_NOSUCHQUEUE;
03301 
03302    ast_copy_string(tmpmem.interface, interface, sizeof(tmpmem.interface));
03303 
03304    AST_LIST_LOCK(&queues);
03305    AST_LIST_TRAVERSE(&queues, q, list) {
03306       ast_mutex_lock(&q->lock);
03307       if (strcmp(q->name, queuename)) {
03308          ast_mutex_unlock(&q->lock);
03309          continue;
03310       }
03311 
03312       if ((mem = ao2_find(q->members, &tmpmem, OBJ_POINTER))) {
03313          /* XXX future changes should beware of this assumption!! */
03314          if (!mem->dynamic) {
03315             res = RES_NOT_DYNAMIC;
03316             ao2_ref(mem, -1);
03317             ast_mutex_unlock(&q->lock);
03318             break;
03319          }
03320          q->membercount--;
03321          manager_event(EVENT_FLAG_AGENT, "QueueMemberRemoved",
03322             "Queue: %s\r\n"
03323             "Location: %s\r\n"
03324             "MemberName: %s\r\n",
03325             q->name, mem->interface, mem->membername);
03326          ao2_unlink(q->members, mem);
03327          ao2_ref(mem, -1);
03328 
03329          if (queue_persistent_members)
03330             dump_queue_members(q);
03331          
03332          res = RES_OKAY;
03333       } else {
03334          res = RES_EXISTS;
03335       }
03336       ast_mutex_unlock(&q->lock);
03337       break;
03338    }
03339 
03340    if (res == RES_OKAY)
03341       remove_from_interfaces(interface);
03342 
03343    AST_LIST_UNLOCK(&queues);
03344 
03345    return res;
03346 }
03347 
03348 
03349 static int add_to_queue(const char *queuename, const char *interface, const char *membername, int penalty, int paused, int dump)
03350 {
03351    struct call_queue *q;
03352    struct member *new_member, *old_member;
03353    int res = RES_NOSUCHQUEUE;
03354 
03355    /* \note Ensure the appropriate realtime queue is loaded.  Note that this
03356     * short-circuits if the queue is already in memory. */
03357    if (!(q = load_realtime_queue(queuename)))
03358       return res;
03359 
03360    AST_LIST_LOCK(&queues);
03361 
03362    ast_mutex_lock(&q->lock);
03363    if ((old_member = interface_exists(q, interface)) == NULL) {
03364       add_to_interfaces(interface);
03365       if ((new_member = create_queue_member(interface, membername, penalty, paused))) {
03366          new_member->dynamic = 1;
03367          ao2_link(q->members, new_member);
03368          q->membercount++;
03369          manager_event(EVENT_FLAG_AGENT, "QueueMemberAdded",
03370             "Queue: %s\r\n"
03371             "Location: %s\r\n"
03372             "MemberName: %s\r\n"
03373             "Membership: %s\r\n"
03374             "Penalty: %d\r\n"
03375             "CallsTaken: %d\r\n"
03376             "LastCall: %d\r\n"
03377             "Status: %d\r\n"
03378             "Paused: %d\r\n",
03379             q->name, new_member->interface, new_member->membername,
03380             "dynamic",
03381             new_member->penalty, new_member->calls, (int) new_member->lastcall,
03382             new_member->status, new_member->paused);
03383          
03384          ao2_ref(new_member, -1);
03385          new_member = NULL;
03386 
03387          if (dump)
03388             dump_queue_members(q);
03389          
03390          res = RES_OKAY;
03391       } else {
03392          res = RES_OUTOFMEMORY;
03393       }
03394    } else {
03395       ao2_ref(old_member, -1);
03396       res = RES_EXISTS;
03397    }
03398    ast_mutex_unlock(&q->lock);
03399    AST_LIST_UNLOCK(&queues);
03400 
03401    return res;
03402 }
03403 
03404 static int set_member_paused(const char *queuename, const char *interface, int paused)
03405 {
03406    int found = 0;
03407    struct call_queue *q;
03408    struct member *mem;
03409 
03410    /* Special event for when all queues are paused - individual events still generated */
03411    /* XXX In all other cases, we use the membername, but since this affects all queues, we cannot */
03412    if (ast_strlen_zero(queuename))
03413       ast_queue_log("NONE", "NONE", interface, (paused ? "PAUSEALL" : "UNPAUSEALL"), "%s", "");
03414 
03415    AST_LIST_LOCK(&queues);
03416    AST_LIST_TRAVERSE(&queues, q, list) {
03417       ast_mutex_lock(&q->lock);
03418       if (ast_strlen_zero(queuename) || !strcasecmp(q->name, queuename)) {
03419          if ((mem = interface_exists(q, interface))) {
03420             found++;
03421             if (mem->paused == paused)
03422                ast_log(LOG_DEBUG, "%spausing already-%spaused queue member %s:%s\n", (paused ? "" : "un"), (paused ? "" : "un"), q->name, interface);
03423             mem->paused = paused;
03424 
03425             if (queue_persistent_members)
03426                dump_queue_members(q);
03427 
03428             if (mem->realtime)
03429                update_realtime_member_field(mem, q->name, "paused", paused ? "1" : "0");
03430 
03431             ast_queue_log(q->name, "NONE", mem->membername, (paused ? "PAUSE" : "UNPAUSE"), "%s", "");
03432 
03433             manager_event(EVENT_FLAG_AGENT, "QueueMemberPaused",
03434                "Queue: %s\r\n"
03435                "Location: %s\r\n"
03436                "MemberName: %s\r\n"
03437                "Paused: %d\r\n",
03438                   q->name, mem->interface, mem->membername, paused);
03439             ao2_ref(mem, -1);
03440          }
03441       }
03442       ast_mutex_unlock(&q->lock);
03443    }
03444    AST_LIST_UNLOCK(&queues);
03445 
03446    return found ? RESULT_SUCCESS : RESULT_FAILURE;
03447 }
03448 
03449 /* Reload dynamic queue members persisted into the astdb */
03450 static void reload_queue_members(void)
03451 {
03452    char *cur_ptr;
03453    char *queue_name;
03454    char *member;
03455    char *interface;
03456    char *membername = NULL;
03457    char *penalty_tok;
03458    int penalty = 0;
03459    char *paused_tok;
03460    int paused = 0;
03461    struct ast_db_entry *db_tree;
03462    struct ast_db_entry *entry;
03463    struct call_queue *cur_queue;
03464    char queue_data[PM_MAX_LEN];
03465 
03466    AST_LIST_LOCK(&queues);
03467 
03468    /* Each key in 'pm_family' is the name of a queue */
03469    db_tree = ast_db_gettree(pm_family, NULL);
03470    for (entry = db_tree; entry; entry = entry->next) {
03471 
03472       queue_name = entry->key + strlen(pm_family) + 2;
03473 
03474       AST_LIST_TRAVERSE(&queues, cur_queue, list) {
03475          ast_mutex_lock(&cur_queue->lock);
03476          if (!strcmp(queue_name, cur_queue->name))
03477             break;
03478          ast_mutex_unlock(&cur_queue->lock);
03479       }
03480       
03481       if (!cur_queue)
03482          cur_queue = load_realtime_queue(queue_name);
03483 
03484       if (!cur_queue) {
03485          /* If the queue no longer exists, remove it from the
03486           * database */
03487          ast_log(LOG_WARNING, "Error loading persistent queue: '%s': it does not exist\n", queue_name);
03488          ast_db_del(pm_family, queue_name);
03489          continue;
03490       } else
03491          ast_mutex_unlock(&cur_queue->lock);
03492 
03493       if (ast_db_get(pm_family, queue_name, queue_data, PM_MAX_LEN))
03494          continue;
03495 
03496       cur_ptr = queue_data;
03497       while ((member = strsep(&cur_ptr, "|"))) {
03498          if (ast_strlen_zero(member))
03499             continue;
03500 
03501          interface = strsep(&member, ";");
03502          penalty_tok = strsep(&member, ";");
03503          paused_tok = strsep(&member, ";");
03504          membername = strsep(&member, ";");
03505 
03506          if (!penalty_tok) {
03507             ast_log(LOG_WARNING, "Error parsing persistent member string for '%s' (penalty)\n", queue_name);
03508             break;
03509          }
03510          penalty = strtol(penalty_tok, NULL, 10);
03511          if (errno == ERANGE) {
03512             ast_log(LOG_WARNING, "Error converting penalty: %s: Out of range.\n", penalty_tok);
03513             break;
03514          }
03515          
03516          if (!paused_tok) {
03517             ast_log(LOG_WARNING, "Error parsing persistent member string for '%s' (paused)\n", queue_name);
03518             break;
03519          }
03520          paused = strtol(paused_tok, NULL, 10);
03521          if ((errno == ERANGE) || paused < 0 || paused > 1) {
03522             ast_log(LOG_WARNING, "Error converting paused: %s: Expected 0 or 1.\n", paused_tok);
03523             break;
03524          }
03525          if (ast_strlen_zero(membername))
03526             membername = interface;
03527 
03528          if (option_debug)
03529             ast_log(LOG_DEBUG, "Reload Members: Queue: %s  Member: %s  Name: %s  Penalty: %d  Paused: %d\n", queue_name, interface, membername, penalty, paused);
03530          
03531          if (add_to_queue(queue_name, interface, membername, penalty, paused, 0) == RES_OUTOFMEMORY) {
03532             ast_log(LOG_ERROR, "Out of Memory when reloading persistent queue member\n");
03533             break;
03534          }
03535       }
03536    }
03537 
03538    AST_LIST_UNLOCK(&queues);
03539    if (db_tree) {
03540       ast_log(LOG_NOTICE, "Queue members successfully reloaded from database.\n");
03541       ast_db_freetree(db_tree);
03542    }
03543 }
03544 
03545 static int pqm_exec(struct ast_channel *chan, void *data)
03546 {
03547    struct ast_module_user *lu;
03548    char *parse;
03549    int priority_jump = 0;
03550    AST_DECLARE_APP_ARGS(args,
03551       AST_APP_ARG(queuename);
03552       AST_APP_ARG(interface);
03553       AST_APP_ARG(options);
03554    );
03555 
03556    if (ast_strlen_zero(data)) {
03557       ast_log(LOG_WARNING, "PauseQueueMember requires an argument ([queuename]|interface[|options])\n");
03558       return -1;
03559    }
03560 
03561    parse = ast_strdupa(data);
03562 
03563    AST_STANDARD_APP_ARGS(args, parse);
03564 
03565    lu = ast_module_user_add(chan);
03566 
03567    if (args.options) {
03568       if (strchr(args.options, 'j'))
03569          priority_jump = 1;
03570    }
03571 
03572    if (ast_strlen_zero(args.interface)) {
03573       ast_log(LOG_WARNING, "Missing interface argument to PauseQueueMember ([queuename]|interface[|options])\n");
03574       ast_module_user_remove(lu);
03575       return -1;
03576    }
03577 
03578    if (set_member_paused(args.queuename, args.interface, 1)) {
03579       ast_log(LOG_WARNING, "Attempt to pause interface %s, not found\n", args.interface);
03580       if (priority_jump || ast_opt_priority_jumping) {
03581          if (ast_goto_if_exists(chan, chan->context, chan->exten, chan->priority + 101)) {
03582             pbx_builtin_setvar_helper(chan, "PQMSTATUS", "NOTFOUND");
03583             ast_module_user_remove(lu);
03584             return 0;
03585          }
03586       }
03587       ast_module_user_remove(lu);
03588       pbx_builtin_setvar_helper(chan, "PQMSTATUS", "NOTFOUND");
03589       return 0;
03590    }
03591 
03592    ast_module_user_remove(lu);
03593    pbx_builtin_setvar_helper(chan, "PQMSTATUS", "PAUSED");
03594 
03595    return 0;
03596 }
03597 
03598 static int upqm_exec(struct ast_channel *chan, void *data)
03599 {
03600    struct ast_module_user *lu;
03601    char *parse;
03602    int priority_jump = 0;
03603    AST_DECLARE_APP_ARGS(args,
03604       AST_APP_ARG(queuename);
03605       AST_APP_ARG(interface);
03606       AST_APP_ARG(options);
03607    );
03608 
03609    if (ast_strlen_zero(data)) {
03610       ast_log(LOG_WARNING, "UnpauseQueueMember requires an argument ([queuename]|interface[|options])\n");
03611       return -1;
03612    }
03613 
03614    parse = ast_strdupa(data);
03615 
03616    AST_STANDARD_APP_ARGS(args, parse);
03617 
03618    lu = ast_module_user_add(chan);
03619 
03620    if (args.options) {
03621       if (strchr(args.options, 'j'))
03622          priority_jump = 1;
03623    }
03624 
03625    if (ast_strlen_zero(args.interface)) {
03626       ast_log(LOG_WARNING, "Missing interface argument to PauseQueueMember ([queuename]|interface[|options])\n");
03627       ast_module_user_remove(lu);
03628       return -1;
03629    }
03630 
03631    if (set_member_paused(args.queuename, args.interface, 0)) {
03632       ast_log(LOG_WARNING, "Attempt to unpause interface %s, not found\n", args.interface);
03633       if (priority_jump || ast_opt_priority_jumping) {
03634          if (ast_goto_if_exists(chan, chan->context, chan->exten, chan->priority + 101)) {
03635             pbx_builtin_setvar_helper(chan, "UPQMSTATUS", "NOTFOUND");
03636             ast_module_user_remove(lu);
03637             return 0;
03638          }
03639       }
03640       ast_module_user_remove(lu);
03641       pbx_builtin_setvar_helper(chan, "UPQMSTATUS", "NOTFOUND");
03642       return 0;
03643    }
03644 
03645    ast_module_user_remove(lu);
03646    pbx_builtin_setvar_helper(chan, "UPQMSTATUS", "UNPAUSED");
03647 
03648    return 0;
03649 }
03650 
03651 static int rqm_exec(struct ast_channel *chan, void *data)
03652 {
03653    int res=-1;
03654    struct ast_module_user *lu;
03655    char *parse, *temppos = NULL;
03656    int priority_jump = 0;
03657    AST_DECLARE_APP_ARGS(args,
03658       AST_APP_ARG(queuename);
03659       AST_APP_ARG(interface);
03660       AST_APP_ARG(options);
03661    );
03662 
03663 
03664    if (ast_strlen_zero(data)) {
03665       ast_log(LOG_WARNING, "RemoveQueueMember requires an argument (queuename[|interface[|options]])\n");
03666       return -1;
03667    }
03668 
03669    parse = ast_strdupa(data);
03670 
03671    AST_STANDARD_APP_ARGS(args, parse);
03672 
03673    lu = ast_module_user_add(chan);
03674 
03675    if (ast_strlen_zero(args.interface)) {
03676       args.interface = ast_strdupa(chan->name);
03677       temppos = strrchr(args.interface, '-');
03678       if (temppos)
03679          *temppos = '\0';
03680    }
03681 
03682    if (args.options) {
03683       if (strchr(args.options, 'j'))
03684          priority_jump = 1;
03685    }
03686 
03687    switch (remove_from_queue(args.queuename, args.interface)) {
03688    case RES_OKAY:
03689       ast_queue_log(args.queuename, chan->uniqueid, args.interface, "REMOVEMEMBER", "%s", "");
03690       ast_log(LOG_NOTICE, "Removed interface '%s' from queue '%s'\n", args.interface, args.queuename);
03691       pbx_builtin_setvar_helper(chan, "RQMSTATUS", "REMOVED");
03692       res = 0;
03693       break;
03694    case RES_EXISTS:
03695       ast_log(LOG_DEBUG, "Unable to remove interface '%s' from queue '%s': Not there\n", args.interface, args.queuename);
03696       if (priority_jump || ast_opt_priority_jumping)
03697          ast_goto_if_exists(chan, chan->context, chan->exten, chan->priority + 101);
03698       pbx_builtin_setvar_helper(chan, "RQMSTATUS", "NOTINQUEUE");
03699       res = 0;
03700       break;
03701    case RES_NOSUCHQUEUE:
03702       ast_log(LOG_WARNING, "Unable to remove interface from queue '%s': No such queue\n", args.queuename);
03703       pbx_builtin_setvar_helper(chan, "RQMSTATUS", "NOSUCHQUEUE");
03704       res = 0;
03705       break;
03706    case RES_NOT_DYNAMIC:
03707       ast_log(LOG_WARNING, "Unable to remove interface from queue '%s': '%s' is not a dynamic member\n", args.queuename, args.interface);
03708       pbx_builtin_setvar_helper(chan, "RQMSTATUS", "NOTDYNAMIC");
03709       res = 0;
03710       break;
03711    }
03712 
03713    ast_module_user_remove(lu);
03714 
03715    return res;
03716 }
03717 
03718 static int aqm_exec(struct ast_channel *chan, void *data)
03719 {
03720    int res=-1;
03721    struct ast_module_user *lu;
03722    char *parse, *temppos = NULL;
03723    int priority_jump = 0;
03724    AST_DECLARE_APP_ARGS(args,
03725       AST_APP_ARG(queuename);
03726       AST_APP_ARG(interface);
03727       AST_APP_ARG(penalty);
03728       AST_APP_ARG(options);
03729       AST_APP_ARG(membername);
03730    );
03731    int penalty = 0;
03732 
03733    if (ast_strlen_zero(data)) {
03734       ast_log(LOG_WARNING, "AddQueueMember requires an argument (queuename[|[interface]|[penalty][|options][|membername]])\n");
03735       return -1;
03736    }
03737 
03738    parse = ast_strdupa(data);
03739 
03740    AST_STANDARD_APP_ARGS(args, parse);
03741 
03742    lu = ast_module_user_add(chan);
03743 
03744    if (ast_strlen_zero(args.interface)) {
03745       args.interface = ast_strdupa(chan->name);
03746       temppos = strrchr(args.interface, '-');
03747       if (temppos)
03748          *temppos = '\0';
03749    }
03750 
03751    if (!ast_strlen_zero(args.penalty)) {
03752       if ((sscanf(args.penalty, "%d", &penalty) != 1) || penalty < 0) {
03753          ast_log(LOG_WARNING, "Penalty '%s' is invalid, must be an integer >= 0\n", args.penalty);
03754          penalty = 0;
03755       }
03756    }
03757    
03758    if (args.options) {
03759       if (strchr(args.options, 'j'))
03760          priority_jump = 1;
03761    }
03762 
03763    switch (add_to_queue(args.queuename, args.interface, args.membername, penalty, 0, queue_persistent_members)) {
03764    case RES_OKAY:
03765       ast_queue_log(args.queuename, chan->uniqueid, args.interface, "ADDMEMBER", "%s", "");
03766       ast_log(LOG_NOTICE, "Added interface '%s' to queue '%s'\n", args.interface, args.queuename);
03767       pbx_builtin_setvar_helper(chan, "AQMSTATUS", "ADDED");
03768       res = 0;
03769       break;
03770    case RES_EXISTS:
03771       ast_log(LOG_WARNING, "Unable to add interface '%s' to queue '%s': Already there\n", args.interface, args.queuename);
03772       if (priority_jump || ast_opt_priority_jumping)
03773          ast_goto_if_exists(chan, chan->context, chan->exten, chan->priority + 101);
03774       pbx_builtin_setvar_helper(chan, "AQMSTATUS", "MEMBERALREADY");
03775       res = 0;
03776       break;
03777    case RES_NOSUCHQUEUE:
03778       ast_log(LOG_WARNING, "Unable to add interface to queue '%s': No such queue\n", args.queuename);
03779       pbx_builtin_setvar_helper(chan, "AQMSTATUS", "NOSUCHQUEUE");
03780       res = 0;
03781       break;
03782    case RES_OUTOFMEMORY:
03783       ast_log(LOG_ERROR, "Out of memory adding member %s to queue %s\n", args.interface, args.queuename);
03784       break;
03785    }
03786 
03787    ast_module_user_remove(lu);
03788 
03789    return res;
03790 }
03791 
03792 static int ql_exec(struct ast_channel *chan, void *data)
03793 {
03794    struct ast_module_user *u;
03795    char *parse;
03796 
03797    AST_DECLARE_APP_ARGS(args,
03798       AST_APP_ARG(queuename);
03799       AST_APP_ARG(uniqueid);
03800       AST_APP_ARG(membername);
03801       AST_APP_ARG(event);
03802       AST_APP_ARG(params);
03803    );
03804 
03805    if (ast_strlen_zero(data)) {
03806       ast_log(LOG_WARNING, "QueueLog requires arguments (queuename|uniqueid|membername|event[|additionalinfo]\n");
03807       return -1;
03808    }
03809 
03810    u = ast_module_user_add(chan);
03811 
03812    parse = ast_strdupa(data);
03813 
03814    AST_STANDARD_APP_ARGS(args, parse);
03815 
03816    if (ast_strlen_zero(args.queuename) || ast_strlen_zero(args.uniqueid)
03817        || ast_strlen_zero(args.membername) || ast_strlen_zero(args.event)) {
03818       ast_log(LOG_WARNING, "QueueLog requires arguments (queuename|uniqueid|membername|event[|additionalinfo])\n");
03819       ast_module_user_remove(u);
03820       return -1;
03821    }
03822 
03823    ast_queue_log(args.queuename, args.uniqueid, args.membername, args.event, 
03824       "%s", args.params ? args.params : "");
03825 
03826    ast_module_user_remove(u);
03827 
03828    return 0;
03829 }
03830 
03831 /*!\brief The starting point for all queue calls
03832  *
03833  * The process involved here is to 
03834  * 1. Parse the options specified in the call to Queue()
03835  * 2. Join the queue
03836  * 3. Wait in a loop until it is our turn to try calling a queue member
03837  * 4. Attempt to call a queue member
03838  * 5. If 4. did not result in a bridged call, then check for between
03839  *    call options such as periodic announcements etc.
03840  * 6. Try 4 again uless some condition (such as an expiration time) causes us to 
03841  *    exit the queue.
03842  */
03843 static int queue_exec(struct ast_channel *chan, void *data)
03844 {
03845    int res=-1;
03846    int ringing=0;
03847    struct ast_module_user *lu;
03848    const char *user_priority;
03849    const char *max_penalty_str;
03850    int prio;
03851    int max_penalty;
03852    enum queue_result reason = QUEUE_UNKNOWN;
03853    /* whether to exit Queue application after the timeout hits */
03854    int tries = 0;
03855    int noption = 0;
03856    char *parse;
03857    AST_DECLARE_APP_ARGS(args,
03858       AST_APP_ARG(queuename);
03859       AST_APP_ARG(options);
03860       AST_APP_ARG(url);
03861       AST_APP_ARG(announceoverride);
03862       AST_APP_ARG(queuetimeoutstr);
03863       AST_APP_ARG(agi);
03864    );
03865    /* Our queue entry */
03866    struct queue_ent qe;
03867    
03868    if (ast_strlen_zero(data)) {
03869       ast_log(LOG_WARNING, "Queue requires an argument: queuename[|options[|URL[|announceoverride[|timeout[|agi]]]]]\n");
03870       return -1;
03871    }
03872    
03873    parse = ast_strdupa(data);
03874    AST_STANDARD_APP_ARGS(args, parse);
03875 
03876    lu = ast_module_user_add(chan);
03877 
03878    /* Setup our queue entry */
03879    memset(&qe, 0, sizeof(qe));
03880    qe.start = time(NULL);
03881 
03882    /* set the expire time based on the supplied timeout; */
03883    if (!ast_strlen_zero(args.queuetimeoutstr))
03884       qe.expire = qe.start + atoi(args.queuetimeoutstr);
03885    else
03886       qe.expire = 0;
03887 
03888    /* Get the priority from the variable ${QUEUE_PRIO} */
03889    user_priority = pbx_builtin_getvar_helper(chan, "QUEUE_PRIO");
03890    if (user_priority) {
03891       if (sscanf(user_priority, "%d", &prio) == 1) {
03892          if (option_debug)
03893             ast_log(LOG_DEBUG, "%s: Got priority %d from ${QUEUE_PRIO}.\n",
03894                chan->name, prio);
03895       } else {
03896          ast_log(LOG_WARNING, "${QUEUE_PRIO}: Invalid value (%s), channel %s.\n",
03897             user_priority, chan->name);
03898          prio = 0;
03899       }
03900    } else {
03901       if (option_debug > 2)
03902          ast_log(LOG_DEBUG, "NO QUEUE_PRIO variable found. Using default.\n");
03903       prio = 0;
03904    }
03905 
03906    /* Get the maximum penalty from the variable ${QUEUE_MAX_PENALTY} */
03907    if ((max_penalty_str = pbx_builtin_getvar_helper(chan, "QUEUE_MAX_PENALTY"))) {
03908       if (sscanf(max_penalty_str, "%d", &max_penalty) == 1) {
03909          if (option_debug)
03910             ast_log(LOG_DEBUG, "%s: Got max penalty %d from ${QUEUE_MAX_PENALTY}.\n",
03911                chan->name, max_penalty);
03912       } else {
03913          ast_log(LOG_WARNING, "${QUEUE_MAX_PENALTY}: Invalid value (%s), channel %s.\n",
03914             max_penalty_str, chan->name);
03915          max_penalty = 0;
03916       }
03917    } else {
03918       max_penalty = 0;
03919    }
03920 
03921    if (args.options && (strchr(args.options, 'r')))
03922       ringing = 1;
03923 
03924    if (option_debug)
03925       ast_log(LOG_DEBUG, "queue: %s, options: %s, url: %s, announce: %s, expires: %ld, priority: %d\n",
03926          args.queuename, args.options, args.url, args.announceoverride, (long)qe.expire, prio);
03927 
03928    qe.chan = chan;
03929    qe.prio = prio;
03930    qe.max_penalty = max_penalty;
03931    qe.last_pos_said = 0;
03932    qe.last_pos = 0;
03933    qe.last_periodic_announce_time = time(NULL);
03934    qe.last_periodic_announce_sound = 0;
03935    qe.valid_digits = 0;
03936    if (!join_queue(args.queuename, &qe, &reason)) {
03937       int makeannouncement = 0;
03938 
03939       ast_queue_log(args.queuename, chan->uniqueid, "NONE", "ENTERQUEUE", "%s|%s", S_OR(args.url, ""),
03940          S_OR(chan->cid.cid_num, ""));
03941 check_turns:
03942       if (ringing) {
03943          ast_indicate(chan, AST_CONTROL_RINGING);
03944       } else {
03945          ast_moh_start(chan, qe.moh, NULL);
03946       }
03947 
03948       /* This is the wait loop for callers 2 through maxlen */
03949       res = wait_our_turn(&qe, ringing, &reason);
03950       if (res)
03951          goto stop;
03952 
03953       for (;;) {
03954          /* This is the wait loop for the head caller*/
03955          /* To exit, they may get their call answered; */
03956          /* they may dial a digit from the queue context; */
03957          /* or, they may timeout. */
03958 
03959          enum queue_member_status stat;
03960 
03961          /* Leave if we have exceeded our queuetimeout */
03962          if (qe.expire && (time(NULL) >= qe.expire)) {
03963             record_abandoned(&qe);
03964             reason = QUEUE_TIMEOUT;
03965             res = 0;
03966             ast_queue_log(args.queuename, chan->uniqueid, "NONE", "EXITWITHTIMEOUT", "%d", qe.pos);
03967             break;
03968          }
03969 
03970          if (makeannouncement) {
03971             /* Make a position announcement, if enabled */
03972             if (qe.parent->announcefrequency && !ringing)
03973                if ((res = say_position(&qe)))
03974                   goto stop;
03975 
03976          }
03977          makeannouncement = 1;
03978 
03979          /* Leave if we have exceeded our queuetimeout */
03980          if (qe.expire && (time(NULL) >= qe.expire)) {
03981             record_abandoned(&qe);
03982             reason = QUEUE_TIMEOUT;
03983             res = 0;
03984             ast_queue_log(args.queuename, chan->uniqueid, "NONE", "EXITWITHTIMEOUT", "%d", qe.pos);
03985             break;
03986          }
03987          /* Make a periodic announcement, if enabled */
03988          if (qe.parent->periodicannouncefrequency && !ringing)
03989             if ((res = say_periodic_announcement(&qe)))
03990                goto stop;
03991 
03992          /* Leave if we have exceeded our queuetimeout */
03993          if (qe.expire && (time(NULL) >= qe.expire)) {
03994             record_abandoned(&qe);
03995             reason = QUEUE_TIMEOUT;
03996             res = 0;
03997             ast_queue_log(args.queuename, chan->uniqueid, "NONE", "EXITWITHTIMEOUT", "%d", qe.pos);
03998             break;
03999          }
04000          /* Try calling all queue members for 'timeout' seconds */
04001          res = try_calling(&qe, args.options, args.announceoverride, args.url, &tries, &noption, args.agi);
04002          if (res)
04003             goto stop;
04004 
04005          stat = get_member_status(qe.parent, qe.max_penalty);
04006 
04007          /* exit after 'timeout' cycle if 'n' option enabled */
04008          if (noption && tries >= qe.parent->membercount) {
04009             if (option_verbose > 2)
04010                ast_verbose(VERBOSE_PREFIX_3 "Exiting on time-out cycle\n");
04011             ast_queue_log(args.queuename, chan->uniqueid, "NONE", "EXITWITHTIMEOUT", "%d", qe.pos);
04012             record_abandoned(&qe);
04013             reason = QUEUE_TIMEOUT;
04014             res = 0;
04015             break;
04016          }
04017 
04018          /* leave the queue if no agents, if enabled */
04019          if (qe.parent->leavewhenempty && (stat == QUEUE_NO_MEMBERS)) {
04020             record_abandoned(&qe);
04021             reason = QUEUE_LEAVEEMPTY;
04022             ast_queue_log(args.queuename, chan->uniqueid, "NONE", "EXITEMPTY", "%d|%d|%ld", qe.pos, qe.opos, (long)(time(NULL) - qe.start));
04023             res = 0;
04024             break;
04025          }
04026 
04027          /* leave the queue if no reachable agents, if enabled */
04028          if ((qe.parent->leavewhenempty == QUEUE_EMPTY_STRICT) && (stat == QUEUE_NO_REACHABLE_MEMBERS)) {
04029             record_abandoned(&qe);
04030             reason = QUEUE_LEAVEUNAVAIL;
04031             ast_queue_log(args.queuename, chan->uniqueid, "NONE", "EXITEMPTY", "%d|%d|%ld", qe.pos, qe.opos, (long)(time(NULL) - qe.start));
04032             res = 0;
04033             break;
04034          }
04035 
04036          /* Leave if we have exceeded our queuetimeout */
04037          if (qe.expire && (time(NULL) >= qe.expire)) {
04038             record_abandoned(&qe);
04039             reason = QUEUE_TIMEOUT;
04040             res = 0;
04041             ast_queue_log(args.queuename, chan->uniqueid, "NONE", "EXITWITHTIMEOUT", "%d", qe.pos);
04042             break;
04043          }
04044 
04045          /* If using dynamic realtime members, we should regenerate the member list for this queue */
04046          update_realtime_members(qe.parent);
04047 
04048          /* OK, we didn't get anybody; wait for 'retry' seconds; may get a digit to exit with */
04049          res = wait_a_bit(&qe);
04050          if (res)
04051             goto stop;
04052 
04053          /* Since this is a priority queue and
04054           * it is not sure that we are still at the head
04055           * of the queue, go and check for our turn again.
04056           */
04057          if (!is_our_turn(&qe)) {
04058             if (option_debug)
04059                ast_log(LOG_DEBUG, "Darn priorities, going back in queue (%s)!\n",
04060                   qe.chan->name);
04061             goto check_turns;
04062          }
04063       }
04064 
04065 stop:
04066       if (res) {
04067          if (res < 0) {
04068             if (!qe.handled) {
04069                record_abandoned(&qe);
04070                ast_queue_log(args.queuename, chan->uniqueid, "NONE", "ABANDON",
04071                   "%d|%d|%ld", qe.pos, qe.opos,
04072                   (long) time(NULL) - qe.start);
04073             }
04074             res = -1;
04075          } else if (qe.valid_digits) {
04076             ast_queue_log(args.queuename, chan->uniqueid, "NONE", "EXITWITHKEY",
04077                "%s|%d", qe.digits, qe.pos);
04078          }
04079       }
04080 
04081       /* Don't allow return code > 0 */
04082       if (res >= 0 && res != AST_PBX_KEEPALIVE) {
04083          res = 0; 
04084          if (ringing) {
04085             ast_indicate(chan, -1);
04086          } else {
04087             ast_moh_stop(chan);
04088          }        
04089          ast_stopstream(chan);
04090       }
04091       leave_queue(&qe);
04092       if (reason != QUEUE_UNKNOWN)
04093          set_queue_result(chan, reason);
04094    } else {
04095       ast_log(LOG_WARNING, "Unable to join queue '%s'\n", args.queuename);
04096       set_queue_result(chan, reason);
04097       res = 0;
04098    }
04099    ast_module_user_remove(lu);
04100 
04101    return res;
04102 }
04103 
04104 static int queue_function_qac(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len)
04105 {
04106    int count = 0;
04107    struct call_queue *q;
04108    struct ast_module_user *lu;
04109    struct member *m;
04110    struct ao2_iterator mem_iter;
04111 
04112    buf[0] = '\0';
04113    
04114    if (ast_strlen_zero(data)) {
04115       ast_log(LOG_ERROR, "%s requires an argument: queuename\n", cmd);
04116       return -1;
04117    }
04118 
04119    lu = ast_module_user_add(chan);
04120 
04121    if ((q = load_realtime_queue(data))) {
04122       ast_mutex_lock(&q->lock);
04123       mem_iter = ao2_iterator_init(q->members, 0);
04124       while ((m = ao2_iterator_next(&mem_iter))) {
04125          /* Count the agents who are logged in and presently answering calls */
04126          if ((m->status != AST_DEVICE_UNAVAILABLE) && (m->status != AST_DEVICE_INVALID)) {
04127             count++;
04128          }
04129          ao2_ref(m, -1);
04130       }
04131       ast_mutex_unlock(&q->lock);
04132    } else
04133       ast_log(LOG_WARNING, "queue %s was not found\n", data);
04134 
04135    snprintf(buf, len, "%d", count);
04136    ast_module_user_remove(lu);
04137 
04138    return 0;
04139 }
04140 
04141 static int queue_function_queuewaitingcount(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len)
04142 {
04143    int count = 0;
04144    struct call_queue *q;
04145    struct ast_module_user *lu;
04146    struct ast_variable *var = NULL;
04147 
04148    buf[0] = '\0';
04149    
04150    if (ast_strlen_zero(data)) {
04151       ast_log(LOG_ERROR, "%s requires an argument: queuename\n", cmd);
04152       return -1;
04153    }
04154 
04155    lu = ast_module_user_add(chan);
04156    
04157    AST_LIST_LOCK(&queues);
04158    AST_LIST_TRAVERSE(&queues, q, list) {
04159       if (!strcasecmp(q->name, data)) {
04160          ast_mutex_lock(&q->lock);
04161          break;
04162       }
04163    }
04164    AST_LIST_UNLOCK(&queues);
04165 
04166    if (q) {
04167       count = q->count;
04168       ast_mutex_unlock(&q->lock);
04169    } else if ((var = ast_load_realtime("queues", "name", data, NULL))) {
04170       /* if the queue is realtime but was not found in memory, this
04171        * means that the queue had been deleted from memory since it was 
04172        * "dead." This means it has a 0 waiting count
04173        */
04174       count = 0;
04175       ast_variables_destroy(var);
04176    } else
04177       ast_log(LOG_WARNING, "queue %s was not found\n", data);
04178 
04179    snprintf(buf, len, "%d", count);
04180    ast_module_user_remove(lu);
04181    return 0;
04182 }
04183 
04184 static int queue_function_queuememberlist(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len)
04185 {
04186    struct ast_module_user *u;
04187    struct call_queue *q;
04188    struct member *m;
04189 
04190    /* Ensure an otherwise empty list doesn't return garbage */
04191    buf[0] = '\0';
04192 
04193    if (ast_strlen_zero(data)) {
04194       ast_log(LOG_ERROR, "QUEUE_MEMBER_LIST requires an argument: queuename\n");
04195       return -1;
04196    }
04197    
04198    u = ast_module_user_add(chan);
04199 
04200    AST_LIST_LOCK(&queues);
04201    AST_LIST_TRAVERSE(&queues, q, list) {
04202       if (!strcasecmp(q->name, data)) {
04203          ast_mutex_lock(&q->lock);
04204          break;
04205       }
04206    }
04207    AST_LIST_UNLOCK(&queues);
04208 
04209    if (q) {
04210       int buflen = 0, count = 0;
04211       struct ao2_iterator mem_iter = ao2_iterator_init(q->members, 0);
04212 
04213       while ((m = ao2_iterator_next(&mem_iter))) {
04214          /* strcat() is always faster than printf() */
04215          if (count++) {
04216             strncat(buf + buflen, ",", len - buflen - 1);
04217             buflen++;
04218          }
04219          strncat(buf + buflen, m->membername, len - buflen - 1);
04220          buflen += strlen(m->membername);
04221          /* Safeguard against overflow (negative length) */
04222          if (buflen >= len - 2) {
04223             ao2_ref(m, -1);
04224             ast_log(LOG_WARNING, "Truncating list\n");
04225             break;
04226          }
04227          ao2_ref(m, -1);
04228       }
04229       ast_mutex_unlock(&q->lock);
04230    } else
04231       ast_log(LOG_WARNING, "queue %s was not found\n", data);
04232 
04233    /* We should already be terminated, but let's make sure. */
04234    buf[len - 1] = '\0';
04235    ast_module_user_remove(u);
04236 
04237    return 0;
04238 }
04239 
04240 static struct ast_custom_function queueagentcount_function = {
04241    .name = "QUEUEAGENTCOUNT",
04242    .synopsis = "Count number of agents answering a queue",
04243    .syntax = "QUEUEAGENTCOUNT(<queuename>)",
04244    .desc =
04245 "Returns the number of members currently associated with the specified queue.\n"
04246 "This function is deprecated.  You should use QUEUE_MEMBER_COUNT() instead.\n",
04247    .read = queue_function_qac,
04248 };
04249 
04250 static struct ast_custom_function queuemembercount_function = {
04251    .name = "QUEUE_MEMBER_COUNT",
04252    .synopsis = "Count number of members answering a queue",
04253    .syntax = "QUEUE_MEMBER_COUNT(<queuename>)",
04254    .desc =
04255 "Returns the number of members currently associated with the specified queue.\n",
04256    .read = queue_function_qac,
04257 };
04258 
04259 static struct ast_custom_function queuewaitingcount_function = {
04260    .name = "QUEUE_WAITING_COUNT",
04261    .synopsis = "Count number of calls currently waiting in a queue",
04262    .syntax = "QUEUE_WAITING_COUNT(<queuename>)",
04263    .desc =
04264 "Returns the number of callers currently waiting in the specified queue.\n",
04265    .read = queue_function_queuewaitingcount,
04266 };
04267 
04268 static struct ast_custom_function queuememberlist_function = {
04269    .name = "QUEUE_MEMBER_LIST",
04270    .synopsis = "Returns a list of interfaces on a queue",
04271    .syntax = "QUEUE_MEMBER_LIST(<queuename>)",
04272    .desc =
04273 "Returns a comma-separated list of members associated with the specified queue.\n",
04274    .read = queue_function_queuememberlist,
04275 };
04276 
04277 static int reload_queues(void)
04278 {
04279    struct call_queue *q;
04280    struct ast_config *cfg;
04281    char *cat, *tmp;
04282    struct ast_variable *var;
04283    struct member *cur, *newm;
04284    struct ao2_iterator mem_iter;
04285    int new;
04286    const char *general_val = NULL;
04287    char parse[80];
04288    char *interface;
04289    char *membername = NULL;
04290    int penalty;
04291    AST_DECLARE_APP_ARGS(args,
04292       AST_APP_ARG(interface);
04293       AST_APP_ARG(penalty);
04294       AST_APP_ARG(membername);
04295    );
04296    
04297    if (!(cfg = ast_config_load("queues.conf"))) {
04298       ast_log(LOG_NOTICE, "No call queueing config file (queues.conf), so no call queues\n");
04299       return 0;
04300    }
04301    AST_LIST_LOCK(&queues);
04302    use_weight=0;
04303    /* Mark all non-realtime queues as dead for the moment */
04304    AST_LIST_TRAVERSE(&queues, q, list) {
04305       if (!q->realtime) {
04306          q->dead = 1;
04307          q->found = 0;
04308       }
04309    }
04310 
04311    /* Chug through config file */
04312    cat = NULL;
04313    while ((cat = ast_category_browse(cfg, cat)) ) {
04314       if (!strcasecmp(cat, "general")) {  
04315          /* Initialize global settings */
04316          queue_persistent_members = 0;
04317          if ((general_val = ast_variable_retrieve(cfg, "general", "persistentmembers")))
04318             queue_persistent_members = ast_true(general_val);
04319          autofill_default = 0;
04320          if ((general_val = ast_variable_retrieve(cfg, "general", "autofill")))
04321             autofill_default = ast_true(general_val);
04322          montype_default = 0;
04323          if ((general_val = ast_variable_retrieve(cfg, "general", "monitor-type")))
04324             if (!strcasecmp(general_val, "mixmonitor"))
04325                montype_default = 1;
04326       } else { /* Define queue */
04327          /* Look for an existing one */
04328          AST_LIST_TRAVERSE(&queues, q, list) {
04329             if (!strcmp(q->name, cat))
04330                break;
04331          }
04332          if (!q) {
04333             /* Make one then */
04334             if (!(q = alloc_queue(cat))) {
04335                /* TODO: Handle memory allocation failure */
04336             }
04337             new = 1;
04338          } else
04339             new = 0;
04340          if (q) {
04341             if (!new)
04342                ast_mutex_lock(&q->lock);
04343             /* Check if a queue with this name already exists */
04344             if (q->found) {
04345                ast_log(LOG_WARNING, "Queue '%s' already defined! Skipping!\n", cat);
04346                if (!new)
04347                   ast_mutex_unlock(&q->lock);
04348                continue;
04349             }
04350             /* Re-initialize the queue, and clear statistics */
04351             init_queue(q);
04352             clear_queue(q);
04353             mem_iter = ao2_iterator_init(q->members, 0);
04354             while ((cur = ao2_iterator_next(&mem_iter))) {
04355                if (!cur->dynamic) {
04356                   cur->delme = 1;
04357                }
04358                ao2_ref(cur, -1);
04359             }
04360             for (var = ast_variable_browse(cfg, cat); var; var = var->next) {
04361                if (!strcasecmp(var->name, "member")) {
04362                   struct member tmpmem;
04363                   membername = NULL;
04364 
04365                   /* Add a new member */
04366                   ast_copy_string(parse, var->value, sizeof(parse));
04367                   
04368                   AST_NONSTANDARD_APP_ARGS(args, parse, ',');
04369 
04370                   interface = args.interface;
04371                   if (!ast_strlen_zero(args.penalty)) {
04372                      tmp = args.penalty;
04373                      while (*tmp && *tmp < 33) tmp++;
04374                      penalty = atoi(tmp);
04375                      if (penalty < 0) {
04376                         penalty = 0;
04377                      }
04378                   } else
04379                      penalty = 0;
04380 
04381                   if (!ast_strlen_zero(args.membername)) {
04382                      membername = args.membername;
04383                      while (*membername && *membername < 33) membername++;
04384                   }
04385 
04386                   /* Find the old position in the list */
04387                   ast_copy_string(tmpmem.interface, interface, sizeof(tmpmem.interface));
04388                   cur = ao2_find(q->members, &tmpmem, OBJ_POINTER | OBJ_UNLINK);
04389 
04390                   newm = create_queue_member(interface, membername, penalty, cur ? cur->paused : 0);
04391                   ao2_link(q->members, newm);
04392                   ao2_ref(newm, -1);
04393                   newm = NULL;
04394 
04395                   if (cur)
04396                      ao2_ref(cur, -1);
04397                   else {
04398                      /* Add them to the master int list if necessary */
04399                      add_to_interfaces(interface);
04400                      q->membercount++;
04401                   }
04402                } else {
04403                   queue_set_param(q, var->name, var->value, var->lineno, 1);
04404                }
04405             }
04406 
04407             /* Free remaining members marked as delme */
04408             mem_iter = ao2_iterator_init(q->members, 0);
04409             while ((cur = ao2_iterator_next(&mem_iter))) {
04410                if (! cur->delme) {
04411                   ao2_ref(cur, -1);
04412                   continue;
04413                }
04414 
04415                q->membercount--;
04416                ao2_unlink(q->members, cur);
04417                remove_from_interfaces(cur->interface);
04418                ao2_ref(cur, -1);
04419             }
04420 
04421             if (q->strategy == QUEUE_STRATEGY_ROUNDROBIN)
04422                rr_dep_warning();
04423 
04424             if (new) {
04425                AST_LIST_INSERT_HEAD(&queues, q, list);
04426             } else
04427                ast_mutex_unlock(&q->lock);
04428          }
04429       }
04430    }
04431    ast_config_destroy(cfg);
04432    AST_LIST_TRAVERSE_SAFE_BEGIN(&queues, q, list) {
04433       if (q->dead) {
04434          AST_LIST_REMOVE_CURRENT(&queues, list);
04435          if (!q->count)
04436             destroy_queue(q);
04437          else
04438             ast_log(LOG_DEBUG, "XXX Leaking a little memory :( XXX\n");
04439       } else {
04440          ast_mutex_lock(&q->lock);
04441          mem_iter = ao2_iterator_init(q->members, 0);
04442          while ((cur = ao2_iterator_next(&mem_iter))) {
04443             if (cur->dynamic)
04444                q->membercount++;
04445             cur->status = ast_device_state(cur->interface);
04446             ao2_ref(cur, -1);
04447          }
04448          ast_mutex_unlock(&q->lock);
04449       }
04450    }
04451    AST_LIST_TRAVERSE_SAFE_END;
04452    AST_LIST_UNLOCK(&queues);
04453    return 1;
04454 }
04455 
04456 static int __queues_show(struct mansession *s, int manager, int fd, int argc, char **argv)
04457 {
04458    struct call_queue *q;
04459    struct queue_ent *qe;
04460    struct member *mem;
04461    int pos, queue_show;
04462    time_t now;
04463    char max_buf[150];
04464    char *max;
04465    size_t max_left;
04466    float sl = 0;
04467    char *term = manager ? "\r\n" : "\n";
04468    struct ao2_iterator mem_iter;
04469 
04470    time(&now);
04471    if (argc == 2)
04472       queue_show = 0;
04473    else if (argc == 3)
04474       queue_show = 1;
04475    else
04476       return RESULT_SHOWUSAGE;
04477 
04478    /* We only want to load realtime queues when a specific queue is asked for. */
04479    if (queue_show) {
04480       load_realtime_queue(argv[2]);
04481    } else if (ast_check_realtime("queues")) {
04482       struct ast_config *cfg = ast_load_realtime_multientry("queues", "name LIKE", "%", (char *) NULL);
04483       char *queuename;
04484       if (cfg) {
04485          for (queuename = ast_category_browse(cfg, NULL); !ast_strlen_zero(queuename); queuename = ast_category_browse(cfg, queuename)) {
04486             load_realtime_queue(queuename);
04487          }
04488          ast_config_destroy(cfg);
04489       }
04490    }
04491 
04492    AST_LIST_LOCK(&queues);
04493    if (AST_LIST_EMPTY(&queues)) {
04494       AST_LIST_UNLOCK(&queues);
04495       if (queue_show) {
04496          if (s)
04497             astman_append(s, "No such queue: %s.%s",argv[2], term);
04498          else
04499             ast_cli(fd, "No such queue: %s.%s",argv[2], term);
04500       } else {
04501          if (s)
04502             astman_append(s, "No queues.%s", term);
04503          else
04504             ast_cli(fd, "No queues.%s", term);
04505       }
04506       return RESULT_SUCCESS;
04507    }
04508    AST_LIST_TRAVERSE(&queues, q, list) {
04509       ast_mutex_lock(&q->lock);
04510       if (queue_show) {
04511          if (strcasecmp(q->name, argv[2]) != 0) {
04512             ast_mutex_unlock(&q->lock);
04513             if (!AST_LIST_NEXT(q, list)) {
04514                ast_cli(fd, "No such queue: %s.%s",argv[2], term);
04515                break;
04516             }
04517             continue;
04518          }
04519       }
04520       max_buf[0] = '\0';
04521       max = max_buf;
04522       max_left = sizeof(max_buf);
04523       if (q->maxlen)
04524          ast_build_string(&max, &max_left, "%d", q->maxlen);
04525       else
04526          ast_build_string(&max, &max_left, "unlimited");
04527       sl = 0;
04528       if (q->callscompleted > 0)
04529          sl = 100 * ((float) q->callscompletedinsl / (float) q->callscompleted);
04530       if (s)
04531          astman_append(s, "%-12.12s has %d calls (max %s) in '%s' strategy (%ds holdtime), W:%d, C:%d, A:%d, SL:%2.1f%% within %ds%s",
04532             q->name, q->count, max_buf, int2strat(q->strategy), q->holdtime, q->weight,
04533             q->callscompleted, q->callsabandoned,sl,q->servicelevel, term);
04534       else
04535          ast_cli(fd, "%-12.12s has %d calls (max %s) in '%s' strategy (%ds holdtime), W:%d, C:%d, A:%d, SL:%2.1f%% within %ds%s",
04536             q->name, q->count, max_buf, int2strat(q->strategy), q->holdtime, q->weight, q->callscompleted, q->callsabandoned,sl,q->servicelevel, term);
04537       if (ao2_container_count(q->members)) {
04538          if (s)
04539             astman_append(s, "   Members: %s", term);
04540          else
04541             ast_cli(fd, "   Members: %s", term);
04542          mem_iter = ao2_iterator_init(q->members, 0);
04543          while ((mem = ao2_iterator_next(&mem_iter))) {
04544             max_buf[0] = '\0';
04545             max = max_buf;
04546             max_left = sizeof(max_buf);
04547             if (strcasecmp(mem->membername, mem->interface)) {
04548                ast_build_string(&max, &max_left, " (%s)", mem->interface);
04549             }
04550             if (mem->penalty)
04551                ast_build_string(&max, &max_left, " with penalty %d", mem->penalty);
04552             if (mem->dynamic)
04553                ast_build_string(&max, &max_left, " (dynamic)");
04554             if (mem->realtime)
04555                ast_build_string(&max, &max_left, " (realtime)");
04556             if (mem->paused)
04557                ast_build_string(&max, &max_left, " (paused)");
04558             ast_build_string(&max, &max_left, " (%s)", devstate2str(mem->status));
04559             if (mem->calls) {
04560                ast_build_string(&max, &max_left, " has taken %d calls (last was %ld secs ago)",
04561                   mem->calls, (long) (time(NULL) - mem->lastcall));
04562             } else
04563                ast_build_string(&max, &max_left, " has taken no calls yet");
04564             if (s)
04565                astman_append(s, "      %s%s%s", mem->membername, max_buf, term);
04566             else
04567                ast_cli(fd, "      %s%s%s", mem->membername, max_buf, term);
04568             ao2_ref(mem, -1);
04569          }
04570       } else if (s)
04571          astman_append(s, "   No Members%s", term);
04572       else  
04573          ast_cli(fd, "   No Members%s", term);
04574       if (q->head) {
04575          pos = 1;
04576          if (s)
04577             astman_append(s, "   Callers: %s", term);
04578          else
04579             ast_cli(fd, "   Callers: %s", term);
04580          for (qe = q->head; qe; qe = qe->next) {
04581             if (s)
04582                astman_append(s, "      %d. %s (wait: %ld:%2.2ld, prio: %d)%s",
04583                   pos++, qe->chan->name, (long) (now - qe->start) / 60,
04584                   (long) (now - qe->start) % 60, qe->prio, term);
04585             else
04586                ast_cli(fd, "      %d. %s (wait: %ld:%2.2ld, prio: %d)%s", pos++,
04587                   qe->chan->name, (long) (now - qe->start) / 60,
04588                   (long) (now - qe->start) % 60, qe->prio, term);
04589          }
04590       } else if (s)
04591          astman_append(s, "   No Callers%s", term);
04592       else
04593          ast_cli(fd, "   No Callers%s", term);
04594       if (s)
04595          astman_append(s, "%s", term);
04596       else
04597          ast_cli(fd, "%s", term);
04598       ast_mutex_unlock(&q->lock);
04599       if (queue_show)
04600          break;
04601    }
04602    AST_LIST_UNLOCK(&queues);
04603    return RESULT_SUCCESS;
04604 }
04605 
04606 static int queue_show(int fd, int argc, char **argv)
04607 {
04608    return __queues_show(NULL, 0, fd, argc, argv);
04609 }
04610 
04611 static char *complete_queue(const char *line, const char *word, int pos, int state)
04612 {
04613    struct call_queue *q;
04614    char *ret = NULL;
04615    int which = 0;
04616    int wordlen = strlen(word);
04617    
04618    AST_LIST_LOCK(&queues);
04619    AST_LIST_TRAVERSE(&queues, q, list) {
04620       if (!strncasecmp(word, q->name, wordlen) && ++which > state) {
04621          ret = ast_strdup(q->name); 
04622          break;
04623       }
04624    }
04625    AST_LIST_UNLOCK(&queues);
04626 
04627    return ret;
04628 }
04629 
04630 static char *complete_queue_show(const char *line, const char *word, int pos, int state)
04631 {
04632    if (pos == 2)
04633       return complete_queue(line, word, pos, state);
04634    return NULL;
04635 }
04636 
04637 /*!\brief callback to display queues status in manager
04638    \addtogroup Group_AMI
04639  */
04640 static int manager_queues_show(struct mansession *s, const struct message *m)
04641 {
04642    char *a[] = { "queue", "show" };
04643 
04644    __queues_show(s, 1, -1, 2, a);
04645    astman_append(s, "\r\n\r\n"); /* Properly terminate Manager output */
04646 
04647    return RESULT_SUCCESS;
04648 }
04649 
04650 /* Dump queue status */
04651 static int manager_queues_status(struct mansession *s, const struct message *m)
04652 {
04653    time_t now;
04654    int pos;
04655    const char *id = astman_get_header(m,"ActionID");
04656    const char *queuefilter = astman_get_header(m,"Queue");
04657    const char *memberfilter = astman_get_header(m,"Member");
04658    char idText[256] = "";
04659    struct call_queue *q;
04660    struct queue_ent *qe;
04661    float sl = 0;
04662    struct member *mem;
04663    struct ao2_iterator mem_iter;
04664 
04665    astman_send_ack(s, m, "Queue status will follow");
04666    time(&now);
04667    AST_LIST_LOCK(&queues);
04668    if (!ast_strlen_zero(id))
04669       snprintf(idText, sizeof(idText), "ActionID: %s\r\n", id);
04670 
04671    AST_LIST_TRAVERSE(&queues, q, list) {
04672       ast_mutex_lock(&q->lock);
04673 
04674       /* List queue properties */
04675       if (ast_strlen_zero(queuefilter) || !strcmp(q->name, queuefilter)) {
04676          sl = ((q->callscompleted > 0) ? 100 * ((float)q->callscompletedinsl / (float)q->callscompleted) : 0);
04677          astman_append(s, "Event: QueueParams\r\n"
04678             "Queue: %s\r\n"
04679             "Max: %d\r\n"
04680             "Calls: %d\r\n"
04681             "Holdtime: %d\r\n"
04682             "Completed: %d\r\n"
04683             "Abandoned: %d\r\n"
04684             "ServiceLevel: %d\r\n"
04685             "ServicelevelPerf: %2.1f\r\n"
04686             "Weight: %d\r\n"
04687             "%s"
04688             "\r\n",
04689             q->name, q->maxlen, q->count, q->holdtime, q->callscompleted,
04690             q->callsabandoned, q->servicelevel, sl, q->weight, idText);
04691          /* List Queue Members */
04692          mem_iter = ao2_iterator_init(q->members, 0);
04693          while ((mem = ao2_iterator_next(&mem_iter))) {
04694             if (ast_strlen_zero(memberfilter) || !strcmp(mem->interface, memberfilter)) {
04695                astman_append(s, "Event: QueueMember\r\n"
04696                   "Queue: %s\r\n"
04697                   "Name: %s\r\n"
04698                   "Location: %s\r\n"
04699                   "Membership: %s\r\n"
04700                   "Penalty: %d\r\n"
04701                   "CallsTaken: %d\r\n"
04702                   "LastCall: %d\r\n"
04703                   "Status: %d\r\n"
04704                   "Paused: %d\r\n"
04705                   "%s"
04706                   "\r\n",
04707                   q->name, mem->membername, mem->interface, mem->dynamic ? "dynamic" : "static",
04708                   mem->penalty, mem->calls, (int)mem->lastcall, mem->status, mem->paused, idText);
04709             }
04710             ao2_ref(mem, -1);
04711          }
04712          /* List Queue Entries */
04713          pos = 1;
04714          for (qe = q->head; qe; qe = qe->next) {
04715             astman_append(s, "Event: QueueEntry\r\n"
04716                "Queue: %s\r\n"
04717                "Position: %d\r\n"
04718                "Channel: %s\r\n"
04719                "CallerID: %s\r\n"
04720                "CallerIDName: %s\r\n"
04721                "Wait: %ld\r\n"
04722                "%s"
04723                "\r\n",
04724                q->name, pos++, qe->chan->name,
04725                S_OR(qe->chan->cid.cid_num, "unknown"),
04726                S_OR(qe->chan->cid.cid_name, "unknown"),
04727                (long) (now - qe->start), idText);
04728          }
04729       }
04730       ast_mutex_unlock(&q->lock);
04731    }
04732 
04733    astman_append(s,
04734       "Event: QueueStatusComplete\r\n"
04735       "%s"
04736       "\r\n",idText);
04737 
04738    AST_LIST_UNLOCK(&queues);
04739 
04740 
04741    return RESULT_SUCCESS;
04742 }
04743 
04744 static int manager_add_queue_member(struct mansession *s, const struct message *m)
04745 {
04746    const char *queuename, *interface, *penalty_s, *paused_s, *membername;
04747    int paused, penalty = 0;
04748 
04749    queuename = astman_get_header(m, "Queue");
04750    interface = astman_get_header(m, "Interface");
04751    penalty_s = astman_get_header(m, "Penalty");
04752    paused_s = astman_get_header(m, "Paused");
04753    membername = astman_get_header(m, "MemberName");
04754 
04755    if (ast_strlen_zero(queuename)) {
04756       astman_send_error(s, m, "'Queue' not specified.");
04757       return 0;
04758    }
04759 
04760    if (ast_strlen_zero(interface)) {
04761       astman_send_error(s, m, "'Interface' not specified.");
04762       return 0;
04763    }
04764 
04765    if (ast_strlen_zero(penalty_s))
04766       penalty = 0;
04767    else if (sscanf(penalty_s, "%d", &penalty) != 1 || penalty < 0)
04768       penalty = 0;
04769 
04770    if (ast_strlen_zero(paused_s))
04771       paused = 0;
04772    else
04773       paused = abs(ast_true(paused_s));
04774 
04775    switch (add_to_queue(queuename, interface, membername, penalty, paused, queue_persistent_members)) {
04776    case RES_OKAY:
04777       ast_queue_log(queuename, "MANAGER", interface, "ADDMEMBER", "%s", "");
04778       astman_send_ack(s, m, "Added interface to queue");
04779       break;
04780    case RES_EXISTS:
04781       astman_send_error(s, m, "Unable to add interface: Already there");
04782       break;
04783    case RES_NOSUCHQUEUE:
04784       astman_send_error(s, m, "Unable to add interface to queue: No such queue");
04785       break;
04786    case RES_OUTOFMEMORY:
04787       astman_send_error(s, m, "Out of memory");
04788       break;
04789    }
04790 
04791    return 0;
04792 }
04793 
04794 static int manager_remove_queue_member(struct mansession *s, const struct message *m)
04795 {
04796    const char *queuename, *interface;
04797 
04798    queuename = astman_get_header(m, "Queue");
04799    interface = astman_get_header(m, "Interface");
04800 
04801    if (ast_strlen_zero(queuename) || ast_strlen_zero(interface)) {
04802       astman_send_error(s, m, "Need 'Queue' and 'Interface' parameters.");
04803       return 0;
04804    }
04805 
04806    switch (remove_from_queue(queuename, interface)) {
04807    case RES_OKAY:
04808       ast_queue_log(queuename, "MANAGER", interface, "REMOVEMEMBER", "%s", "");
04809       astman_send_ack(s, m, "Removed interface from queue");
04810       break;
04811    case RES_EXISTS:
04812       astman_send_error(s, m, "Unable to remove interface: Not there");
04813       break;
04814    case RES_NOSUCHQUEUE:
04815       astman_send_error(s, m, "Unable to remove interface from queue: No such queue");
04816       break;
04817    case RES_OUTOFMEMORY:
04818       astman_send_error(s, m, "Out of memory");
04819       break;
04820    case RES_NOT_DYNAMIC:
04821       astman_send_error(s, m, "Member not dynamic");
04822       break;
04823    }
04824 
04825    return 0;
04826 }
04827 
04828 static int manager_pause_queue_member(struct mansession *s, const struct message *m)
04829 {
04830    const char *queuename, *interface, *paused_s;
04831    int paused;
04832 
04833    interface = astman_get_header(m, "Interface");
04834    paused_s = astman_get_header(m, "Paused");
04835    queuename = astman_get_header(m, "Queue");   /* Optional - if not supplied, pause the given Interface in all queues */
04836 
04837    if (ast_strlen_zero(interface) || ast_strlen_zero(paused_s)) {
04838       astman_send_error(s, m, "Need 'Interface' and 'Paused' parameters.");
04839       return 0;
04840    }
04841 
04842    paused = abs(ast_true(paused_s));
04843 
04844    if (set_member_paused(queuename, interface, paused))
04845       astman_send_error(s, m, "Interface not found");
04846    else
04847       astman_send_ack(s, m, paused ? "Interface paused successfully" : "Interface unpaused successfully");
04848    return 0;
04849 }
04850 
04851 static int handle_queue_add_member(int fd, int argc, char *argv[])
04852 {
04853    char *queuename, *interface, *membername = NULL;
04854    int penalty;
04855 
04856    if ((argc != 6) && (argc != 8) && (argc != 10)) {
04857       return RESULT_SHOWUSAGE;
04858    } else if (strcmp(argv[4], "to")) {
04859       return RESULT_SHOWUSAGE;
04860    } else if ((argc == 8) && strcmp(argv[6], "penalty")) {
04861       return RESULT_SHOWUSAGE;
04862    } else if ((argc == 10) && strcmp(argv[8], "as")) {
04863       return RESULT_SHOWUSAGE;
04864    }
04865 
04866    queuename = argv[5];
04867    interface = argv[3];
04868    if (argc >= 8) {
04869       if (sscanf(argv[7], "%d", &penalty) == 1) {
04870          if (penalty < 0) {
04871             ast_cli(fd, "Penalty must be >= 0\n");
04872             penalty = 0;
04873          }
04874       } else {
04875          ast_cli(fd, "Penalty must be an integer >= 0\n");
04876          penalty = 0;
04877       }
04878    } else {
04879       penalty = 0;
04880    }
04881 
04882    if (argc >= 10) {
04883       membername = argv[9];
04884    }
04885 
04886    switch (add_to_queue(queuename, interface, membername, penalty, 0, queue_persistent_members)) {
04887    case RES_OKAY:
04888       ast_queue_log(queuename, "CLI", interface, "ADDMEMBER", "%s", "");
04889       ast_cli(fd, "Added interface '%s' to queue '%s'\n", interface, queuename);
04890       return RESULT_SUCCESS;
04891    case RES_EXISTS:
04892       ast_cli(fd, "Unable to add interface '%s' to queue '%s': Already there\n", interface, queuename);
04893       return RESULT_FAILURE;
04894    case RES_NOSUCHQUEUE:
04895       ast_cli(fd, "Unable to add interface to queue '%s': No such queue\n", queuename);
04896       return RESULT_FAILURE;
04897    case RES_OUTOFMEMORY:
04898       ast_cli(fd, "Out of memory\n");
04899       return RESULT_FAILURE;
04900    default:
04901       return RESULT_FAILURE;
04902    }
04903 }
04904 
04905 static char *complete_queue_add_member(const char *line, const char *word, int pos, int state)
04906 {
04907    /* 0 - queue; 1 - add; 2 - member; 3 - <interface>; 4 - to; 5 - <queue>; 6 - penalty; 7 - <penalty>; 8 - as; 9 - <membername> */
04908    switch (pos) {
04909    case 3:  /* Don't attempt to complete name of interface (infinite possibilities) */
04910       return NULL;
04911    case 4:  /* only one possible match, "to" */
04912       return state == 0 ? ast_strdup("to") : NULL;
04913    case 5:  /* <queue> */
04914       return complete_queue(line, word, pos, state);
04915    case 6: /* only one possible match, "penalty" */
04916       return state == 0 ? ast_strdup("penalty") : NULL;
04917    case 7:
04918       if (state < 100) {   /* 0-99 */
04919          char *num;
04920          if ((num = ast_malloc(3))) {
04921             sprintf(num, "%d", state);
04922          }
04923          return num;
04924       } else {
04925          return NULL;
04926       }
04927    case 8: /* only one possible match, "as" */
04928       return state == 0 ? ast_strdup("as") : NULL;
04929    case 9:  /* Don't attempt to complete name of member (infinite possibilities) */
04930       return NULL;
04931    default:
04932       return NULL;
04933    }
04934 }
04935 
04936 static int handle_queue_remove_member(int fd, int argc, char *argv[])
04937 {
04938    char *queuename, *interface;
04939 
04940    if (argc != 6) {
04941       return RESULT_SHOWUSAGE;
04942    } else if (strcmp(argv[4], "from")) {
04943       return RESULT_SHOWUSAGE;
04944    }
04945 
04946    queuename = argv[5];
04947    interface = argv[3];
04948 
04949    switch (remove_from_queue(queuename, interface)) {
04950    case RES_OKAY:
04951       ast_queue_log(queuename, "CLI", interface, "REMOVEMEMBER", "%s", "");
04952       ast_cli(fd, "Removed interface '%s' from queue '%s'\n", interface, queuename);
04953       return RESULT_SUCCESS;
04954    case RES_EXISTS:
04955       ast_cli(fd, "Unable to remove interface '%s' from queue '%s': Not there\n", interface, queuename);
04956       return RESULT_FAILURE;
04957    case RES_NOSUCHQUEUE:
04958       ast_cli(fd, "Unable to remove interface from queue '%s': No such queue\n", queuename);
04959       return RESULT_FAILURE;
04960    case RES_OUTOFMEMORY:
04961       ast_cli(fd, "Out of memory\n");
04962       return RESULT_FAILURE;
04963    case RES_NOT_DYNAMIC:
04964       ast_cli(fd, "Member not dynamic\n");
04965       return RESULT_FAILURE;
04966    default:
04967       return RESULT_FAILURE;
04968    }
04969 }
04970 
04971 static char *complete_queue_remove_member(const char *line, const char *word, int pos, int state)
04972 {
04973    int which = 0;
04974    struct call_queue *q;
04975    struct member *m;
04976    struct ao2_iterator mem_iter;
04977 
04978    /* 0 - queue; 1 - remove; 2 - member; 3 - <member>; 4 - from; 5 - <queue> */
04979    if (pos > 5 || pos < 3)
04980       return NULL;
04981    if (pos == 4)  /* only one possible match, 'from' */
04982       return state == 0 ? ast_strdup("from") : NULL;
04983 
04984    if (pos == 5)  /* No need to duplicate code */
04985       return complete_queue(line, word, pos, state);
04986 
04987    /* here is the case for 3, <member> */
04988    if (!AST_LIST_EMPTY(&queues)) { /* XXX unnecessary ? the traverse does that for us */
04989       AST_LIST_TRAVERSE(&queues, q, list) {
04990          ast_mutex_lock(&q->lock);
04991          mem_iter = ao2_iterator_init(q->members, 0);
04992          while ((m = ao2_iterator_next(&mem_iter))) {
04993             if (++which > state) {
04994                char *tmp;
04995                ast_mutex_unlock(&q->lock);
04996                tmp = ast_strdup(m->interface);
04997                ao2_ref(m, -1);
04998                return tmp;
04999             }
05000             ao2_ref(m, -1);
05001          }
05002          ast_mutex_unlock(&q->lock);
05003       }
05004    }
05005 
05006    return NULL;
05007 }
05008 
05009 static char queue_show_usage[] =
05010 "Usage: queue show\n"
05011 "       Provides summary information on a specified queue.\n";
05012 
05013 static char qam_cmd_usage[] =
05014 "Usage: queue add member <channel> to <queue> [penalty <penalty>]\n";
05015 
05016 static char qrm_cmd_usage[] =
05017 "Usage: queue remove member <channel> from <queue>\n";
05018 
05019 static struct ast_cli_entry cli_show_queue_deprecated = {
05020    { "show", "queue", NULL },
05021    queue_show, NULL,
05022    NULL, complete_queue_show };
05023 
05024 static struct ast_cli_entry cli_add_queue_member_deprecated = {
05025    { "add", "queue", "member", NULL },
05026    handle_queue_add_member, NULL,
05027    NULL, complete_queue_add_member };
05028 
05029 static struct ast_cli_entry cli_remove_queue_member_deprecated = {
05030    { "remove", "queue", "member", NULL },
05031    handle_queue_remove_member, NULL,
05032    NULL, complete_queue_remove_member };
05033 
05034 static struct ast_cli_entry cli_queue[] = {
05035    /* Deprecated */
05036    { { "show", "queues", NULL },
05037    queue_show, NULL,
05038    NULL, NULL },
05039 
05040    { { "queue", "show", NULL },
05041    queue_show, "Show status of a specified queue",
05042    queue_show_usage, complete_queue_show, &cli_show_queue_deprecated },
05043 
05044    { { "queue", "add", "member", NULL },
05045    handle_queue_add_member, "Add a channel to a specified queue",
05046    qam_cmd_usage, complete_queue_add_member, &cli_add_queue_member_deprecated },
05047 
05048    { { "queue", "remove", "member", NULL },
05049    handle_queue_remove_member, "Removes a channel from a specified queue",
05050    qrm_cmd_usage, complete_queue_remove_member, &cli_remove_queue_member_deprecated },
05051 };
05052 
05053 static int unload_module(void)
05054 {
05055    int res;
05056 
05057    if (device_state.thread != AST_PTHREADT_NULL) {
05058       device_state.stop = 1;
05059       ast_mutex_lock(&device_state.lock);
05060       ast_cond_signal(&device_state.cond);
05061       ast_mutex_unlock(&device_state.lock);
05062       pthread_join(device_state.thread, NULL);
05063    }
05064 
05065    ast_cli_unregister_multiple(cli_queue, sizeof(cli_queue) / sizeof(struct ast_cli_entry));
05066    res = ast_manager_unregister("QueueStatus");
05067    res |= ast_manager_unregister("Queues");
05068    res |= ast_manager_unregister("QueueAdd");
05069    res |= ast_manager_unregister("QueueRemove");
05070    res |= ast_manager_unregister("QueuePause");
05071    res |= ast_unregister_application(app_aqm);
05072    res |= ast_unregister_application(app_rqm);
05073    res |= ast_unregister_application(app_pqm);
05074    res |= ast_unregister_application(app_upqm);
05075    res |= ast_unregister_application(app_ql);
05076    res |= ast_unregister_application(app);
05077    res |= ast_custom_function_unregister(&queueagentcount_function);
05078    res |= ast_custom_function_unregister(&queuemembercount_function);
05079    res |= ast_custom_function_unregister(&queuememberlist_function);
05080    res |= ast_custom_function_unregister(&queuewaitingcount_function);
05081    ast_devstate_del(statechange_queue, NULL);
05082 
05083    ast_module_user_hangup_all();
05084 
05085    clear_and_free_interfaces();
05086 
05087    return res;
05088 }
05089 
05090 static int load_module(void)
05091 {
05092    int res;
05093 
05094    if (!reload_queues())
05095       return AST_MODULE_LOAD_DECLINE;
05096 
05097    if (queue_persistent_members)
05098       reload_queue_members();
05099 
05100    ast_mutex_init(&device_state.lock);
05101    ast_cond_init(&device_state.cond, NULL);
05102    ast_pthread_create(&device_state.thread, NULL, device_state_thread, NULL);
05103 
05104    ast_cli_register_multiple(cli_queue, sizeof(cli_queue) / sizeof(struct ast_cli_entry));
05105    res = ast_register_application(app, queue_exec, synopsis, descrip);
05106    res |= ast_register_application(app_aqm, aqm_exec, app_aqm_synopsis, app_aqm_descrip);
05107    res |= ast_register_application(app_rqm, rqm_exec, app_rqm_synopsis, app_rqm_descrip);
05108    res |= ast_register_application(app_pqm, pqm_exec, app_pqm_synopsis, app_pqm_descrip);
05109    res |= ast_register_application(app_upqm, upqm_exec, app_upqm_synopsis, app_upqm_descrip);
05110    res |= ast_register_application(app_ql, ql_exec, app_ql_synopsis, app_ql_descrip);
05111    res |= ast_manager_register("Queues", 0, manager_queues_show, "Queues");
05112    res |= ast_manager_register("QueueStatus", 0, manager_queues_status, "Queue Status");
05113    res |= ast_manager_register("QueueAdd", EVENT_FLAG_AGENT, manager_add_queue_member, "Add interface to queue.");
05114    res |= ast_manager_register("QueueRemove", EVENT_FLAG_AGENT, manager_remove_queue_member, "Remove interface from queue.");
05115    res |= ast_manager_register("QueuePause", EVENT_FLAG_AGENT, manager_pause_queue_member, "Makes a queue member temporarily unavailable");
05116    res |= ast_custom_function_register(&queueagentcount_function);
05117    res |= ast_custom_function_register(&queuemembercount_function);
05118    res |= ast_custom_function_register(&queuememberlist_function);
05119    res |= ast_custom_function_register(&queuewaitingcount_function);
05120    res |= ast_devstate_add(statechange_queue, NULL);
05121 
05122    return res;
05123 }
05124 
05125 static int reload(void)
05126 {
05127    reload_queues();
05128    return 0;
05129 }
05130 
05131 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "True Call Queueing",
05132       .load = load_module,
05133       .unload = unload_module,
05134       .reload = reload,
05135           );
05136 

Generated on Fri Jul 3 20:35:32 2009 for Asterisk - the Open Source PBX by  doxygen 1.5.9