Fix building that was broken by recent monitor.h changes. Thanks Russell for pointin...
[asterisk/asterisk.git] / apps / app_queue.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2006, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*! \file
20  *
21  * \brief True call queues with optional send URL on answer
22  *
23  * \author Mark Spencer <markster@digium.com>
24  *
25  * \arg Config in \ref Config_qu queues.conf
26  *
27  * \par Development notes
28  * \note 2004-11-25: Persistent Dynamic Members added by:
29  *             NetNation Communications (www.netnation.com)
30  *             Kevin Lindsay <kevinl@netnation.com>
31  *
32  *             Each dynamic agent in each queue is now stored in the astdb.
33  *             When asterisk is restarted, each agent will be automatically
34  *             readded into their recorded queues. This feature can be
35  *             configured with the 'persistent_members=<1|0>' setting in the
36  *             '[general]' category in queues.conf. The default is on.
37  *
38  * \note 2004-06-04: Priorities in queues added by inAccess Networks (work funded by Hellas On Line (HOL) www.hol.gr).
39  *
40  * \note These features added by David C. Troy <dave@toad.net>:
41  *    - Per-queue holdtime calculation
42  *    - Estimated holdtime announcement
43  *    - Position announcement
44  *    - Abandoned/completed call counters
45  *    - Failout timer passed as optional app parameter
46  *    - Optional monitoring of calls, started when call is answered
47  *
48  * Patch Version 1.07 2003-12-24 01
49  *
50  * Added servicelevel statistic by Michiel Betel <michiel@betel.nl>
51  * Added Priority jumping code for adding and removing queue members by Jonathan Stanton <asterisk@doilooklikeicare.com>
52  *
53  * Fixed to work with CVS as of 2004-02-25 and released as 1.07a
54  * by Matthew Enger <m.enger@xi.com.au>
55  *
56  * \ingroup applications
57  */
58
59 #include "asterisk.h"
60
61 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
62
63 #include <stdlib.h>
64 #include <errno.h>
65 #include <unistd.h>
66 #include <string.h>
67 #include <stdlib.h>
68 #include <stdio.h>
69 #include <sys/time.h>
70 #include <sys/signal.h>
71 #include <netinet/in.h>
72
73 #include "asterisk/lock.h"
74 #include "asterisk/file.h"
75 #include "asterisk/logger.h"
76 #include "asterisk/channel.h"
77 #include "asterisk/pbx.h"
78 #include "asterisk/options.h"
79 #include "asterisk/app.h"
80 #include "asterisk/linkedlists.h"
81 #include "asterisk/module.h"
82 #include "asterisk/translate.h"
83 #include "asterisk/say.h"
84 #include "asterisk/features.h"
85 #include "asterisk/musiconhold.h"
86 #include "asterisk/cli.h"
87 #include "asterisk/manager.h"
88 #include "asterisk/config.h"
89 #include "asterisk/monitor.h"
90 #include "asterisk/utils.h"
91 #include "asterisk/causes.h"
92 #include "asterisk/astdb.h"
93 #include "asterisk/devicestate.h"
94 #include "asterisk/stringfields.h"
95 #include "asterisk/event.h"
96
97 enum {
98         QUEUE_STRATEGY_RINGALL = 0,
99         QUEUE_STRATEGY_LEASTRECENT,
100         QUEUE_STRATEGY_FEWESTCALLS,
101         QUEUE_STRATEGY_RANDOM,
102         QUEUE_STRATEGY_RRMEMORY
103 };
104
105 static struct strategy {
106         int strategy;
107         char *name;
108 } strategies[] = {
109         { QUEUE_STRATEGY_RINGALL, "ringall" },
110         { QUEUE_STRATEGY_LEASTRECENT, "leastrecent" },
111         { QUEUE_STRATEGY_FEWESTCALLS, "fewestcalls" },
112         { QUEUE_STRATEGY_RANDOM, "random" },
113         { QUEUE_STRATEGY_RRMEMORY, "rrmemory" },
114 };
115
116 #define DEFAULT_RETRY           5
117 #define DEFAULT_TIMEOUT         15
118 #define RECHECK                 1               /* Recheck every second to see we we're at the top yet */
119 #define MAX_PERIODIC_ANNOUNCEMENTS 10 /* The maximum periodic announcements we can have */
120 #define DEFAULT_MIN_ANNOUNCE_FREQUENCY 15 /* The minimum number of seconds between position announcements
121                                              The default value of 15 provides backwards compatibility */
122
123 #define RES_OKAY        0               /* Action completed */
124 #define RES_EXISTS      (-1)            /* Entry already exists */
125 #define RES_OUTOFMEMORY (-2)            /* Out of memory */
126 #define RES_NOSUCHQUEUE (-3)            /* No such queue */
127
128 static char *app = "Queue";
129
130 static char *synopsis = "Queue a call for a call queue";
131
132 static char *descrip =
133 "  Queue(queuename[|options[|URL][|announceoverride][|timeout][|AGI][|macro][|gosub]):\n"
134 "Queues an incoming call in a particular call queue as defined in queues.conf.\n"
135 "This application will return to the dialplan if the queue does not exist, or\n"
136 "any of the join options cause the caller to not enter the queue.\n"
137 "The option string may contain zero or more of the following characters:\n"
138 "      'c' -- continue in the dialplan if the callee hangs up.\n"
139 "      'd' -- data-quality (modem) call (minimum delay).\n"
140 "      'h' -- allow callee to hang up by pressing *.\n"
141 "      'H' -- allow caller to hang up by pressing *.\n"
142 "      'n' -- no retries on the timeout; will exit this application and \n"
143 "             go to the next step.\n"
144 "      'i' -- ignore call forward requests from queue members and do nothing\n"
145 "             when they are requested.\n"
146 "      'r' -- ring instead of playing MOH.\n"
147 "      't' -- allow the called user to transfer the calling user.\n"
148 "      'T' -- allow the calling user to transfer the call.\n"
149 "      'w' -- allow the called user to write the conversation to disk via Monitor.\n"
150 "      'W' -- allow the calling user to write the conversation to disk via Monitor.\n"
151 "  In addition to transferring the call, a call may be parked and then picked\n"
152 "up by another user.\n"
153 "  The optional URL will be sent to the called party if the channel supports\n"
154 "it.\n"
155 "  The optional AGI parameter will setup an AGI script to be executed on the \n"
156 "calling party's channel once they are connected to a queue member.\n"
157 "  The optional macro parameter will run a macro on the \n"
158 "calling party's channel once they are connected to a queue member.\n"
159 "  The optional gosub parameter will run a gosub on the \n"
160 "calling party's channel once they are connected to a queue member.\n"
161 "  The timeout will cause the queue to fail out after a specified number of\n"
162 "seconds, checked between each queues.conf 'timeout' and 'retry' cycle.\n"
163 "  This application sets the following channel variable upon completion:\n"
164 "      QUEUESTATUS    The status of the call as a text string, one of\n"
165 "             TIMEOUT | FULL | JOINEMPTY | LEAVEEMPTY | JOINUNAVAIL | LEAVEUNAVAIL | CONTINUE\n";
166
167 static char *app_aqm = "AddQueueMember" ;
168 static char *app_aqm_synopsis = "Dynamically adds queue members" ;
169 static char *app_aqm_descrip =
170 "   AddQueueMember(queuename[|interface[|penalty[|options[|membername]]]]):\n"
171 "Dynamically adds interface to an existing queue.\n"
172 "If the interface is already in the queue it will return an error.\n"
173 "  This application sets the following channel variable upon completion:\n"
174 "     AQMSTATUS    The status of the attempt to add a queue member as a \n"
175 "                     text string, one of\n"
176 "           ADDED | MEMBERALREADY | NOSUCHQUEUE \n"
177 "Example: AddQueueMember(techsupport|SIP/3000)\n"
178 "";
179
180 static char *app_rqm = "RemoveQueueMember" ;
181 static char *app_rqm_synopsis = "Dynamically removes queue members" ;
182 static char *app_rqm_descrip =
183 "   RemoveQueueMember(queuename[|interface[|options]]):\n"
184 "Dynamically removes interface to an existing queue\n"
185 "If the interface is NOT in the queue it will return an error.\n"
186 "  This application sets the following channel variable upon completion:\n"
187 "     RQMSTATUS      The status of the attempt to remove a queue member as a\n"
188 "                     text string, one of\n"
189 "           REMOVED | NOTINQUEUE | NOSUCHQUEUE \n"
190 "Example: RemoveQueueMember(techsupport|SIP/3000)\n"
191 "";
192
193 static char *app_pqm = "PauseQueueMember" ;
194 static char *app_pqm_synopsis = "Pauses a queue member" ;
195 static char *app_pqm_descrip =
196 "   PauseQueueMember([queuename]|interface[|options]):\n"
197 "Pauses (blocks calls for) a queue member.\n"
198 "The given interface will be paused in the given queue.  This prevents\n"
199 "any calls from being sent from the queue to the interface until it is\n"
200 "unpaused with UnpauseQueueMember or the manager interface.  If no\n"
201 "queuename is given, the interface is paused in every queue it is a\n"
202 "member of. The application will fail if the interface is not found.\n"
203 "  This application sets the following channel variable upon completion:\n"
204 "     PQMSTATUS      The status of the attempt to pause a queue member as a\n"
205 "                     text string, one of\n"
206 "           PAUSED | NOTFOUND\n"
207 "Example: PauseQueueMember(|SIP/3000)\n";
208
209 static char *app_upqm = "UnpauseQueueMember" ;
210 static char *app_upqm_synopsis = "Unpauses a queue member" ;
211 static char *app_upqm_descrip =
212 "   UnpauseQueueMember([queuename]|interface[|options]):\n"
213 "Unpauses (resumes calls to) a queue member.\n"
214 "This is the counterpart to PauseQueueMember and operates exactly the\n"
215 "same way, except it unpauses instead of pausing the given interface.\n"
216 "  This application sets the following channel variable upon completion:\n"
217 "     UPQMSTATUS       The status of the attempt to unpause a queue \n"
218 "                      member as a text string, one of\n"
219 "            UNPAUSED | NOTFOUND\n"
220 "Example: UnpauseQueueMember(|SIP/3000)\n";
221
222 static char *app_ql = "QueueLog" ;
223 static char *app_ql_synopsis = "Writes to the queue_log" ;
224 static char *app_ql_descrip =
225 "   QueueLog(queuename|uniqueid|agent|event[|additionalinfo]):\n"
226 "Allows you to write your own events into the queue log\n"
227 "Example: QueueLog(101|${UNIQUEID}|${AGENT}|WENTONBREAK|600)\n";
228
229 /*! \brief Persistent Members astdb family */
230 static const char *pm_family = "Queue/PersistentMembers";
231 /* The maximum length of each persistent member queue database entry */
232 #define PM_MAX_LEN 8192
233
234 /*! \brief queues.conf [general] option */
235 static int queue_keep_stats = 0;
236
237 /*! \brief queues.conf [general] option */
238 static int queue_persistent_members = 0;
239
240 /*! \brief queues.conf per-queue weight option */
241 static int use_weight = 0;
242
243 /*! \brief queues.conf [general] option */
244 static int autofill_default = 0;
245
246 /*! \brief queues.conf [general] option */
247 static int montype_default = 0;
248
249 /*! \brief Subscription to device state change events */
250 static struct ast_event_sub *device_state_sub;
251
252 enum queue_result {
253         QUEUE_UNKNOWN = 0,
254         QUEUE_TIMEOUT = 1,
255         QUEUE_JOINEMPTY = 2,
256         QUEUE_LEAVEEMPTY = 3,
257         QUEUE_JOINUNAVAIL = 4,
258         QUEUE_LEAVEUNAVAIL = 5,
259         QUEUE_FULL = 6,
260         QUEUE_CONTINUE = 7,
261 };
262
263 const struct {
264         enum queue_result id;
265         char *text;
266 } queue_results[] = {
267         { QUEUE_UNKNOWN, "UNKNOWN" },
268         { QUEUE_TIMEOUT, "TIMEOUT" },
269         { QUEUE_JOINEMPTY,"JOINEMPTY" },
270         { QUEUE_LEAVEEMPTY, "LEAVEEMPTY" },
271         { QUEUE_JOINUNAVAIL, "JOINUNAVAIL" },
272         { QUEUE_LEAVEUNAVAIL, "LEAVEUNAVAIL" },
273         { QUEUE_FULL, "FULL" },
274         { QUEUE_CONTINUE, "CONTINUE" },
275 };
276
277 /*! \brief We define a custom "local user" structure because we
278    use it not only for keeping track of what is in use but
279    also for keeping track of who we're dialing. */
280
281 struct callattempt {
282         struct callattempt *q_next;
283         struct ast_channel *chan;
284         char interface[256];
285         int stillgoing;
286         int metric;
287         int oldstatus;
288         time_t lastcall;
289         struct member *member;
290 };
291
292
293 struct queue_ent {
294         struct call_queue *parent;          /*!< What queue is our parent */
295         char moh[80];                       /*!< Name of musiconhold to be used */
296         char announce[80];                  /*!< Announcement to play for member when call is answered */
297         char context[AST_MAX_CONTEXT];      /*!< Context when user exits queue */
298         char digits[AST_MAX_EXTENSION];     /*!< Digits entered while in queue */
299         int pos;                            /*!< Where we are in the queue */
300         int prio;                           /*!< Our priority */
301         int last_pos_said;                  /*!< Last position we told the user */
302         time_t last_periodic_announce_time; /*!< The last time we played a periodic announcement */
303         int last_periodic_announce_sound;   /*!< The last periodic announcement we made */
304         time_t last_pos;                    /*!< Last time we told the user their position */
305         int opos;                           /*!< Where we started in the queue */
306         int handled;                        /*!< Whether our call was handled */
307         int max_penalty;                    /*!< Limit the members that can take this call to this penalty or lower */
308         time_t start;                       /*!< When we started holding */
309         time_t expire;                      /*!< When this entry should expire (time out of queue) */
310         struct ast_channel *chan;           /*!< Our channel */
311         struct queue_ent *next;             /*!< The next queue entry */
312 };
313
314 struct member {
315         char interface[80];                 /*!< Technology/Location */
316         char membername[80];                /*!< Member name to use in queue logs */
317         int penalty;                        /*!< Are we a last resort? */
318         int calls;                          /*!< Number of calls serviced by this member */
319         int dynamic;                        /*!< Are we dynamically added? */
320         int status;                         /*!< Status of queue member */
321         int paused;                         /*!< Are we paused (not accepting calls)? */
322         time_t lastcall;                    /*!< When last successful call was hungup */
323         unsigned int dead:1;                /*!< Used to detect members deleted in realtime */
324         unsigned int delme:1;               /*!< Flag to delete entry on reload */
325         struct member *next;                /*!< Next member */
326 };
327
328 struct member_interface {
329         char interface[80];
330         AST_LIST_ENTRY(member_interface) list;    /*!< Next call queue */
331 };
332
333 static AST_LIST_HEAD_STATIC(interfaces, member_interface);
334
335 /* values used in multi-bit flags in call_queue */
336 #define QUEUE_EMPTY_NORMAL 1
337 #define QUEUE_EMPTY_STRICT 2
338 #define QUEUE_EMPTY_LOOSE 3
339 #define ANNOUNCEHOLDTIME_ALWAYS 1
340 #define ANNOUNCEHOLDTIME_ONCE 2
341 #define QUEUE_EVENT_VARIABLES 3
342
343 struct call_queue {
344         ast_mutex_t lock;       
345         char name[80];                      /*!< Name */
346         char moh[80];                       /*!< Music On Hold class to be used */
347         char announce[80];                  /*!< Announcement to play when call is answered */
348         char context[AST_MAX_CONTEXT];      /*!< Exit context */
349         unsigned int monjoin:1;
350         unsigned int dead:1;
351         unsigned int joinempty:2;
352         unsigned int eventwhencalled:2;
353         unsigned int leavewhenempty:2;
354         unsigned int ringinuse:1;
355         unsigned int setinterfacevar:1;
356         unsigned int setqueuevar:1;
357         unsigned int setqueueentryvar:1;
358         unsigned int reportholdtime:1;
359         unsigned int wrapped:1;
360         unsigned int timeoutrestart:1;
361         unsigned int announceholdtime:2;
362         unsigned int strategy:3;
363         unsigned int maskmemberstatus:1;
364         unsigned int realtime:1;
365         int announcefrequency;              /*!< How often to announce their position */
366         int minannouncefrequency;           /*!< The minimum number of seconds between position announcements (def. 15) */
367         int periodicannouncefrequency;      /*!< How often to play periodic announcement */
368         int roundingseconds;                /*!< How many seconds do we round to? */
369         int holdtime;                       /*!< Current avg holdtime, based on recursive boxcar filter */
370         int callscompleted;                 /*!< Number of queue calls completed */
371         int callsabandoned;                 /*!< Number of queue calls abandoned */
372         int servicelevel;                   /*!< seconds setting for servicelevel*/
373         int callscompletedinsl;             /*!< Number of calls answered with servicelevel*/
374         char monfmt[8];                     /*!< Format to use when recording calls */
375         int montype;                        /*!< Monitor type  Monitor vs. MixMonitor */
376         char membermacro[32];               /*!< Macro to run upon member connection */
377         char membergosub[32];               /*!< Gosub to run upon member connection */
378         char sound_next[80];                /*!< Sound file: "Your call is now first in line" (def. queue-youarenext) */
379         char sound_thereare[80];            /*!< Sound file: "There are currently" (def. queue-thereare) */
380         char sound_calls[80];               /*!< Sound file: "calls waiting to speak to a representative." (def. queue-callswaiting)*/
381         char sound_holdtime[80];            /*!< Sound file: "The current estimated total holdtime is" (def. queue-holdtime) */
382         char sound_minutes[80];             /*!< Sound file: "minutes." (def. queue-minutes) */
383         char sound_lessthan[80];            /*!< Sound file: "less-than" (def. queue-lessthan) */
384         char sound_seconds[80];             /*!< Sound file: "seconds." (def. queue-seconds) */
385         char sound_thanks[80];              /*!< Sound file: "Thank you for your patience." (def. queue-thankyou) */
386         char sound_callerannounce[80];      /*!< Sound file: Custom announce for caller, no default */
387         char sound_reporthold[80];          /*!< Sound file: "Hold time" (def. queue-reporthold) */
388         char sound_periodicannounce[MAX_PERIODIC_ANNOUNCEMENTS][80];/*!< Sound files: Custom announce, no default */
389
390         int count;                          /*!< How many entries */
391         int maxlen;                         /*!< Max number of entries */
392         int wrapuptime;                     /*!< Wrapup Time */
393
394         int retry;                          /*!< Retry calling everyone after this amount of time */
395         int timeout;                        /*!< How long to wait for an answer */
396         int weight;                         /*!< Respective weight */
397         int autopause;                      /*!< Auto pause queue members if they fail to answer */
398
399         /* Queue strategy things */
400         int rrpos;                          /*!< Round Robin - position */
401         int memberdelay;                    /*!< Seconds to delay connecting member to caller */
402         int autofill;                       /*!< Ignore the head call status and ring an available agent */
403         
404         struct member *members;             /*!< Head of the list of members */
405         struct queue_ent *head;             /*!< Head of the list of callers */
406         AST_LIST_ENTRY(call_queue) list;    /*!< Next call queue */
407 };
408
409 static AST_LIST_HEAD_STATIC(queues, call_queue);
410
411 static int set_member_paused(const char *queuename, const char *interface, int paused);
412
413 static void set_queue_result(struct ast_channel *chan, enum queue_result res)
414 {
415         int i;
416
417         for (i = 0; i < sizeof(queue_results) / sizeof(queue_results[0]); i++) {
418                 if (queue_results[i].id == res) {
419                         pbx_builtin_setvar_helper(chan, "QUEUESTATUS", queue_results[i].text);
420                         return;
421                 }
422         }
423 }
424
425 static char *int2strat(int strategy)
426 {
427         int x;
428
429         for (x = 0; x < sizeof(strategies) / sizeof(strategies[0]); x++) {
430                 if (strategy == strategies[x].strategy)
431                         return strategies[x].name;
432         }
433
434         return "<unknown>";
435 }
436
437 static int strat2int(const char *strategy)
438 {
439         int x;
440
441         for (x = 0; x < sizeof(strategies) / sizeof(strategies[0]); x++) {
442                 if (!strcasecmp(strategy, strategies[x].name))
443                         return strategies[x].strategy;
444         }
445
446         return -1;
447 }
448
449 static void set_queue_variables(struct queue_ent *qe)
450 {
451
452         char interfacevar[256]="";
453         float sl = 0;
454         
455         if (qe->parent->setqueuevar) {
456         sl = 0;
457         if (qe->parent->callscompleted > 0) 
458                 sl = 100 * ((float) qe->parent->callscompletedinsl / (float) qe->parent->callscompleted);
459
460         snprintf(interfacevar,sizeof(interfacevar),
461                 "QUEUEMAX=%d|QUEUESTRATEGY=%s|QUEUECALLS=%d|QUEUEHOLDTIME=%d|QUEUECOMPLETED=%d|QUEUEABANDONED=%d|QUEUESRVLEVEL=%d|QUEUESRVLEVELPERF=%2.1f",
462                 qe->parent->maxlen, int2strat(qe->parent->strategy), qe->parent->count, qe->parent->holdtime, qe->parent->callscompleted,
463                 qe->parent->callsabandoned,  qe->parent->servicelevel, sl);
464         
465         pbx_builtin_setvar(qe->chan, interfacevar); 
466         }
467 }
468
469 /*! \brief Insert the 'new' entry after the 'prev' entry of queue 'q' */
470 static inline void insert_entry(struct call_queue *q, struct queue_ent *prev, struct queue_ent *new, int *pos)
471 {
472         struct queue_ent *cur;
473
474         if (!q || !new)
475                 return;
476         if (prev) {
477                 cur = prev->next;
478                 prev->next = new;
479         } else {
480                 cur = q->head;
481                 q->head = new;
482         }
483         new->next = cur;
484         new->parent = q;
485         new->pos = ++(*pos);
486         new->opos = *pos;
487 }
488
489 enum queue_member_status {
490         QUEUE_NO_MEMBERS,
491         QUEUE_NO_REACHABLE_MEMBERS,
492         QUEUE_NO_UNPAUSED_REACHABLE_MEMBERS,
493         QUEUE_NORMAL
494 };
495
496 static enum queue_member_status get_member_status(struct call_queue *q, int max_penalty)
497 {
498         struct member *member;
499         enum queue_member_status result = QUEUE_NO_MEMBERS;
500
501         ast_mutex_lock(&q->lock);
502         for (member = q->members; member; member = member->next) {
503                 if (max_penalty && (member->penalty > max_penalty))
504                         continue;
505
506                 switch (member->status) {
507                 case AST_DEVICE_INVALID:
508                         /* nothing to do */
509                         break;
510                 case AST_DEVICE_UNAVAILABLE:
511                         if (result != QUEUE_NO_UNPAUSED_REACHABLE_MEMBERS) 
512                                 result = QUEUE_NO_REACHABLE_MEMBERS;
513                         break;
514                 default:
515                         if (member->paused) {
516                                 result = QUEUE_NO_UNPAUSED_REACHABLE_MEMBERS;
517                         } else {
518                                 ast_mutex_unlock(&q->lock);
519                                 return QUEUE_NORMAL;
520                         }
521                         break;
522                 }
523         }
524         
525         ast_mutex_unlock(&q->lock);
526         return result;
527 }
528
529 struct statechange {
530         AST_LIST_ENTRY(statechange) entry;
531         int state;
532         char dev[0];
533 };
534
535 static void *handle_statechange(struct statechange *sc)
536 {
537         struct call_queue *q;
538         struct member *cur;
539         struct member_interface *curint;
540         char *loc;
541         char *technology;
542
543         technology = ast_strdupa(sc->dev);
544         loc = strchr(technology, '/');
545         if (loc) {
546                 *loc++ = '\0';
547         } else {
548                 return NULL;
549         }
550
551         AST_LIST_LOCK(&interfaces);
552         AST_LIST_TRAVERSE(&interfaces, curint, list) {
553                 char *interface;
554                 char *slash_pos;
555                 interface = ast_strdupa(curint->interface);
556                 if ((slash_pos = strchr(interface, '/')))
557                         if ((slash_pos = strchr(slash_pos + 1, '/')))
558                                 *slash_pos = '\0';
559
560                 if (!strcasecmp(interface, sc->dev))
561                         break;
562         }
563         AST_LIST_UNLOCK(&interfaces);
564
565         if (!curint) {
566                 ast_debug(3, "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));
567                 return NULL;
568         }
569
570         ast_debug(1, "Device '%s/%s' changed to state '%d' (%s)\n", technology, loc, sc->state, devstate2str(sc->state));
571         AST_LIST_LOCK(&queues);
572         AST_LIST_TRAVERSE(&queues, q, list) {
573                 ast_mutex_lock(&q->lock);
574                 for (cur = q->members; cur; cur = cur->next) {
575                         char *interface;
576                         char *slash_pos;
577                         interface = ast_strdupa(cur->interface);
578                         if ((slash_pos = strchr(interface, '/')))
579                                 if ((slash_pos = strchr(slash_pos + 1, '/')))
580                                         *slash_pos = '\0';
581
582                         if (strcasecmp(sc->dev, interface))
583                                 continue;
584
585                         if (cur->status != sc->state) {
586                                 cur->status = sc->state;
587                                 if (q->maskmemberstatus)
588                                         continue;
589
590                                 manager_event(EVENT_FLAG_AGENT, "QueueMemberStatus",
591                                         "Queue: %s\r\n"
592                                         "Location: %s\r\n"
593                                         "MemberName: %s\r\n"
594                                         "Membership: %s\r\n"
595                                         "Penalty: %d\r\n"
596                                         "CallsTaken: %d\r\n"
597                                         "LastCall: %d\r\n"
598                                         "Status: %d\r\n"
599                                         "Paused: %d\r\n",
600                                         q->name, cur->interface, cur->membername, cur->dynamic ? "dynamic" : "static",
601                                         cur->penalty, cur->calls, (int)cur->lastcall, cur->status, cur->paused);
602                         }
603                 }
604                 ast_mutex_unlock(&q->lock);
605         }
606         AST_LIST_UNLOCK(&queues);
607
608         return NULL;
609 }
610
611 /*!
612  * \brief Data used by the device state thread
613  */
614 static struct {
615         /*! Set to 1 to stop the thread */
616         unsigned int stop:1;
617         /*! The device state monitoring thread */
618         pthread_t thread;
619         /*! Lock for the state change queue */
620         ast_mutex_t lock;
621         /*! Condition for the state change queue */
622         ast_cond_t cond;
623         /*! Queue of state changes */
624         AST_LIST_HEAD_NOLOCK(, statechange) state_change_q;
625 } device_state = {
626         .thread = AST_PTHREADT_NULL,
627 };
628
629 static void *device_state_thread(void *data)
630 {
631         struct statechange *sc;
632
633         while (!device_state.stop) {
634                 ast_mutex_lock(&device_state.lock);
635                 if (!(sc = AST_LIST_REMOVE_HEAD(&device_state.state_change_q, entry))) {
636                         ast_cond_wait(&device_state.cond, &device_state.lock);
637                         sc = AST_LIST_REMOVE_HEAD(&device_state.state_change_q, entry);
638                 }
639                 ast_mutex_unlock(&device_state.lock);
640
641                 /* Check to see if we were woken up to see the request to stop */
642                 if (device_state.stop)
643                         return NULL;
644
645                 if (!sc)
646                         continue;
647
648                 handle_statechange(sc);
649
650                 free(sc);
651         }
652
653         return NULL;
654 }
655
656 static int statechange_queue(const char *dev, enum ast_device_state state)
657 {
658         struct statechange *sc;
659
660         if (!(sc = ast_calloc(1, sizeof(*sc) + strlen(dev) + 1)))
661                 return 0;
662
663         sc->state = state;
664         strcpy(sc->dev, dev);
665
666         ast_mutex_lock(&device_state.lock);
667         AST_LIST_INSERT_TAIL(&device_state.state_change_q, sc, entry);
668         ast_cond_signal(&device_state.cond);
669         ast_mutex_unlock(&device_state.lock);
670
671         return 0;
672 }
673
674 static void device_state_cb(const struct ast_event *event, void *unused)
675 {
676         enum ast_device_state state;
677         const char *device;
678
679         state = ast_event_get_ie_uint(event, AST_EVENT_IE_STATE);
680         device = ast_event_get_ie_str(event, AST_EVENT_IE_DEVICE);
681
682         if (ast_strlen_zero(device)) {
683                 ast_log(LOG_ERROR, "Received invalid event that had no device IE\n");
684                 return;
685         }
686
687         statechange_queue(device, state);
688 }
689
690 static struct member *create_queue_member(const char *interface, const char *membername, int penalty, int paused)
691 {
692         struct member *cur;
693         
694         if ((cur = ast_calloc(1, sizeof(*cur)))) {
695                 cur->penalty = penalty;
696                 cur->paused = paused;
697                 ast_copy_string(cur->interface, interface, sizeof(cur->interface));
698                 ast_copy_string(cur->membername, membername, sizeof(cur->membername));
699                 if (!strchr(cur->interface, '/'))
700                         ast_log(LOG_WARNING, "No location at interface '%s'\n", interface);
701                 cur->status = ast_device_state(interface);
702         }
703
704         return cur;
705 }
706
707 static struct call_queue *alloc_queue(const char *queuename)
708 {
709         struct call_queue *q;
710
711         if ((q = ast_calloc(1, sizeof(*q)))) {
712                 ast_mutex_init(&q->lock);
713                 ast_copy_string(q->name, queuename, sizeof(q->name));
714         }
715         return q;
716 }
717
718 static void init_queue(struct call_queue *q)
719 {
720         int i;
721
722         q->dead = 0;
723         q->retry = DEFAULT_RETRY;
724         q->timeout = -1;
725         q->maxlen = 0;
726         q->announcefrequency = 0;
727         q->minannouncefrequency = DEFAULT_MIN_ANNOUNCE_FREQUENCY;
728         q->announceholdtime = 0;
729         q->roundingseconds = 0; /* Default - don't announce seconds */
730         q->servicelevel = 0;
731         q->ringinuse = 1;
732         q->setinterfacevar = 0;
733         q->setqueuevar = 0;
734         q->setqueueentryvar = 0;
735         q->autofill = autofill_default;
736         q->montype = montype_default;
737         q->membermacro[0] = '\0';
738         q->membergosub[0] = '\0';
739         q->moh[0] = '\0';
740         q->announce[0] = '\0';
741         q->context[0] = '\0';
742         q->monfmt[0] = '\0';
743         q->periodicannouncefrequency = 0;
744         q->sound_callerannounce[0] = '\0';      /* Default, don't announce the caller that he has been answered */
745         ast_copy_string(q->sound_next, "queue-youarenext", sizeof(q->sound_next));
746         ast_copy_string(q->sound_thereare, "queue-thereare", sizeof(q->sound_thereare));
747         ast_copy_string(q->sound_calls, "queue-callswaiting", sizeof(q->sound_calls));
748         ast_copy_string(q->sound_holdtime, "queue-holdtime", sizeof(q->sound_holdtime));
749         ast_copy_string(q->sound_minutes, "queue-minutes", sizeof(q->sound_minutes));
750         ast_copy_string(q->sound_seconds, "queue-seconds", sizeof(q->sound_seconds));
751         ast_copy_string(q->sound_thanks, "queue-thankyou", sizeof(q->sound_thanks));
752         ast_copy_string(q->sound_lessthan, "queue-less-than", sizeof(q->sound_lessthan));
753         ast_copy_string(q->sound_reporthold, "queue-reporthold", sizeof(q->sound_reporthold));
754         ast_copy_string(q->sound_periodicannounce[0], "queue-periodic-announce", sizeof(q->sound_periodicannounce[0]));
755         for (i = 1; i < MAX_PERIODIC_ANNOUNCEMENTS; i++) {
756                 q->sound_periodicannounce[i][0]='\0';
757         }
758 }
759
760 static void clear_queue(struct call_queue *q)
761 {
762         q->holdtime = 0;
763         q->callscompleted = 0;
764         q->callsabandoned = 0;
765         q->callscompletedinsl = 0;
766         q->wrapuptime = 0;
767 }
768
769 static int add_to_interfaces(const char *interface)
770 {
771         struct member_interface *curint;
772
773         AST_LIST_LOCK(&interfaces);
774         AST_LIST_TRAVERSE(&interfaces, curint, list) {
775                 if (!strcasecmp(curint->interface, interface))
776                         break;
777         }
778
779         if (curint) {
780                 AST_LIST_UNLOCK(&interfaces);
781                 return 0;
782         }
783
784         ast_debug(1, "Adding %s to the list of interfaces that make up all of our queue members.\n", interface);
785         
786         if ((curint = ast_calloc(1, sizeof(*curint)))) {
787                 ast_copy_string(curint->interface, interface, sizeof(curint->interface));
788                 AST_LIST_INSERT_HEAD(&interfaces, curint, list);
789         }
790         AST_LIST_UNLOCK(&interfaces);
791
792         return 0;
793 }
794
795 static int interface_exists_global(const char *interface)
796 {
797         struct call_queue *q;
798         struct member *mem;
799         int ret = 0;
800
801         AST_LIST_LOCK(&queues);
802         AST_LIST_TRAVERSE(&queues, q, list) {
803                 ast_mutex_lock(&q->lock);
804                 for (mem = q->members; mem && !ret; mem = mem->next) {
805                         if (!strcasecmp(interface, mem->interface))
806                                 ret = 1;
807                 }
808                 ast_mutex_unlock(&q->lock);
809                 if (ret)
810                         break;
811         }
812         AST_LIST_UNLOCK(&queues);
813
814         return ret;
815 }
816
817 static int remove_from_interfaces(const char *interface)
818 {
819         struct member_interface *curint;
820
821         AST_LIST_LOCK(&interfaces);
822         AST_LIST_TRAVERSE_SAFE_BEGIN(&interfaces, curint, list) {
823                 if (!strcasecmp(curint->interface, interface)) {
824                         if (!interface_exists_global(interface)) {
825                                 ast_debug(1, "Removing %s from the list of interfaces that make up all of our queue members.\n", interface);
826                                 AST_LIST_REMOVE_CURRENT(&interfaces, list);
827                                 ast_free(curint);
828                         }
829                         break;
830                 }
831         }
832         AST_LIST_TRAVERSE_SAFE_END;
833         AST_LIST_UNLOCK(&interfaces);
834
835         return 0;
836 }
837
838 static void clear_and_free_interfaces(void)
839 {
840         struct member_interface *curint;
841
842         AST_LIST_LOCK(&interfaces);
843         while ((curint = AST_LIST_REMOVE_HEAD(&interfaces, list)))
844                 ast_free(curint);
845         AST_LIST_UNLOCK(&interfaces);
846 }
847
848 /*! \brief Configure a queue parameter.
849 \par
850    For error reporting, line number is passed for .conf static configuration.
851    For Realtime queues, linenum is -1.
852    The failunknown flag is set for config files (and static realtime) to show
853    errors for unknown parameters. It is cleared for dynamic realtime to allow
854    extra fields in the tables. */
855 static void queue_set_param(struct call_queue *q, const char *param, const char *val, int linenum, int failunknown)
856 {
857         if (!strcasecmp(param, "musicclass") || 
858                 !strcasecmp(param, "music") || !strcasecmp(param, "musiconhold")) {
859                 ast_copy_string(q->moh, val, sizeof(q->moh));
860         } else if (!strcasecmp(param, "announce")) {
861                 ast_copy_string(q->announce, val, sizeof(q->announce));
862         } else if (!strcasecmp(param, "context")) {
863                 ast_copy_string(q->context, val, sizeof(q->context));
864         } else if (!strcasecmp(param, "timeout")) {
865                 q->timeout = atoi(val);
866                 if (q->timeout < 0)
867                         q->timeout = DEFAULT_TIMEOUT;
868         } else if (!strcasecmp(param, "ringinuse")) {
869                 q->ringinuse = ast_true(val);
870         } else if (!strcasecmp(param, "setinterfacevar")) {
871                 q->setinterfacevar = ast_true(val);
872         } else if (!strcasecmp(param, "setqueuevar")) {
873                 q->setqueuevar = ast_true(val);
874         } else if (!strcasecmp(param, "setqueueentryvar")) {
875                 q->setqueueentryvar = ast_true(val);
876         } else if (!strcasecmp(param, "monitor-join")) {
877                 q->monjoin = ast_true(val);
878         } else if (!strcasecmp(param, "monitor-format")) {
879                 ast_copy_string(q->monfmt, val, sizeof(q->monfmt));
880         } else if (!strcasecmp(param, "membermacro")) {
881                 ast_copy_string(q->membermacro, val, sizeof(q->membermacro));
882         } else if (!strcasecmp(param, "membergosub")) {
883                 ast_copy_string(q->membergosub, val, sizeof(q->membergosub));
884         } else if (!strcasecmp(param, "queue-youarenext")) {
885                 ast_copy_string(q->sound_next, val, sizeof(q->sound_next));
886         } else if (!strcasecmp(param, "queue-thereare")) {
887                 ast_copy_string(q->sound_thereare, val, sizeof(q->sound_thereare));
888         } else if (!strcasecmp(param, "queue-callswaiting")) {
889                 ast_copy_string(q->sound_calls, val, sizeof(q->sound_calls));
890         } else if (!strcasecmp(param, "queue-holdtime")) {
891                 ast_copy_string(q->sound_holdtime, val, sizeof(q->sound_holdtime));
892         } else if (!strcasecmp(param, "queue-minutes")) {
893                 ast_copy_string(q->sound_minutes, val, sizeof(q->sound_minutes));
894         } else if (!strcasecmp(param, "queue-seconds")) {
895                 ast_copy_string(q->sound_seconds, val, sizeof(q->sound_seconds));
896         } else if (!strcasecmp(param, "queue-lessthan")) {
897                 ast_copy_string(q->sound_lessthan, val, sizeof(q->sound_lessthan));
898         } else if (!strcasecmp(param, "queue-thankyou")) {
899                 ast_copy_string(q->sound_thanks, val, sizeof(q->sound_thanks));
900         } else if (!strcasecmp(param, "queue-callerannounce")) {
901                 ast_copy_string(q->sound_callerannounce, val, sizeof(q->sound_callerannounce));
902         } else if (!strcasecmp(param, "queue-reporthold")) {
903                 ast_copy_string(q->sound_reporthold, val, sizeof(q->sound_reporthold));
904         } else if (!strcasecmp(param, "announce-frequency")) {
905                 q->announcefrequency = atoi(val);
906         } else if (!strcasecmp(param, "min-announce-frequency")) {
907                 q->minannouncefrequency = atoi(val);
908                 ast_debug(1, "%s=%s for queue '%s'\n", param, val, q->name);
909         } else if (!strcasecmp(param, "announce-round-seconds")) {
910                 q->roundingseconds = atoi(val);
911                 /* Rounding to any other values just doesn't make sense... */
912                 if (!(q->roundingseconds == 0 || q->roundingseconds == 1 || q->roundingseconds == 5 || q->roundingseconds == 10
913                         || q->roundingseconds == 15 || q->roundingseconds == 20 || q->roundingseconds == 30)) {
914                         if (linenum >= 0) {
915                                 ast_log(LOG_WARNING, "'%s' isn't a valid value for %s "
916                                         "using 0 instead for queue '%s' at line %d of queues.conf\n",
917                                         val, param, q->name, linenum);
918                         } else {
919                                 ast_log(LOG_WARNING, "'%s' isn't a valid value for %s "
920                                         "using 0 instead for queue '%s'\n", val, param, q->name);
921                         }
922                         q->roundingseconds=0;
923                 }
924         } else if (!strcasecmp(param, "announce-holdtime")) {
925                 if (!strcasecmp(val, "once"))
926                         q->announceholdtime = ANNOUNCEHOLDTIME_ONCE;
927                 else if (ast_true(val))
928                         q->announceholdtime = ANNOUNCEHOLDTIME_ALWAYS;
929                 else
930                         q->announceholdtime = 0;
931         } else if (!strcasecmp(param, "periodic-announce")) {
932                 if (strchr(val, '|')) {
933                         char *s, *buf = ast_strdupa(val);
934                         unsigned int i = 0;
935
936                         while ((s = strsep(&buf, "|"))) {
937                                 ast_copy_string(q->sound_periodicannounce[i], s, sizeof(q->sound_periodicannounce[i]));
938                                 i++;
939                                 if (i == MAX_PERIODIC_ANNOUNCEMENTS)
940                                         break;
941                         }
942                 } else {
943                         ast_copy_string(q->sound_periodicannounce[0], val, sizeof(q->sound_periodicannounce[0]));
944                 }
945         } else if (!strcasecmp(param, "periodic-announce-frequency")) {
946                 q->periodicannouncefrequency = atoi(val);
947         } else if (!strcasecmp(param, "retry")) {
948                 q->retry = atoi(val);
949                 if (q->retry <= 0)
950                         q->retry = DEFAULT_RETRY;
951         } else if (!strcasecmp(param, "wrapuptime")) {
952                 q->wrapuptime = atoi(val);
953         } else if (!strcasecmp(param, "autofill")) {
954                 q->autofill = ast_true(val);
955         } else if (!strcasecmp(param, "monitor-type")) {
956                 if (!strcasecmp(val, "mixmonitor"))
957                         q->montype = 1;
958         } else if (!strcasecmp(param, "autopause")) {
959                 q->autopause = ast_true(val);
960         } else if (!strcasecmp(param, "maxlen")) {
961                 q->maxlen = atoi(val);
962                 if (q->maxlen < 0)
963                         q->maxlen = 0;
964         } else if (!strcasecmp(param, "servicelevel")) {
965                 q->servicelevel= atoi(val);
966         } else if (!strcasecmp(param, "strategy")) {
967                 q->strategy = strat2int(val);
968                 if (q->strategy < 0) {
969                         ast_log(LOG_WARNING, "'%s' isn't a valid strategy for queue '%s', using ringall instead\n",
970                                 val, q->name);
971                         q->strategy = QUEUE_STRATEGY_RINGALL;
972                 }
973         } else if (!strcasecmp(param, "joinempty")) {
974                 if (!strcasecmp(val, "loose"))
975                         q->joinempty = QUEUE_EMPTY_LOOSE;
976                 else if (!strcasecmp(val, "strict"))
977                         q->joinempty = QUEUE_EMPTY_STRICT;
978                 else if (ast_true(val))
979                         q->joinempty = QUEUE_EMPTY_NORMAL;
980                 else
981                         q->joinempty = 0;
982         } else if (!strcasecmp(param, "leavewhenempty")) {
983                 if (!strcasecmp(val, "loose"))
984                         q->leavewhenempty = QUEUE_EMPTY_LOOSE;
985                 else if (!strcasecmp(val, "strict"))
986                         q->leavewhenempty = QUEUE_EMPTY_STRICT;
987                 else if (ast_true(val))
988                         q->leavewhenempty = QUEUE_EMPTY_NORMAL;
989                 else
990                         q->leavewhenempty = 0;
991         } else if (!strcasecmp(param, "eventmemberstatus")) {
992                 q->maskmemberstatus = !ast_true(val);
993         } else if (!strcasecmp(param, "eventwhencalled")) {
994                 if (!strcasecmp(val, "vars")) {
995                         q->eventwhencalled = QUEUE_EVENT_VARIABLES;
996                 } else {
997                         q->eventwhencalled = ast_true(val);
998                 }
999         } else if (!strcasecmp(param, "reportholdtime")) {
1000                 q->reportholdtime = ast_true(val);
1001         } else if (!strcasecmp(param, "memberdelay")) {
1002                 q->memberdelay = atoi(val);
1003         } else if (!strcasecmp(param, "weight")) {
1004                 q->weight = atoi(val);
1005                 if (q->weight)
1006                         use_weight++;
1007                 /* With Realtime queues, if the last queue using weights is deleted in realtime,
1008                    we will not see any effect on use_weight until next reload. */
1009         } else if (!strcasecmp(param, "timeoutrestart")) {
1010                 q->timeoutrestart = ast_true(val);
1011         } else if (failunknown) {
1012                 if (linenum >= 0) {
1013                         ast_log(LOG_WARNING, "Unknown keyword in queue '%s': %s at line %d of queues.conf\n",
1014                                 q->name, param, linenum);
1015                 } else {
1016                         ast_log(LOG_WARNING, "Unknown keyword in queue '%s': %s\n", q->name, param);
1017                 }
1018         }
1019 }
1020
1021 static void rt_handle_member_record(struct call_queue *q, char *interface, const char *membername, const char *penalty_str, const char *paused_str)
1022 {
1023         struct member *m, *prev_m;
1024         int penalty = 0;
1025         int paused  = 0;
1026
1027         if (penalty_str) {
1028                 penalty = atoi(penalty_str);
1029                 if (penalty < 0)
1030                         penalty = 0;
1031         }
1032
1033         if (paused_str) {
1034                 paused = atoi(paused_str);
1035                 if (paused < 0)
1036                         paused = 0;
1037         }
1038
1039         /* Find the member, or the place to put a new one. */
1040         for (m = q->members, prev_m = NULL;
1041                 m && strcmp(m->interface, interface);
1042                 prev_m = m, m = m->next);
1043
1044         /* Create a new one if not found, else update penalty */
1045         if (!m) {
1046                 if ((m = create_queue_member(interface, membername, penalty, paused))) {
1047                         m->dead = 0;
1048                         add_to_interfaces(interface);
1049                         if (prev_m) {
1050                                 prev_m->next = m;
1051                         } else {
1052                                 q->members = m;
1053                         }
1054                 }
1055         } else {
1056                 m->dead = 0;    /* Do not delete this one. */
1057                 if (paused_str)
1058                         m->paused = paused;
1059                 m->penalty = penalty;
1060         }
1061 }
1062
1063 static void free_members(struct call_queue *q, int all)
1064 {
1065         /* Free non-dynamic members */
1066         struct member *curm, *next, *prev = NULL;
1067
1068         for (curm = q->members; curm; curm = next) {
1069                 next = curm->next;
1070                 if (all || !curm->dynamic) {
1071                         if (prev)
1072                                 prev->next = next;
1073                         else
1074                                 q->members = next;
1075                         remove_from_interfaces(curm->interface);
1076                         ast_free(curm);
1077                 } else
1078                         prev = curm;
1079         }
1080 }
1081
1082 static void destroy_queue(struct call_queue *q)
1083 {
1084         free_members(q, 1);
1085         ast_mutex_destroy(&q->lock);
1086         ast_free(q);
1087 }
1088
1089 /*!\brief Reload a single queue via realtime.
1090    \return Return the queue, or NULL if it doesn't exist.
1091    \note Should be called with the global qlock locked. */
1092 static struct call_queue *find_queue_by_name_rt(const char *queuename, struct ast_variable *queue_vars, struct ast_config *member_config)
1093 {
1094         struct ast_variable *v;
1095         struct call_queue *q;
1096         struct member *m, *prev_m, *next_m;
1097         char *interface = NULL;
1098         char *tmp, *tmp_name;
1099         char tmpbuf[64];        /* Must be longer than the longest queue param name. */
1100
1101         /* Find the queue in the in-core list (we will create a new one if not found). */
1102         AST_LIST_TRAVERSE(&queues, q, list) {
1103                 if (!strcasecmp(q->name, queuename))
1104                         break;
1105         }
1106
1107         /* Static queues override realtime. */
1108         if (q) {
1109                 ast_mutex_lock(&q->lock);
1110                 if (!q->realtime) {
1111                         if (q->dead) {
1112                                 ast_mutex_unlock(&q->lock);
1113                                 return NULL;
1114                         } else {
1115                                 ast_mutex_unlock(&q->lock);
1116                                 return q;
1117                         }
1118                 }
1119         } else if (!member_config)
1120                 /* Not found in the list, and it's not realtime ... */
1121                 return NULL;
1122
1123         /* Check if queue is defined in realtime. */
1124         if (!queue_vars) {
1125                 /* Delete queue from in-core list if it has been deleted in realtime. */
1126                 if (q) {
1127                         /*! \note Hmm, can't seem to distinguish a DB failure from a not
1128                            found condition... So we might delete an in-core queue
1129                            in case of DB failure. */
1130                         ast_debug(1, "Queue %s not found in realtime.\n", queuename);
1131
1132                         q->dead = 1;
1133                         /* Delete if unused (else will be deleted when last caller leaves). */
1134                         if (!q->count) {
1135                                 /* Delete. */
1136                                 AST_LIST_REMOVE(&queues, q, list);
1137                                 ast_mutex_unlock(&q->lock);
1138                                 destroy_queue(q);
1139                         } else
1140                                 ast_mutex_unlock(&q->lock);
1141                 }
1142                 return NULL;
1143         }
1144
1145         /* Create a new queue if an in-core entry does not exist yet. */
1146         if (!q) {
1147                 if (!(q = alloc_queue(queuename)))
1148                         return NULL;
1149                 ast_mutex_lock(&q->lock);
1150                 clear_queue(q);
1151                 q->realtime = 1;
1152                 AST_LIST_INSERT_HEAD(&queues, q, list);
1153         }
1154         init_queue(q);          /* Ensure defaults for all parameters not set explicitly. */
1155
1156         memset(tmpbuf, 0, sizeof(tmpbuf));
1157         for (v = queue_vars; v; v = v->next) {
1158                 /* Convert to dashes `-' from underscores `_' as the latter are more SQL friendly. */
1159                 if ((tmp = strchr(v->name, '_'))) {
1160                         ast_copy_string(tmpbuf, v->name, sizeof(tmpbuf));
1161                         tmp_name = tmpbuf;
1162                         tmp = tmp_name;
1163                         while ((tmp = strchr(tmp, '_')))
1164                                 *tmp++ = '-';
1165                 } else
1166                         tmp_name = v->name;
1167                 queue_set_param(q, tmp_name, v->value, -1, 0);
1168         }
1169
1170         /* Temporarily set non-dynamic members dead so we can detect deleted ones. */
1171         for (m = q->members; m; m = m->next) {
1172                 if (!m->dynamic)
1173                         m->dead = 1;
1174         }
1175
1176         while ((interface = ast_category_browse(member_config, interface))) {
1177                 rt_handle_member_record(q, interface,
1178                         S_OR(ast_variable_retrieve(member_config, interface, "membername"), interface),
1179                         ast_variable_retrieve(member_config, interface, "penalty"),
1180                         ast_variable_retrieve(member_config, interface, "paused"));
1181         }
1182
1183         /* Delete all realtime members that have been deleted in DB. */
1184         m = q->members;
1185         prev_m = NULL;
1186         while (m) {
1187                 next_m = m->next;
1188                 if (m->dead) {
1189                         if (prev_m) {
1190                                 prev_m->next = next_m;
1191                         } else {
1192                                 q->members = next_m;
1193                         }
1194                         remove_from_interfaces(m->interface);
1195                         ast_free(m);
1196                 } else {
1197                         prev_m = m;
1198                 }
1199                 m = next_m;
1200         }
1201
1202         ast_mutex_unlock(&q->lock);
1203
1204         return q;
1205 }
1206
1207 static struct call_queue *load_realtime_queue(const char *queuename)
1208 {
1209         struct ast_variable *queue_vars;
1210         struct ast_config *member_config = NULL;
1211         struct call_queue *q;
1212
1213         /* Find the queue in the in-core list first. */
1214         AST_LIST_LOCK(&queues);
1215         AST_LIST_TRAVERSE(&queues, q, list) {
1216                 if (!strcasecmp(q->name, queuename)) {
1217                         break;
1218                 }
1219         }
1220         AST_LIST_UNLOCK(&queues);
1221
1222         if (!q || q->realtime) {
1223                 /*! \note Load from realtime before taking the global qlock, to avoid blocking all
1224                    queue operations while waiting for the DB.
1225
1226                    This will be two separate database transactions, so we might
1227                    see queue parameters as they were before another process
1228                    changed the queue and member list as it was after the change.
1229                    Thus we might see an empty member list when a queue is
1230                    deleted. In practise, this is unlikely to cause a problem. */
1231
1232                 queue_vars = ast_load_realtime("queues", "name", queuename, NULL);
1233                 if (queue_vars) {
1234                         member_config = ast_load_realtime_multientry("queue_members", "interface LIKE", "%", "queue_name", queuename, NULL);
1235                         if (!member_config) {
1236                                 ast_log(LOG_ERROR, "no queue_members defined in your config (extconfig.conf).\n");
1237                                 return NULL;
1238                         }
1239                 }
1240
1241                 AST_LIST_LOCK(&queues);
1242
1243                 q = find_queue_by_name_rt(queuename, queue_vars, member_config);
1244                 if (member_config)
1245                         ast_config_destroy(member_config);
1246                 if (queue_vars)
1247                         ast_variables_destroy(queue_vars);
1248
1249                 AST_LIST_UNLOCK(&queues);
1250         }
1251         return q;
1252 }
1253
1254 static int join_queue(char *queuename, struct queue_ent *qe, enum queue_result *reason)
1255 {
1256         struct call_queue *q;
1257         struct queue_ent *cur, *prev = NULL;
1258         int res = -1;
1259         int pos = 0;
1260         int inserted = 0;
1261         enum queue_member_status stat;
1262
1263         if (!(q = load_realtime_queue(queuename)))
1264                 return res;
1265
1266         AST_LIST_LOCK(&queues);
1267         ast_mutex_lock(&q->lock);
1268
1269         /* This is our one */
1270         stat = get_member_status(q, qe->max_penalty);
1271         if (!q->joinempty && (stat == QUEUE_NO_MEMBERS))
1272                 *reason = QUEUE_JOINEMPTY;
1273         else if ((q->joinempty == QUEUE_EMPTY_STRICT) && (stat == QUEUE_NO_REACHABLE_MEMBERS || stat == QUEUE_NO_UNPAUSED_REACHABLE_MEMBERS))
1274                 *reason = QUEUE_JOINUNAVAIL;
1275         else if ((q->joinempty == QUEUE_EMPTY_LOOSE) && (stat == QUEUE_NO_REACHABLE_MEMBERS))
1276                 *reason = QUEUE_JOINUNAVAIL;
1277         else if (q->maxlen && (q->count >= q->maxlen))
1278                 *reason = QUEUE_FULL;
1279         else {
1280                 /* There's space for us, put us at the right position inside
1281                  * the queue.
1282                  * Take into account the priority of the calling user */
1283                 inserted = 0;
1284                 prev = NULL;
1285                 cur = q->head;
1286                 while (cur) {
1287                         /* We have higher priority than the current user, enter
1288                          * before him, after all the other users with priority
1289                          * higher or equal to our priority. */
1290                         if ((!inserted) && (qe->prio > cur->prio)) {
1291                                 insert_entry(q, prev, qe, &pos);
1292                                 inserted = 1;
1293                         }
1294                         cur->pos = ++pos;
1295                         prev = cur;
1296                         cur = cur->next;
1297                 }
1298                 /* No luck, join at the end of the queue */
1299                 if (!inserted)
1300                         insert_entry(q, prev, qe, &pos);
1301                 ast_copy_string(qe->moh, q->moh, sizeof(qe->moh));
1302                 ast_copy_string(qe->announce, q->announce, sizeof(qe->announce));
1303                 ast_copy_string(qe->context, q->context, sizeof(qe->context));
1304                 q->count++;
1305                 res = 0;
1306                 manager_event(EVENT_FLAG_CALL, "Join",
1307                         "Channel: %s\r\nCallerID: %s\r\nCallerIDName: %s\r\nQueue: %s\r\nPosition: %d\r\nCount: %d\r\nUniqueid: %s\r\n",
1308                         qe->chan->name,
1309                         S_OR(qe->chan->cid.cid_num, "unknown"), /* XXX somewhere else it is <unknown> */
1310                         S_OR(qe->chan->cid.cid_name, "unknown"),
1311                         q->name, qe->pos, q->count, qe->chan->uniqueid );
1312                 ast_debug(1, "Queue '%s' Join, Channel '%s', Position '%d'\n", q->name, qe->chan->name, qe->pos );
1313         }
1314         ast_mutex_unlock(&q->lock);
1315         AST_LIST_UNLOCK(&queues);
1316
1317         return res;
1318 }
1319
1320 static int play_file(struct ast_channel *chan, char *filename)
1321 {
1322         int res;
1323
1324         ast_stopstream(chan);
1325         res = ast_streamfile(chan, filename, chan->language);
1326         if (!res)
1327                 res = ast_waitstream(chan, AST_DIGIT_ANY);
1328         ast_stopstream(chan);
1329
1330         return res;
1331 }
1332
1333 static int valid_exit(struct queue_ent *qe, char digit)
1334 {
1335         int digitlen = strlen(qe->digits);
1336
1337         /* Prevent possible buffer overflow */
1338         if (digitlen < sizeof(qe->digits) - 2) {
1339                 qe->digits[digitlen] = digit;
1340                 qe->digits[digitlen + 1] = '\0';
1341         } else {
1342                 qe->digits[0] = '\0';
1343                 return 0;
1344         }
1345
1346         /* If there's no context to goto, short-circuit */
1347         if (ast_strlen_zero(qe->context))
1348                 return 0;
1349
1350         /* If the extension is bad, then reset the digits to blank */
1351         if (!ast_canmatch_extension(qe->chan, qe->context, qe->digits, 1, qe->chan->cid.cid_num)) {
1352                 qe->digits[0] = '\0';
1353                 return 0;
1354         }
1355
1356         /* We have an exact match */
1357         if (!ast_goto_if_exists(qe->chan, qe->context, qe->digits, 1)) {
1358                 /* Return 1 on a successful goto */
1359                 return 1;
1360         }
1361
1362         return 0;
1363 }
1364
1365 static int say_position(struct queue_ent *qe)
1366 {
1367         int res = 0, avgholdmins, avgholdsecs;
1368         time_t now;
1369
1370         /* Let minannouncefrequency seconds pass between the start of each position announcement */
1371         time(&now);
1372         if ((now - qe->last_pos) < qe->parent->minannouncefrequency)
1373                 return 0;
1374
1375         /* If either our position has changed, or we are over the freq timer, say position */
1376         if ((qe->last_pos_said == qe->pos) && ((now - qe->last_pos) < qe->parent->announcefrequency))
1377                 return 0;
1378
1379         ast_moh_stop(qe->chan);
1380         /* Say we're next, if we are */
1381         if (qe->pos == 1) {
1382                 res = play_file(qe->chan, qe->parent->sound_next);
1383                 if (res && valid_exit(qe, res))
1384                         goto playout;
1385                 else
1386                         goto posout;
1387         } else {
1388                 res = play_file(qe->chan, qe->parent->sound_thereare);
1389                 if (res && valid_exit(qe, res))
1390                         goto playout;
1391                 res = ast_say_number(qe->chan, qe->pos, AST_DIGIT_ANY, qe->chan->language, (char *) NULL); /* Needs gender */
1392                 if (res && valid_exit(qe, res))
1393                         goto playout;
1394                 res = play_file(qe->chan, qe->parent->sound_calls);
1395                 if (res && valid_exit(qe, res))
1396                         goto playout;
1397         }
1398         /* Round hold time to nearest minute */
1399         avgholdmins = abs(((qe->parent->holdtime + 30) - (now - qe->start)) / 60);
1400
1401         /* If they have specified a rounding then round the seconds as well */
1402         if (qe->parent->roundingseconds) {
1403                 avgholdsecs = (abs(((qe->parent->holdtime + 30) - (now - qe->start))) - 60 * avgholdmins) / qe->parent->roundingseconds;
1404                 avgholdsecs *= qe->parent->roundingseconds;
1405         } else {
1406                 avgholdsecs = 0;
1407         }
1408
1409         if (option_verbose > 2)
1410                 ast_verbose(VERBOSE_PREFIX_3 "Hold time for %s is %d minutes %d seconds\n", qe->parent->name, avgholdmins, avgholdsecs);
1411
1412         /* If the hold time is >1 min, if it's enabled, and if it's not
1413            supposed to be only once and we have already said it, say it */
1414         if ((avgholdmins+avgholdsecs) > 0 && (qe->parent->announceholdtime) &&
1415                 (!(qe->parent->announceholdtime == ANNOUNCEHOLDTIME_ONCE) && qe->last_pos)) {
1416                 res = play_file(qe->chan, qe->parent->sound_holdtime);
1417                 if (res && valid_exit(qe, res))
1418                         goto playout;
1419
1420                 if (avgholdmins > 0) {
1421                         if (avgholdmins < 2) {
1422                                 res = play_file(qe->chan, qe->parent->sound_lessthan);
1423                                 if (res && valid_exit(qe, res))
1424                                         goto playout;
1425
1426                                 res = ast_say_number(qe->chan, 2, AST_DIGIT_ANY, qe->chan->language, NULL);
1427                                 if (res && valid_exit(qe, res))
1428                                         goto playout;
1429                         } else {
1430                                 res = ast_say_number(qe->chan, avgholdmins, AST_DIGIT_ANY, qe->chan->language, NULL);
1431                                 if (res && valid_exit(qe, res))
1432                                         goto playout;
1433                         }
1434                         
1435                         res = play_file(qe->chan, qe->parent->sound_minutes);
1436                         if (res && valid_exit(qe, res))
1437                                 goto playout;
1438                 }
1439                 if (avgholdsecs>0) {
1440                         res = ast_say_number(qe->chan, avgholdsecs, AST_DIGIT_ANY, qe->chan->language, NULL);
1441                         if (res && valid_exit(qe, res))
1442                                 goto playout;
1443
1444                         res = play_file(qe->chan, qe->parent->sound_seconds);
1445                         if (res && valid_exit(qe, res))
1446                                 goto playout;
1447                 }
1448
1449         }
1450
1451 posout:
1452         if (option_verbose > 2)
1453                 ast_verbose(VERBOSE_PREFIX_3 "Told %s in %s their queue position (which was %d)\n",
1454                         qe->chan->name, qe->parent->name, qe->pos);
1455         res = play_file(qe->chan, qe->parent->sound_thanks);
1456         if (res && !valid_exit(qe, res))
1457                 res = 0;
1458
1459 playout:
1460         /* Set our last_pos indicators */
1461         qe->last_pos = now;
1462         qe->last_pos_said = qe->pos;
1463
1464         /* Don't restart music on hold if we're about to exit the caller from the queue */
1465         if (!res)
1466                 ast_moh_start(qe->chan, qe->moh, NULL);
1467
1468         return res;
1469 }
1470
1471 static void recalc_holdtime(struct queue_ent *qe)
1472 {
1473         int oldvalue, newvalue;
1474
1475         /* Calculate holdtime using a recursive boxcar filter */
1476         /* Thanks to SRT for this contribution */
1477         /* 2^2 (4) is the filter coefficient; a higher exponent would give old entries more weight */
1478
1479         newvalue = time(NULL) - qe->start;
1480
1481         ast_mutex_lock(&qe->parent->lock);
1482         if (newvalue <= qe->parent->servicelevel)
1483                 qe->parent->callscompletedinsl++;
1484         oldvalue = qe->parent->holdtime;
1485         qe->parent->holdtime = (((oldvalue << 2) - oldvalue) + newvalue) >> 2;
1486         ast_mutex_unlock(&qe->parent->lock);
1487 }
1488
1489
1490 static void leave_queue(struct queue_ent *qe)
1491 {
1492         struct call_queue *q;
1493         struct queue_ent *cur, *prev = NULL;
1494         int pos = 0;
1495
1496         if (!(q = qe->parent))
1497                 return;
1498         ast_mutex_lock(&q->lock);
1499
1500         prev = NULL;
1501         for (cur = q->head; cur; cur = cur->next) {
1502                 if (cur == qe) {
1503                         q->count--;
1504
1505                         /* Take us out of the queue */
1506                         manager_event(EVENT_FLAG_CALL, "Leave",
1507                                 "Channel: %s\r\nQueue: %s\r\nCount: %d\r\nUniqueid: %s\r\n",
1508                                 qe->chan->name, q->name,  q->count, qe->chan->uniqueid);
1509                         ast_debug(1, "Queue '%s' Leave, Channel '%s'\n", q->name, qe->chan->name );
1510                         /* Take us out of the queue */
1511                         if (prev)
1512                                 prev->next = cur->next;
1513                         else
1514                                 q->head = cur->next;
1515                 } else {
1516                         /* Renumber the people after us in the queue based on a new count */
1517                         cur->pos = ++pos;
1518                         prev = cur;
1519                 }
1520         }
1521         ast_mutex_unlock(&q->lock);
1522
1523         if (q->dead && !q->count) {     
1524                 /* It's dead and nobody is in it, so kill it */
1525                 AST_LIST_LOCK(&queues);
1526                 AST_LIST_REMOVE(&queues, q, list);
1527                 AST_LIST_UNLOCK(&queues);
1528                 destroy_queue(q);
1529         }
1530 }
1531
1532 /* Hang up a list of outgoing calls */
1533 static void hangupcalls(struct callattempt *outgoing, struct ast_channel *exception)
1534 {
1535         struct callattempt *oo;
1536
1537         while (outgoing) {
1538                 /* Hangup any existing lines we have open */
1539                 if (outgoing->chan && (outgoing->chan != exception))
1540                         ast_hangup(outgoing->chan);
1541                 oo = outgoing;
1542                 outgoing = outgoing->q_next;
1543                 ast_free(oo);
1544         }
1545 }
1546
1547 static int update_status(struct call_queue *q, struct member *member, int status)
1548 {
1549         struct member *cur;
1550
1551         /* Since a reload could have taken place, we have to traverse the list to
1552                 be sure it's still valid */
1553         ast_mutex_lock(&q->lock);
1554         for (cur = q->members; cur; cur = cur->next) {
1555                 if (member != cur)
1556                         continue;
1557
1558                 cur->status = status;
1559                 if (!q->maskmemberstatus) {
1560                         manager_event(EVENT_FLAG_AGENT, "QueueMemberStatus",
1561                                 "Queue: %s\r\n"
1562                                 "Location: %s\r\n"
1563                                 "MemberName: %s\r\n"
1564                                 "Membership: %s\r\n"
1565                                 "Penalty: %d\r\n"
1566                                 "CallsTaken: %d\r\n"
1567                                 "LastCall: %d\r\n"
1568                                 "Status: %d\r\n"
1569                                 "Paused: %d\r\n",
1570                                 q->name, cur->interface, cur->membername, cur->dynamic ? "dynamic" : "static",
1571                                 cur->penalty, cur->calls, (int)cur->lastcall, cur->status, cur->paused);
1572                 }
1573         }
1574         ast_mutex_unlock(&q->lock);
1575         return 0;
1576 }
1577
1578 static int update_dial_status(struct call_queue *q, struct member *member, int status)
1579 {
1580         if (status == AST_CAUSE_BUSY)
1581                 status = AST_DEVICE_BUSY;
1582         else if (status == AST_CAUSE_UNREGISTERED)
1583                 status = AST_DEVICE_UNAVAILABLE;
1584         else if (status == AST_CAUSE_NOSUCHDRIVER)
1585                 status = AST_DEVICE_INVALID;
1586         else
1587                 status = AST_DEVICE_UNKNOWN;
1588         return update_status(q, member, status);
1589 }
1590
1591 /* traverse all defined queues which have calls waiting and contain this member
1592    return 0 if no other queue has precedence (higher weight) or 1 if found  */
1593 static int compare_weight(struct call_queue *rq, struct member *member)
1594 {
1595         struct call_queue *q;
1596         struct member *mem;
1597         int found = 0;
1598         
1599         /* &qlock and &rq->lock already set by try_calling()
1600          * to solve deadlock */
1601         AST_LIST_TRAVERSE(&queues, q, list) {
1602                 if (q == rq) /* don't check myself, could deadlock */
1603                         continue;
1604                 ast_mutex_lock(&q->lock);
1605                 if (q->count && q->members) {
1606                         for (mem = q->members; mem; mem = mem->next) {
1607                                 if (strcmp(mem->interface, member->interface))
1608                                         continue;
1609
1610                                 ast_debug(1, "Found matching member %s in queue '%s'\n", mem->interface, q->name);
1611                                 if (q->weight > rq->weight) {
1612                                         ast_debug(1, "Queue '%s' (weight %d, calls %d) is preferred over '%s' (weight %d, calls %d)\n", q->name, q->weight, q->count, rq->name, rq->weight, rq->count);
1613                                         found = 1;
1614                                         break;
1615                                 }
1616                         }
1617                 }
1618                 ast_mutex_unlock(&q->lock);
1619                 if (found)
1620                         break;
1621         }
1622         return found;
1623 }
1624
1625 /*! \brief common hangup actions */
1626 static void do_hang(struct callattempt *o)
1627 {
1628         o->stillgoing = 0;
1629         ast_hangup(o->chan);
1630         o->chan = NULL;
1631 }
1632
1633 static char *vars2manager(struct ast_channel *chan, char *vars, size_t len)
1634 {
1635         struct ast_str *buf = ast_str_alloca(len + 1);
1636         char *tmp;
1637
1638         if (pbx_builtin_serialize_variables(chan, &buf)) {
1639                 int i, j;
1640
1641                 /* convert "\n" to "\nVariable: " */
1642                 strcpy(vars, "Variable: ");
1643                 tmp = buf->str;
1644
1645                 for (i = 0, j = 10; (i < len - 1) && (j < len - 1); i++, j++) {
1646                         vars[j] = tmp[i];
1647
1648                         if (tmp[i + 1] == '\0')
1649                                 break;
1650                         if (tmp[i] == '\n') {
1651                                 vars[j] = '\r';
1652                                 vars[++j] = '\n';
1653
1654                                 ast_copy_string(&(vars[j]), "Variable: ", len - j);
1655                                 j += 9;
1656                         }
1657                 }
1658                 if (j > len - 1)
1659                         j = len - 1;
1660                 vars[j - 2] = '\r';
1661                 vars[j - 1] = '\n';
1662                 vars[j] = '\0';
1663         } else {
1664                 /* there are no channel variables; leave it blank */
1665                 *vars = '\0';
1666         }
1667         return vars;
1668 }
1669
1670 static int ring_entry(struct queue_ent *qe, struct callattempt *tmp, int *busies)
1671 {
1672         int res;
1673         int status;
1674         char tech[256];
1675         char *location;
1676
1677         /* on entry here, we know that tmp->chan == NULL */
1678         if (qe->parent->wrapuptime && (time(NULL) - tmp->lastcall < qe->parent->wrapuptime)) {
1679                 ast_debug(1, "Wrapuptime not yet expired for %s\n", tmp->interface);
1680                 if (qe->chan->cdr)
1681                         ast_cdr_busy(qe->chan->cdr);
1682                 tmp->stillgoing = 0;
1683                 (*busies)++;
1684                 return 0;
1685         }
1686
1687         if (!qe->parent->ringinuse && (tmp->member->status != AST_DEVICE_NOT_INUSE) && (tmp->member->status != AST_DEVICE_UNKNOWN)) {
1688                 ast_debug(1, "%s in use, can't receive call\n", tmp->interface);
1689                 if (qe->chan->cdr)
1690                         ast_cdr_busy(qe->chan->cdr);
1691                 tmp->stillgoing = 0;
1692                 return 0;
1693         }
1694
1695         if (tmp->member->paused) {
1696                 ast_debug(1, "%s paused, can't receive call\n", tmp->interface);
1697                 if (qe->chan->cdr)
1698                         ast_cdr_busy(qe->chan->cdr);
1699                 tmp->stillgoing = 0;
1700                 return 0;
1701         }
1702         if (use_weight && compare_weight(qe->parent,tmp->member)) {
1703                 ast_debug(1, "Priority queue delaying call to %s:%s\n", qe->parent->name, tmp->interface);
1704                 if (qe->chan->cdr)
1705                         ast_cdr_busy(qe->chan->cdr);
1706                 tmp->stillgoing = 0;
1707                 (*busies)++;
1708                 return 0;
1709         }
1710
1711         ast_copy_string(tech, tmp->interface, sizeof(tech));
1712         if ((location = strchr(tech, '/')))
1713                 *location++ = '\0';
1714         else
1715                 location = "";
1716
1717         /* Request the peer */
1718         tmp->chan = ast_request(tech, qe->chan->nativeformats, location, &status);
1719         if (!tmp->chan) {                       /* If we can't, just go on to the next call */
1720                 if (qe->chan->cdr)
1721                         ast_cdr_busy(qe->chan->cdr);
1722                 tmp->stillgoing = 0;
1723                 update_dial_status(qe->parent, tmp->member, status);
1724
1725                 ast_mutex_lock(&qe->parent->lock);
1726                 qe->parent->rrpos++;
1727                 ast_mutex_unlock(&qe->parent->lock);
1728
1729                 (*busies)++;
1730                 return 0;
1731         } else if (status != tmp->oldstatus)
1732                 update_dial_status(qe->parent, tmp->member, status);
1733         
1734         tmp->chan->appl = "AppQueue";
1735         tmp->chan->data = "(Outgoing Line)";
1736         tmp->chan->whentohangup = 0;
1737         if (tmp->chan->cid.cid_num)
1738                 ast_free(tmp->chan->cid.cid_num);
1739         tmp->chan->cid.cid_num = ast_strdup(qe->chan->cid.cid_num);
1740         if (tmp->chan->cid.cid_name)
1741                 ast_free(tmp->chan->cid.cid_name);
1742         tmp->chan->cid.cid_name = ast_strdup(qe->chan->cid.cid_name);
1743         if (tmp->chan->cid.cid_ani)
1744                 ast_free(tmp->chan->cid.cid_ani);
1745         tmp->chan->cid.cid_ani = ast_strdup(qe->chan->cid.cid_ani);
1746
1747         /* Inherit specially named variables from parent channel */
1748         ast_channel_inherit_variables(qe->chan, tmp->chan);
1749
1750         /* Presense of ADSI CPE on outgoing channel follows ours */
1751         tmp->chan->adsicpe = qe->chan->adsicpe;
1752
1753         /* Place the call, but don't wait on the answer */
1754         if ((res = ast_call(tmp->chan, location, 0))) {
1755                 /* Again, keep going even if there's an error */
1756                 ast_debug(1, "ast call on peer returned %d\n", res);
1757                 if (option_verbose > 2)
1758                         ast_verbose(VERBOSE_PREFIX_3 "Couldn't call %s\n", tmp->interface);
1759                 do_hang(tmp);
1760                 (*busies)++;
1761                 return 0;
1762         } else if (qe->parent->eventwhencalled) {
1763                 char vars[2048];
1764
1765                 manager_event(EVENT_FLAG_AGENT, "AgentCalled",
1766                                         "Queue: %s\r\n"
1767                                         "AgentCalled: %s\r\n"
1768                                         "ChannelCalling: %s\r\n"
1769                                         "DestinationChannel: %s\r\n"
1770                                         "CallerIDNum: %s\r\n"
1771                                         "CallerIDName: %s\r\n"
1772                                         "Context: %s\r\n"
1773                                         "Extension: %s\r\n"
1774                                         "Priority: %d\r\n"
1775                                         "%s",
1776                                         qe->parent->name, tmp->interface, qe->chan->name, tmp->chan->name,
1777                                         tmp->chan->cid.cid_num ? tmp->chan->cid.cid_num : "unknown",
1778                                         tmp->chan->cid.cid_name ? tmp->chan->cid.cid_name : "unknown",
1779                                         qe->chan->context, qe->chan->exten, qe->chan->priority,
1780                                         qe->parent->eventwhencalled == QUEUE_EVENT_VARIABLES ? vars2manager(qe->chan, vars, sizeof(vars)) : "");
1781                 if (option_verbose > 2)
1782                         ast_verbose(VERBOSE_PREFIX_3 "Called %s\n", tmp->interface);
1783         }
1784
1785         return 1;
1786 }
1787
1788 /*! \brief find the entry with the best metric, or NULL */
1789 static struct callattempt *find_best(struct callattempt *outgoing)
1790 {
1791         struct callattempt *best = NULL, *cur;
1792
1793         for (cur = outgoing; cur; cur = cur->q_next) {
1794                 if (cur->stillgoing &&                                  /* Not already done */
1795                         !cur->chan &&                                   /* Isn't already going */
1796                         (!best || cur->metric < best->metric)) {                /* We haven't found one yet, or it's better */
1797                         best = cur;
1798                 }
1799         }
1800
1801         return best;
1802 }
1803
1804 static int ring_one(struct queue_ent *qe, struct callattempt *outgoing, int *busies)
1805 {
1806         int ret = 0;
1807
1808         while (ret == 0) {
1809                 struct callattempt *best = find_best(outgoing);
1810                 if (!best) {
1811                         ast_debug(1, "Nobody left to try ringing in queue\n");
1812                         break;
1813                 }
1814                 if (qe->parent->strategy == QUEUE_STRATEGY_RINGALL) {
1815                         struct callattempt *cur;
1816                         /* Ring everyone who shares this best metric (for ringall) */
1817                         for (cur = outgoing; cur; cur = cur->q_next) {
1818                                 if (cur->stillgoing && !cur->chan && cur->metric <= best->metric) {
1819                                         ast_debug(1, "(Parallel) Trying '%s' with metric %d\n", cur->interface, cur->metric);
1820                                         ring_entry(qe, cur, busies);
1821                                 }
1822                         }
1823                 } else {
1824                         /* Ring just the best channel */
1825                         ast_debug(1, "Trying '%s' with metric %d\n", best->interface, best->metric);
1826                         ring_entry(qe, best, busies);
1827                 }
1828                 if (best->chan) /* break out with result = 1 */
1829                         ret = 1;
1830         }
1831
1832         return ret;
1833 }
1834
1835 static int store_next(struct queue_ent *qe, struct callattempt *outgoing)
1836 {
1837         struct callattempt *best = find_best(outgoing);
1838
1839         if (best) {
1840                 /* Ring just the best channel */
1841                 ast_debug(1, "Next is '%s' with metric %d\n", best->interface, best->metric);
1842                 qe->parent->rrpos = best->metric % 1000;
1843         } else {
1844                 /* Just increment rrpos */
1845                 if (qe->parent->wrapped) {
1846                         /* No more channels, start over */
1847                         qe->parent->rrpos = 0;
1848                 } else {
1849                         /* Prioritize next entry */
1850                         qe->parent->rrpos++;
1851                 }
1852         }
1853         qe->parent->wrapped = 0;
1854
1855         return 0;
1856 }
1857
1858 static int background_file(struct queue_ent *qe, struct ast_channel *chan, char *filename)
1859 {
1860         int res;
1861
1862         ast_stopstream(chan);
1863         res = ast_streamfile(chan, filename, chan->language);
1864
1865         if (!res) {
1866                 /* Wait for a keypress */
1867                 res = ast_waitstream(chan, AST_DIGIT_ANY);
1868                 if (res < 0 || !valid_exit(qe, res))
1869                         res = 0;
1870
1871                 /* Stop playback */
1872                 ast_stopstream(chan);
1873         }
1874         
1875         return res;
1876 }
1877
1878 static int say_periodic_announcement(struct queue_ent *qe)
1879 {
1880         int res = 0;
1881         time_t now;
1882
1883         /* Get the current time */
1884         time(&now);
1885
1886         /* Check to see if it is time to announce */
1887         if ((now - qe->last_periodic_announce_time) < qe->parent->periodicannouncefrequency)
1888                 return 0;
1889
1890         /* Stop the music on hold so we can play our own file */
1891         ast_moh_stop(qe->chan);
1892
1893         if (option_verbose > 2)
1894                 ast_verbose(VERBOSE_PREFIX_3 "Playing periodic announcement\n");
1895
1896         /* Check to make sure we have a sound file. If not, reset to the first sound file */
1897         if (qe->last_periodic_announce_sound >= MAX_PERIODIC_ANNOUNCEMENTS || !strlen(qe->parent->sound_periodicannounce[qe->last_periodic_announce_sound])) {
1898                 qe->last_periodic_announce_sound = 0;
1899         }
1900         
1901         /* play the announcement */
1902         res = background_file(qe, qe->chan, qe->parent->sound_periodicannounce[qe->last_periodic_announce_sound]);
1903
1904         /* Resume Music on Hold if the caller is going to stay in the queue */
1905         if (!res)
1906                 ast_moh_start(qe->chan, qe->moh, NULL);
1907
1908         /* update last_periodic_announce_time */
1909         qe->last_periodic_announce_time = now;
1910
1911         /* Update the current periodic announcement to the next announcement */
1912         qe->last_periodic_announce_sound++;
1913         
1914         return res;
1915 }
1916
1917 static void record_abandoned(struct queue_ent *qe)
1918 {
1919         ast_mutex_lock(&qe->parent->lock);
1920         set_queue_variables(qe);
1921         manager_event(EVENT_FLAG_AGENT, "QueueCallerAbandon",
1922                 "Queue: %s\r\n"
1923                 "Uniqueid: %s\r\n"
1924                 "Position: %d\r\n"
1925                 "OriginalPosition: %d\r\n"
1926                 "HoldTime: %d\r\n",
1927                 qe->parent->name, qe->chan->uniqueid, qe->pos, qe->opos, (int)(time(NULL) - qe->start));
1928
1929         qe->parent->callsabandoned++;
1930         ast_mutex_unlock(&qe->parent->lock);
1931 }
1932
1933 /*! \brief RNA == Ring No Answer. Common code that is executed when we try a queue member and they don't answer. */
1934 static void rna(int rnatime, struct queue_ent *qe, char *interface, char *membername)
1935 {
1936         if (option_verbose > 2)
1937                 ast_verbose( VERBOSE_PREFIX_3 "Nobody picked up in %d ms\n", rnatime);
1938         ast_queue_log(qe->parent->name, qe->chan->uniqueid, membername, "RINGNOANSWER", "%d", rnatime);
1939         if (qe->parent->autopause) {
1940                 if (!set_member_paused(qe->parent->name, interface, 1)) {
1941                         if (option_verbose > 2)
1942                                 ast_verbose( VERBOSE_PREFIX_3 "Auto-Pausing Queue Member %s in queue %s since they failed to answer.\n", interface, qe->parent->name);
1943                 } else {
1944                         if (option_verbose > 2)
1945                                 ast_verbose( VERBOSE_PREFIX_3 "Failed to pause Queue Member %s in queue %s!\n", interface, qe->parent->name);
1946                 }
1947         }
1948         return;
1949 }
1950
1951 #define AST_MAX_WATCHERS 256
1952
1953 static struct callattempt *wait_for_answer(struct queue_ent *qe, struct callattempt *outgoing, int *to, char *digit, int prebusies, int caller_disconnect, int forwardsallowed)
1954 {
1955         char *queue = qe->parent->name;
1956         struct callattempt *o;
1957         int status;
1958         int sentringing = 0;
1959         int numbusies = prebusies;
1960         int numnochan = 0;
1961         int stillgoing = 0;
1962         int orig = *to;
1963         struct ast_frame *f;
1964         struct callattempt *peer = NULL;
1965         struct ast_channel *winner;
1966         struct ast_channel *in = qe->chan;
1967         char on[80] = "";
1968         char membername[80] = "";
1969         long starttime = 0;
1970         long endtime = 0;       
1971
1972         starttime = (long) time(NULL);
1973         
1974         while (*to && !peer) {
1975                 int numlines, retry, pos = 1;
1976                 struct ast_channel *watchers[AST_MAX_WATCHERS];
1977                 watchers[0] = in;
1978
1979                 for (retry = 0; retry < 2; retry++) {
1980                         numlines = 0;
1981                         for (o = outgoing; o; o = o->q_next) { /* Keep track of important channels */
1982                                 if (o->stillgoing) {    /* Keep track of important channels */
1983                                         stillgoing = 1;
1984                                         if (o->chan)
1985                                                 watchers[pos++] = o->chan;
1986                                 }
1987                                 numlines++;
1988                         }
1989                         if (pos > 1 /* found */ || !stillgoing /* nobody listening */ ||
1990                                 (qe->parent->strategy != QUEUE_STRATEGY_RINGALL) /* ring would not be delivered */)
1991                                 break;
1992                         /* On "ringall" strategy we only move to the next penalty level
1993                            when *all* ringing phones are done in the current penalty level */
1994                         ring_one(qe, outgoing, &numbusies);
1995                         /* and retry... */
1996                 }
1997                 if (pos == 1 /* not found */) {
1998                         if (numlines == (numbusies + numnochan)) {
1999                                 ast_debug(1, "Everyone is busy at this time\n");
2000                         } else {
2001                                 ast_log(LOG_NOTICE, "No one is answering queue '%s' (%d/%d/%d)\n", queue, numlines, numbusies, numnochan);
2002                         }
2003                         *to = 0;
2004                         return NULL;
2005                 }
2006                 winner = ast_waitfor_n(watchers, pos, to);
2007                 for (o = outgoing; o; o = o->q_next) {
2008                         if (o->stillgoing && (o->chan) &&  (o->chan->_state == AST_STATE_UP)) {
2009                                 if (!peer) {
2010                                         if (option_verbose > 2)
2011                                                 ast_verbose( VERBOSE_PREFIX_3 "%s answered %s\n", o->chan->name, in->name);
2012                                         peer = o;
2013                                 }
2014                         } else if (o->chan && (o->chan == winner)) {
2015
2016                                 ast_copy_string(on, o->member->interface, sizeof(on));
2017                                 ast_copy_string(membername, o->member->membername, sizeof(membername));
2018
2019                                 if (!ast_strlen_zero(o->chan->call_forward) && !forwardsallowed) {
2020                                         if (option_verbose > 2)
2021                                                 ast_verbose(VERBOSE_PREFIX_3 "Forwarding %s to '%s' prevented.\n", in->name, o->chan->call_forward);
2022                                         numnochan++;
2023                                         do_hang(o);
2024                                         winner = NULL;
2025                                         continue;
2026                                 } else if (!ast_strlen_zero(o->chan->call_forward)) {
2027                                         char tmpchan[256];
2028                                         char *stuff;
2029                                         char *tech;
2030
2031                                         ast_copy_string(tmpchan, o->chan->call_forward, sizeof(tmpchan));
2032                                         if ((stuff = strchr(tmpchan, '/'))) {
2033                                                 *stuff++ = '\0';
2034                                                 tech = tmpchan;
2035                                         } else {
2036                                                 snprintf(tmpchan, sizeof(tmpchan), "%s@%s", o->chan->call_forward, o->chan->context);
2037                                                 stuff = tmpchan;
2038                                                 tech = "Local";
2039                                         }
2040                                         /* Before processing channel, go ahead and check for forwarding */
2041                                         if (option_verbose > 2)
2042                                                 ast_verbose(VERBOSE_PREFIX_3 "Now forwarding %s to '%s/%s' (thanks to %s)\n", in->name, tech, stuff, o->chan->name);
2043                                         /* Setup parameters */
2044                                         o->chan = ast_request(tech, in->nativeformats, stuff, &status);
2045                                         if (status != o->oldstatus)
2046                                                 update_dial_status(qe->parent, o->member, status);                                              
2047                                         if (!o->chan) {
2048                                                 ast_log(LOG_NOTICE, "Unable to create local channel for call forward to '%s/%s'\n", tech, stuff);
2049                                                 o->stillgoing = 0;
2050                                                 numnochan++;
2051                                         } else {
2052                                                 ast_channel_inherit_variables(in, o->chan);
2053                                                 if (o->chan->cid.cid_num)
2054                                                         ast_free(o->chan->cid.cid_num);
2055                                                 o->chan->cid.cid_num = ast_strdup(in->cid.cid_num);
2056
2057                                                 if (o->chan->cid.cid_name)
2058                                                         ast_free(o->chan->cid.cid_name);
2059                                                 o->chan->cid.cid_name = ast_strdup(in->cid.cid_name);
2060
2061                                                 ast_string_field_set(o->chan, accountcode, in->accountcode);
2062                                                 o->chan->cdrflags = in->cdrflags;
2063
2064                                                 if (in->cid.cid_ani) {
2065                                                         if (o->chan->cid.cid_ani)
2066                                                                 ast_free(o->chan->cid.cid_ani);
2067                                                         o->chan->cid.cid_ani = ast_strdup(in->cid.cid_ani);
2068                                                 }
2069                                                 if (o->chan->cid.cid_rdnis)
2070                                                         ast_free(o->chan->cid.cid_rdnis);
2071                                                 o->chan->cid.cid_rdnis = ast_strdup(S_OR(in->macroexten, in->exten));
2072                                                 if (ast_call(o->chan, tmpchan, 0)) {
2073                                                         ast_log(LOG_NOTICE, "Failed to dial on local channel for call forward to '%s'\n", tmpchan);
2074                                                         do_hang(o);
2075                                                         numnochan++;
2076                                                 }
2077                                         }
2078                                         /* Hangup the original channel now, in case we needed it */
2079                                         ast_hangup(winner);
2080                                         continue;
2081                                 }
2082                                 f = ast_read(winner);
2083                                 if (f) {
2084                                         if (f->frametype == AST_FRAME_CONTROL) {
2085                                                 switch (f->subclass) {
2086                                                 case AST_CONTROL_ANSWER:
2087                                                         /* This is our guy if someone answered. */
2088                                                         if (!peer) {
2089                                                                 if (option_verbose > 2)
2090                                                                         ast_verbose( VERBOSE_PREFIX_3 "%s answered %s\n", o->chan->name, in->name);
2091                                                                 peer = o;
2092                                                         }
2093                                                         break;
2094                                                 case AST_CONTROL_BUSY:
2095                                                         if (option_verbose > 2)
2096                                                                 ast_verbose( VERBOSE_PREFIX_3 "%s is busy\n", o->chan->name);
2097                                                         if (in->cdr)
2098                                                                 ast_cdr_busy(in->cdr);
2099                                                         do_hang(o);
2100                                                         endtime = (long) time(NULL);
2101                                                         endtime -= starttime;
2102                                                         rna(endtime*1000, qe, on, membername);
2103                                                         if (qe->parent->strategy != QUEUE_STRATEGY_RINGALL) {
2104                                                                 if (qe->parent->timeoutrestart)
2105                                                                         *to = orig;
2106                                                                 ring_one(qe, outgoing, &numbusies);
2107                                                         }
2108                                                         numbusies++;
2109                                                         break;
2110                                                 case AST_CONTROL_CONGESTION:
2111                                                         if (option_verbose > 2)
2112                                                                 ast_verbose( VERBOSE_PREFIX_3 "%s is circuit-busy\n", o->chan->name);
2113                                                         if (in->cdr)
2114                                                                 ast_cdr_busy(in->cdr);
2115                                                         endtime = (long) time(NULL);
2116                                                         endtime -= starttime;
2117                                                         rna(endtime*1000, qe, on, membername);
2118                                                         do_hang(o);
2119                                                         if (qe->parent->strategy != QUEUE_STRATEGY_RINGALL) {
2120                                                                 if (qe->parent->timeoutrestart)
2121                                                                         *to = orig;
2122                                                                 ring_one(qe, outgoing, &numbusies);
2123                                                         }
2124                                                         numbusies++;
2125                                                         break;
2126                                                 case AST_CONTROL_RINGING:
2127                                                         if (option_verbose > 2)
2128                                                                 ast_verbose( VERBOSE_PREFIX_3 "%s is ringing\n", o->chan->name);
2129                                                         if (!sentringing) {
2130 #if 0
2131                                                                 ast_indicate(in, AST_CONTROL_RINGING);
2132 #endif                                                          
2133                                                                 sentringing++;
2134                                                         }
2135                                                         break;
2136                                                 case AST_CONTROL_OFFHOOK:
2137                                                         /* Ignore going off hook */
2138                                                         break;
2139                                                 default:
2140                                                         ast_debug(1, "Dunno what to do with control type %d\n", f->subclass);
2141                                                 }
2142                                         }
2143                                         ast_frfree(f);
2144                                 } else {
2145                                         endtime = (long) time(NULL) - starttime;
2146                                         rna(endtime * 1000, qe, on, membername);
2147                                         do_hang(o);
2148                                         if (qe->parent->strategy != QUEUE_STRATEGY_RINGALL) {
2149                                                 if (qe->parent->timeoutrestart)
2150                                                         *to = orig;
2151                                                 ring_one(qe, outgoing, &numbusies);
2152                                         }
2153                                 }
2154                         }
2155                 }
2156                 if (winner == in) {
2157                         f = ast_read(in);
2158                         if (!f || ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_HANGUP))) {
2159                                 /* Got hung up */
2160                                 *to = -1;
2161                                 if (f)
2162                                         ast_frfree(f);
2163                                 return NULL;
2164                         }
2165                         if ((f->frametype == AST_FRAME_DTMF) && caller_disconnect && (f->subclass == '*')) {
2166                                 if (option_verbose > 3)
2167                                         ast_verbose(VERBOSE_PREFIX_3 "User hit %c to disconnect call.\n", f->subclass);
2168                                 *to = 0;
2169                                 ast_frfree(f);
2170                                 return NULL;
2171                         }
2172                         if ((f->frametype == AST_FRAME_DTMF) && valid_exit(qe, f->subclass)) {
2173                                 if (option_verbose > 3)
2174                                         ast_verbose(VERBOSE_PREFIX_3 "User pressed digit: %c\n", f->subclass);
2175                                 *to = 0;
2176                                 *digit = f->subclass;
2177                                 ast_frfree(f);
2178                                 return NULL;
2179                         }
2180                         ast_frfree(f);
2181                 }
2182                 if (!*to)
2183                         rna(orig, qe, on, membername);
2184         }
2185
2186         return peer;
2187 }
2188
2189 static int is_our_turn(struct queue_ent *qe)
2190 {
2191         struct queue_ent *ch;
2192         struct member *cur;
2193         int avl = 0;
2194         int idx = 0;
2195         int res;
2196
2197         if (!qe->parent->autofill) {
2198                 /* Atomically read the parent head -- does not need a lock */
2199                 ch = qe->parent->head;
2200                 /* If we are now at the top of the head, break out */
2201                 if (ch == qe) {
2202                         ast_debug(1, "It's our turn (%s).\n", qe->chan->name);
2203                         res = 1;
2204                 } else {
2205                         ast_debug(1, "It's not our turn (%s).\n", qe->chan->name);
2206                         res = 0;
2207                 }       
2208
2209         } else {
2210                 /* This needs a lock. How many members are available to be served? */
2211                 ast_mutex_lock(&qe->parent->lock);
2212                         
2213                 ch = qe->parent->head;
2214         
2215                 if (qe->parent->strategy == QUEUE_STRATEGY_RINGALL) {
2216                         ast_debug(1, "Even though there are %d available members, the strategy is ringall so only the head call is allowed in\n", avl);
2217                         avl = 1;
2218                 } else {
2219                         for (cur = qe->parent->members; cur; cur = cur->next) {
2220                                 switch (cur->status) {
2221                                 case AST_DEVICE_NOT_INUSE:
2222                                 case AST_DEVICE_UNKNOWN:
2223                                         avl++;
2224                                         break;
2225                                 }
2226                         }
2227                 }
2228
2229                 ast_debug(1, "There are %d available members.\n", avl);
2230         
2231                 while ((idx < avl) && (ch) && (ch != qe)) {
2232                         idx++;
2233                         ch = ch->next;                  
2234                 }
2235         
2236                 /* If the queue entry is within avl [the number of available members] calls from the top ... */
2237                 if (ch && idx < avl) {
2238                         ast_debug(1, "It's our turn (%s).\n", qe->chan->name);
2239                         res = 1;
2240                 } else {
2241                         ast_debug(1, "It's not our turn (%s).\n", qe->chan->name);
2242                         res = 0;
2243                 }
2244                 
2245                 ast_mutex_unlock(&qe->parent->lock);
2246         }
2247
2248         return res;
2249 }
2250
2251 static int wait_our_turn(struct queue_ent *qe, int ringing, enum queue_result *reason)
2252 {
2253         int res = 0;
2254
2255         /* This is the holding pen for callers 2 through maxlen */
2256         for (;;) {
2257                 enum queue_member_status stat;
2258
2259                 if (is_our_turn(qe))
2260                         break;
2261
2262                 /* If we have timed out, break out */
2263                 if (qe->expire && (time(NULL) > qe->expire)) {
2264                         *reason = QUEUE_TIMEOUT;
2265                         break;
2266                 }
2267
2268                 stat = get_member_status(qe->parent, qe->max_penalty);
2269
2270                 /* leave the queue if no agents, if enabled */
2271                 if (qe->parent->leavewhenempty && (stat == QUEUE_NO_MEMBERS)) {
2272                         *reason = QUEUE_LEAVEEMPTY;
2273                         ast_queue_log(qe->parent->name, qe->chan->uniqueid, "NONE", "EXITEMPTY", "%d|%d|%ld", qe->pos, qe->opos, (long) time(NULL) - qe->start);
2274                         leave_queue(qe);
2275                         break;
2276                 }
2277
2278                 /* leave the queue if no reachable agents, if enabled */
2279                 if ((qe->parent->leavewhenempty == QUEUE_EMPTY_STRICT) && (stat == QUEUE_NO_REACHABLE_MEMBERS || stat == QUEUE_NO_UNPAUSED_REACHABLE_MEMBERS)) {
2280                         *reason = QUEUE_LEAVEUNAVAIL;
2281                         ast_queue_log(qe->parent->name, qe->chan->uniqueid, "NONE", "EXITEMPTY", "%d|%d|%ld", qe->pos, qe->opos, (long) time(NULL) - qe->start);
2282                         leave_queue(qe);
2283                         break;
2284                 }
2285                 if ((qe->parent->leavewhenempty == QUEUE_EMPTY_LOOSE) && (stat == QUEUE_NO_REACHABLE_MEMBERS)) {
2286                         *reason = QUEUE_LEAVEUNAVAIL;
2287                         ast_queue_log(qe->parent->name, qe->chan->uniqueid, "NONE", "EXITEMPTY", "%d|%d|%ld", qe->pos, qe->opos, (long) time(NULL) - qe->start);
2288                         leave_queue(qe);
2289                         break;
2290                 }
2291
2292                 /* Make a position announcement, if enabled */
2293                 if (qe->parent->announcefrequency && !ringing &&
2294                         (res = say_position(qe)))
2295                         break;
2296
2297                 /* Make a periodic announcement, if enabled */
2298                 if (qe->parent->periodicannouncefrequency && !ringing &&
2299                         (res = say_periodic_announcement(qe)))
2300                         break;
2301
2302                 /* Wait a second before checking again */
2303                 if ((res = ast_waitfordigit(qe->chan, RECHECK * 1000)))
2304                         break;
2305         }
2306
2307         return res;
2308 }
2309
2310 static int update_queue(struct call_queue *q, struct member *member)
2311 {
2312         struct member *cur;
2313
2314         /* Since a reload could have taken place, we have to traverse the list to
2315                 be sure it's still valid */
2316         ast_mutex_lock(&q->lock);
2317         cur = q->members;
2318         while (cur) {
2319                 if (member == cur) {
2320                         time(&cur->lastcall);
2321                         cur->calls++;
2322                         break;
2323                 }
2324                 cur = cur->next;
2325         }
2326         q->callscompleted++;
2327         ast_mutex_unlock(&q->lock);
2328         return 0;
2329 }
2330
2331 static int calc_metric(struct call_queue *q, struct member *mem, int pos, struct queue_ent *qe, struct callattempt *tmp)
2332 {
2333         if (qe->max_penalty && (mem->penalty > qe->max_penalty))
2334                 return -1;
2335
2336         switch (q->strategy) {
2337         case QUEUE_STRATEGY_RINGALL:
2338                 /* Everyone equal, except for penalty */
2339                 tmp->metric = mem->penalty * 1000000;
2340                 break;
2341         case QUEUE_STRATEGY_RRMEMORY:
2342                 if (pos < q->rrpos) {
2343                         tmp->metric = 1000 + pos;
2344                 } else {
2345                         if (pos > q->rrpos)
2346                                 /* Indicate there is another priority */
2347                                 q->wrapped = 1;
2348                         tmp->metric = pos;
2349                 }
2350                 tmp->metric += mem->penalty * 1000000;
2351                 break;
2352         case QUEUE_STRATEGY_RANDOM:
2353                 tmp->metric = ast_random() % 1000;
2354                 tmp->metric += mem->penalty * 1000000;
2355                 break;
2356         case QUEUE_STRATEGY_FEWESTCALLS:
2357                 tmp->metric = mem->calls;
2358                 tmp->metric += mem->penalty * 1000000;
2359                 break;
2360         case QUEUE_STRATEGY_LEASTRECENT:
2361                 if (!mem->lastcall)
2362                         tmp->metric = 0;
2363                 else
2364                         tmp->metric = 1000000 - (time(NULL) - mem->lastcall);
2365                 tmp->metric += mem->penalty * 1000000;
2366                 break;
2367         default:
2368                 ast_log(LOG_WARNING, "Can't calculate metric for unknown strategy %d\n", q->strategy);
2369                 break;
2370         }
2371         return 0;
2372 }
2373
2374 enum agent_complete_reason {
2375         CALLER,
2376         AGENT,
2377         TRANSFER
2378 };
2379
2380 static void send_agent_complete(const struct queue_ent *qe, const char *queuename,
2381         const struct ast_channel *peer, const struct member *member, time_t callstart,
2382         char *vars, size_t vars_len, enum agent_complete_reason rsn)
2383 {
2384         const char *reason;
2385
2386         if (!qe->parent->eventwhencalled)
2387                 return;
2388
2389         switch (rsn) {
2390         case CALLER:
2391                 reason = "caller";
2392                 break;
2393         case AGENT:
2394                 reason = "agent";
2395                 break;
2396         case TRANSFER:
2397                 reason = "transfer";
2398                 break;
2399         }
2400
2401         manager_event(EVENT_FLAG_AGENT, "AgentComplete",
2402                 "Queue: %s\r\n"
2403                 "Uniqueid: %s\r\n"
2404                 "Channel: %s\r\n"
2405                 "Member: %s\r\n"
2406                 "MemberName: %s\r\n"
2407                 "HoldTime: %ld\r\n"
2408                 "TalkTime: %ld\r\n"
2409                 "Reason: %s\r\n"
2410                 "%s",
2411                 queuename, qe->chan->uniqueid, peer->name, member->interface, member->membername,
2412                 (long)(callstart - qe->start), (long)(time(NULL) - callstart), reason,
2413                 qe->parent->eventwhencalled == QUEUE_EVENT_VARIABLES ? vars2manager(qe->chan, vars, vars_len) : "");
2414 }
2415
2416 static int try_calling(struct queue_ent *qe, const char *options, char *announceoverride, const char *url, int *go_on, const char *agi, const char *macro, const char *gosub)
2417 {
2418         struct member *cur;
2419         struct callattempt *outgoing = NULL; /* the list of calls we are building */
2420         int to;
2421         char oldexten[AST_MAX_EXTENSION]="";
2422         char oldcontext[AST_MAX_CONTEXT]="";
2423         char queuename[256]="";
2424         char interfacevar[256]="";
2425         struct ast_channel *peer;
2426         struct ast_channel *which;
2427         struct callattempt *lpeer;
2428         struct member *member;
2429         struct ast_app *app;
2430         int res = 0, bridge = 0;
2431         int numbusies = 0;
2432         int x=0;
2433         char *announce = NULL;
2434         char digit = 0;
2435         time_t callstart;
2436         time_t now = time(NULL);
2437         struct ast_bridge_config bridge_config;
2438         char nondataquality = 1;
2439         char *agiexec = NULL;
2440         char *macroexec = NULL;
2441         char *gosubexec = NULL;
2442         int ret = 0;
2443         const char *monitorfilename;
2444         const char *monitor_exec;
2445         const char *monitor_options;
2446         char tmpid[256], tmpid2[256];
2447         char meid[1024], meid2[1024];
2448         char mixmonargs[1512];
2449         struct ast_app *mixmonapp = NULL;
2450         char *p;
2451         char vars[2048];
2452         int forwardsallowed = 1;
2453         memset(&bridge_config, 0, sizeof(bridge_config));
2454         time(&now);
2455                 
2456         for (; options && *options; options++)
2457                 switch (*options) {
2458                 case 't':
2459                         ast_set_flag(&(bridge_config.features_callee), AST_FEATURE_REDIRECT);
2460                         break;
2461                 case 'T':
2462                         ast_set_flag(&(bridge_config.features_caller), AST_FEATURE_REDIRECT);
2463                         break;
2464                 case 'w':
2465                         ast_set_flag(&(bridge_config.features_callee), AST_FEATURE_AUTOMON);
2466                         break;
2467                 case 'W':
2468                         ast_set_flag(&(bridge_config.features_caller), AST_FEATURE_AUTOMON);
2469                         break;
2470                 case 'd':
2471                         nondataquality = 0;
2472                         break;
2473                 case 'h':
2474                         ast_set_flag(&(bridge_config.features_callee), AST_FEATURE_DISCONNECT);
2475                         break;
2476                 case 'H':
2477                         ast_set_flag(&(bridge_config.features_caller), AST_FEATURE_DISCONNECT);
2478                         break;
2479                 case 'n':
2480                         *go_on = 1;
2481                         break;
2482                 case 'i':
2483                         forwardsallowed = 0;
2484                         break;
2485                 }
2486
2487         /* Hold the lock while we setup the outgoing calls */
2488         if (use_weight)
2489                 AST_LIST_LOCK(&queues);
2490         ast_mutex_lock(&qe->parent->lock);
2491         ast_debug(1, "%s is trying to call a queue member.\n",
2492                                                         qe->chan->name);
2493         ast_copy_string(queuename, qe->parent->name, sizeof(queuename));
2494         cur = qe->parent->members;
2495         if (!ast_strlen_zero(qe->announce))
2496                 announce = qe->announce;
2497         if (!ast_strlen_zero(announceoverride))
2498                 announce = announceoverride;
2499
2500         for (; cur; cur = cur->next) {
2501                 struct callattempt *tmp = ast_calloc(1, sizeof(*tmp));
2502
2503                 if (!tmp) {
2504                         ast_mutex_unlock(&qe->parent->lock);
2505                         if (use_weight)
2506                                 AST_LIST_UNLOCK(&queues);
2507                         goto out;
2508                 }
2509                 tmp->stillgoing = -1;
2510                 tmp->member = cur;              /* Never directly dereference!  Could change on reload */
2511                 tmp->oldstatus = cur->status;
2512                 tmp->lastcall = cur->lastcall;
2513                 ast_copy_string(tmp->interface, cur->interface, sizeof(tmp->interface));
2514                 /* Special case: If we ring everyone, go ahead and ring them, otherwise
2515                    just calculate their metric for the appropriate strategy */
2516                 if (!calc_metric(qe->parent, cur, x++, qe, tmp)) {
2517                         /* Put them in the list of outgoing thingies...  We're ready now.
2518                            XXX If we're forcibly removed, these outgoing calls won't get
2519                            hung up XXX */
2520                         tmp->q_next = outgoing;
2521                         outgoing = tmp;         
2522                         /* If this line is up, don't try anybody else */
2523                         if (outgoing->chan && (outgoing->chan->_state == AST_STATE_UP))
2524                                 break;
2525                 } else {
2526                         ast_free(tmp);
2527                 }
2528         }
2529         if (qe->expire && (!qe->parent->timeout || (qe->expire - now) <= qe->parent->timeout))
2530                 to = (qe->expire - now) * 1000;
2531         else
2532                 to = (qe->parent->timeout) ? qe->parent->timeout * 1000 : -1;
2533         ring_one(qe, outgoing, &numbusies);
2534         ast_mutex_unlock(&qe->parent->lock);
2535         if (use_weight)
2536                 AST_LIST_UNLOCK(&queues);
2537         lpeer = wait_for_answer(qe, outgoing, &to, &digit, numbusies, ast_test_flag(&(bridge_config.features_caller), AST_FEATURE_DISCONNECT), forwardsallowed);
2538         ast_mutex_lock(&qe->parent->lock);
2539         if (qe->parent->strategy == QUEUE_STRATEGY_RRMEMORY) {
2540                 store_next(qe, outgoing);
2541         }
2542         ast_mutex_unlock(&qe->parent->lock);
2543         peer = lpeer ? lpeer->chan : NULL;
2544         if (!peer) {
2545                 if (to) {
2546                         /* Must gotten hung up */
2547                         res = -1;
2548                 } else {
2549                         res = digit;
2550                 }
2551                 ast_debug(1, "%s: Nobody answered.\n", qe->chan->name);
2552         } else { /* peer is valid */
2553                 /* Ah ha!  Someone answered within the desired timeframe.  Of course after this
2554                    we will always return with -1 so that it is hung up properly after the
2555                    conversation.  */
2556                 qe->handled++;
2557                 if (!strcmp(qe->chan->tech->type, "Zap"))
2558                         ast_channel_setoption(qe->chan, AST_OPTION_TONE_VERIFY, &nondataquality, sizeof(nondataquality), 0);
2559                 if (!strcmp(peer->tech->type, "Zap"))
2560                         ast_channel_setoption(peer, AST_OPTION_TONE_VERIFY, &nondataquality, sizeof(nondataquality), 0);
2561                 /* Update parameters for the queue */
2562                 recalc_holdtime(qe);
2563                 member = lpeer->member;
2564                 hangupcalls(outgoing, peer);
2565                 outgoing = NULL;
2566                 if (announce || qe->parent->reportholdtime || qe->parent->memberdelay) {
2567                         int res2;
2568
2569                         res2 = ast_autoservice_start(qe->chan);
2570                         if (!res2) {
2571                                 if (qe->parent->memberdelay) {
2572                                         ast_log(LOG_NOTICE, "Delaying member connect for %d seconds\n", qe->parent->memberdelay);
2573                                         res2 |= ast_safe_sleep(peer, qe->parent->memberdelay * 1000);
2574                                 }
2575                                 if (!res2 && announce) {
2576                                         if (play_file(peer, announce))
2577                                                 ast_log(LOG_WARNING, "Announcement file '%s' is unavailable, continuing anyway...\n", announce);
2578                                 }
2579                                 if (!res2 && qe->parent->reportholdtime) {
2580                                         if (!play_file(peer, qe->parent->sound_reporthold)) {
2581                                                 int holdtime;
2582
2583                                                 time(&now);
2584                                                 holdtime = abs((now - qe->start) / 60);
2585                                                 if (holdtime < 2) {
2586                                                         play_file(peer, qe->parent->sound_lessthan);
2587                                                         ast_say_number(peer, 2, AST_DIGIT_ANY, peer->language, NULL);
2588                                                 } else
2589                                                         ast_say_number(peer, holdtime, AST_DIGIT_ANY, peer->language, NULL);
2590                                                 play_file(peer, qe->parent->sound_minutes);
2591                                         }
2592                                 }
2593                         }
2594                         res2 |= ast_autoservice_stop(qe->chan);
2595                         if (peer->_softhangup) {
2596                                 /* Agent must have hung up */
2597                                 ast_log(LOG_WARNING, "Agent on %s hungup on the customer.  They're going to be pissed.\n", peer->name);
2598                                 ast_queue_log(queuename, qe->chan->uniqueid, member->membername, "AGENTDUMP", "%s", "");
2599                                 record_abandoned(qe);
2600                                 if (qe->parent->eventwhencalled)
2601                                         manager_event(EVENT_FLAG_AGENT, "AgentDump",
2602                                                         "Queue: %s\r\n"
2603                                                         "Uniqueid: %s\r\n"
2604                                                         "Channel: %s\r\n"
2605                                                         "Member: %s\r\n"
2606                                                         "MemberName: %s\r\n"
2607                                                         "%s",
2608                                                         queuename, qe->chan->uniqueid, peer->name, member->interface, member->membername,
2609                                                         qe->parent->eventwhencalled == QUEUE_EVENT_VARIABLES ? vars2manager(qe->chan, vars, sizeof(vars)) : "");
2610                                 ast_hangup(peer);
2611                                 goto out;
2612                         } else if (res2) {
2613                                 /* Caller must have hung up just before being connected*/
2614                                 ast_log(LOG_NOTICE, "Caller was about to talk to agent on %s but the caller hungup.\n", peer->name);
2615                                 ast_queue_log(queuename, qe->chan->uniqueid, member->membername, "ABANDON", "%d|%d|%ld", qe->pos, qe->opos, (long) time(NULL) - qe->start);
2616                                 record_abandoned(qe);
2617                                 ast_hangup(peer);
2618                                 return -1;
2619                         }
2620                 }
2621                 /* Stop music on hold */
2622                 ast_moh_stop(qe->chan);
2623                 /* If appropriate, log that we have a destination channel */
2624                 if (qe->chan->cdr)
2625                         ast_cdr_setdestchan(qe->chan->cdr, peer->name);
2626                 /* Make sure channels are compatible */
2627                 res = ast_channel_make_compatible(qe->chan, peer);
2628                 if (res < 0) {
2629                         ast_queue_log(queuename, qe->chan->uniqueid, member->membername, "SYSCOMPAT", "%s", "");
2630                         ast_log(LOG_WARNING, "Had to drop call because I couldn't make %s compatible with %s\n", qe->chan->name, peer->name);
2631                         record_abandoned(qe);
2632                         ast_hangup(peer);
2633                         return -1;
2634                 }
2635
2636                 /* Play announcement to the caller telling it's his turn if defined */
2637                 if (!ast_strlen_zero(qe->parent->sound_callerannounce)) {
2638                         if (play_file(qe->chan, qe->parent->sound_callerannounce))
2639                                 ast_log(LOG_WARNING, "Announcement file '%s' is unavailable, continuing anyway...\n", qe->parent->sound_callerannounce);
2640                 }
2641
2642                 /* Begin Monitoring */
2643                 if (qe->parent->monfmt && *qe->parent->monfmt) {
2644                         if (!qe->parent->montype) {
2645                                 ast_debug(1, "Starting Monitor as requested.\n");
2646                                 monitorfilename = pbx_builtin_getvar_helper(qe->chan, "MONITOR_FILENAME");
2647                                 if (pbx_builtin_getvar_helper(qe->chan, "MONITOR_EXEC") || pbx_builtin_getvar_helper(qe->chan, "MONITOR_EXEC_ARGS"))
2648                                         which = qe->chan;
2649                                 else
2650                                         which = peer;
2651                                 if (monitorfilename)
2652                                         ast_monitor_start(which, qe->parent->monfmt, monitorfilename, 1, X_REC_IN | X_REC_OUT);
2653                                 else if (qe->chan->cdr)
2654                                         ast_monitor_start(which, qe->parent->monfmt, qe->chan->cdr->uniqueid, 1, X_REC_IN | X_REC_OUT);
2655                                 else {
2656                                         /* Last ditch effort -- no CDR, make up something */
2657                                         snprintf(tmpid, sizeof(tmpid), "chan-%lx", ast_random());
2658                                         ast_monitor_start(which, qe->parent->monfmt, tmpid, 1, X_REC_IN | X_REC_OUT);
2659                                 }
2660                                 if (qe->parent->monjoin)
2661                                         ast_monitor_setjoinfiles(which, 1);
2662                         } else {
2663                                 ast_debug(1, "Starting MixMonitor as requested.\n");
2664                                 monitorfilename = pbx_builtin_getvar_helper(qe->chan, "MONITOR_FILENAME");
2665                                 if (!monitorfilename) {
2666                                         if (qe->chan->cdr)
2667                                                 ast_copy_string(tmpid, qe->chan->cdr->uniqueid, sizeof(tmpid)-1);
2668                                         else
2669                                                 snprintf(tmpid, sizeof(tmpid), "chan-%lx", ast_random());
2670                                 } else {
2671                                         ast_copy_string(tmpid2, monitorfilename, sizeof(tmpid2)-1);
2672                                         for (p = tmpid2; *p ; p++) {
2673                                                 if (*p == '^' && *(p+1) == '{') {
2674                                                         *p = '$';
2675                                                 }
2676                                         }
2677
2678                                         memset(tmpid, 0, sizeof(tmpid));
2679                                         pbx_substitute_variables_helper(qe->chan, tmpid2, tmpid, sizeof(tmpid) - 1);
2680                                 }
2681
2682                                 monitor_exec = pbx_builtin_getvar_helper(qe->chan, "MONITOR_EXEC");
2683                                 monitor_options = pbx_builtin_getvar_helper(qe->chan, "MONITOR_OPTIONS");
2684
2685                                 if (monitor_exec) {
2686                                         ast_copy_string(meid2, monitor_exec, sizeof(meid2)-1);
2687                                         for (p = meid2; *p ; p++) {
2688                                                 if (*p == '^' && *(p+1) == '{') {
2689                                                         *p = '$';
2690                                                 }
2691                                         }
2692
2693                                         memset(meid, 0, sizeof(meid));
2694                                         pbx_substitute_variables_helper(qe->chan, meid2, meid, sizeof(meid) - 1);
2695                                 }
2696         
2697                                 snprintf(tmpid2, sizeof(tmpid2)-1, "%s.%s", tmpid, qe->parent->monfmt);
2698
2699                                 mixmonapp = pbx_findapp("MixMonitor");
2700
2701                                 if (strchr(tmpid2, '|')) {
2702                                         ast_log(LOG_WARNING, "monitor-format (in queues.conf) and MONITOR_FILENAME cannot contain a '|'! Not recording.\n");
2703                                         mixmonapp = NULL;
2704                                 }
2705
2706                                 if (!monitor_options)
2707                                         monitor_options = "";
2708                                 
2709                                 if (strchr(monitor_options, '|')) {
2710                                         ast_log(LOG_WARNING, "MONITOR_OPTIONS cannot contain a '|'! Not recording.\n");
2711                                         mixmonapp = NULL;
2712                                 }
2713
2714                                 if (mixmonapp) {
2715                                         if (!ast_strlen_zero(monitor_exec))
2716                                                 snprintf(mixmonargs, sizeof(mixmonargs)-1, "%s|b%s|%s", tmpid2, monitor_options, monitor_exec);
2717                                         else
2718                                                 snprintf(mixmonargs, sizeof(mixmonargs)-1, "%s|b%s", tmpid2, monitor_options);
2719                                                 
2720                                         ast_debug(1, "Arguments being passed to MixMonitor: %s\n", mixmonargs);
2721
2722                                         ret = pbx_exec(qe->chan, mixmonapp, mixmonargs);
2723
2724                                 } else
2725                                         ast_log(LOG_WARNING, "Asked to run MixMonitor on this call, but cannot find the MixMonitor app!\n");
2726
2727                         }
2728                 }
2729                 /* Drop out of the queue at this point, to prepare for next caller */
2730                 leave_queue(qe);                        
2731                 if (!ast_strlen_zero(url) && ast_channel_supports_html(peer)) {
2732                         ast_debug(1, "app_queue: sendurl=%s.\n", url);
2733                         ast_channel_sendurl(peer, url);
2734                 }
2735                 
2736                 ast_mutex_lock(&qe->parent->lock);
2737                 /* if setinterfacevar is defined, make member variables available to the channel */
2738                 /* use  pbx_builtin_setvar to set a load of variables with one call */
2739                 if (qe->parent->setinterfacevar) {
2740                         snprintf(interfacevar,sizeof(interfacevar), "MEMBERINTERFACE=%s|MEMBERNAME=%s|MEMBERCALLS=%d|MEMBERLASTCALL=%ld|MEMBERPENALTY=%d|MEMBERDYNAMIC=%d",
2741                                 member->interface, member->membername, member->calls, (long)member->lastcall, member->penalty, member->dynamic);
2742                         pbx_builtin_setvar(qe->chan, interfacevar);
2743                 }
2744                 
2745                 /* if setqueueentryvar is defined, make queue entry (i.e. the caller) variables available to the channel */
2746                 /* use  pbx_builtin_setvar to set a load of variables with one call */
2747                 if (qe->parent->setqueueentryvar) {
2748                         snprintf(interfacevar,sizeof(interfacevar), "QEHOLDTIME=%ld|QEORIGINALPOS=%d",
2749                                 (long) time(NULL) - qe->start, qe->opos);
2750                         pbx_builtin_setvar(qe->chan, interfacevar);
2751                 }
2752         
2753                 /* try to set queue variables if configured to do so*/
2754                 set_queue_variables(qe);
2755                 ast_mutex_unlock(&qe->parent->lock);
2756                 
2757                 /* run a macro for this connection if defined. The macro simply returns, no action is taken on the result */
2758                 /* use macro from dialplan if passed as a option, otherwise use the default queue macro */
2759                 if (!ast_strlen_zero(macro)) {
2760                                 macroexec = ast_strdupa(macro);
2761                 } else {
2762                         if (qe->parent->membermacro)
2763                                 macroexec = ast_strdupa(qe->parent->membermacro);
2764                 }
2765
2766                 if (!ast_strlen_zero(macroexec)) {
2767                         ast_debug(1, "app_queue: macro=%s.\n", macroexec);
2768                         
2769                         res = ast_autoservice_start(qe->chan);
2770                         if (res) {
2771                                 ast_log(LOG_ERROR, "Unable to start autoservice on calling channel\n");
2772                                 res = -1;
2773                         }
2774                         
2775                         app = pbx_findapp("Macro");
2776                         
2777                         if (app) {
2778                                 res = pbx_exec(qe->chan, app, macroexec);
2779                                 ast_debug(1, "Macro exited with status %d\n", res);
2780                                 res = 0;
2781                         } else {
2782                                 ast_log(LOG_ERROR, "Could not find application Macro\n");
2783                                 res = -1;
2784                         }
2785                 
2786                         if (ast_autoservice_stop(qe->chan) < 0) {
2787                                 ast_log(LOG_ERROR, "Could not stop autoservice on calling channel\n");
2788                                 res = -1;
2789                         }
2790                 }
2791
2792                 /* run a gosub for this connection if defined. The gosub simply returns, no action is taken on the result */
2793                 /* use gosub from dialplan if passed as a option, otherwise use the default queue gosub */
2794                 if (!ast_strlen_zero(gosub)) {
2795                                 gosubexec = ast_strdupa(gosub);
2796                 } else {
2797                         if (qe->parent->membergosub)
2798                                 gosubexec = ast_strdupa(qe->parent->membergosub);
2799                 }
2800
2801                 if (!ast_strlen_zero(gosubexec)) {
2802                         if (option_debug)
2803                                 ast_log(LOG_DEBUG, "app_queue: gosub=%s.\n", gosubexec);
2804                         
2805                         res = ast_autoservice_start(qe->chan);
2806                         if (res) {
2807                                 ast_log(LOG_ERROR, "Unable to start autoservice on calling channel\n");
2808                                 res = -1;
2809                         }
2810                         
2811                         app = pbx_findapp("Gosub");
2812                         
2813                         if (app) {
2814                                 char *gosub_args, *gosub_argstart;
2815
2816                                 /* Set where we came from */
2817                                 ast_copy_string(qe->chan->context, "app_dial_gosub_virtual_context", sizeof(qe->chan->context));
2818                                 ast_copy_string(qe->chan->exten, "s", sizeof(qe->chan->exten));
2819                                 qe->chan->priority = 0;
2820
2821                                 gosub_argstart = strchr(gosubexec, '|');
2822                                 if (gosub_argstart) {
2823                                         *gosub_argstart = 0;
2824                                         asprintf(&gosub_args, "%s|s|1(%s)", gosubexec, gosub_argstart + 1);
2825                                         *gosub_argstart = '|';
2826                                 } else {
2827                                         asprintf(&gosub_args, "%s|s|1", gosubexec);
2828                                 }
2829                                 if (gosub_args) {
2830                                         res = pbx_exec(qe->chan, app, gosub_args);
2831                                         ast_pbx_run(qe->chan);
2832                                         free(gosub_args);
2833                                         if (option_debug)
2834                                                 ast_log(LOG_DEBUG, "Gosub exited with status %d\n", res);
2835                                 } else
2836                                         ast_log(LOG_ERROR, "Could not Allocate string for Gosub arguments -- Gosub Call Aborted!\n");
2837                                 
2838                                 res = 0;
2839                         } else {
2840                                 ast_log(LOG_ERROR, "Could not find application Gosub\n");
2841                                 res = -1;
2842                         }
2843                 
2844                         if (ast_autoservice_stop(qe->chan) < 0) {
2845                                 ast_log(LOG_ERROR, "Could not stop autoservice on calling channel\n");
2846                                 res = -1;
2847                         }
2848                 }
2849
2850                 if (!ast_strlen_zero(agi)) {
2851                         ast_debug(1, "app_queue: agi=%s.\n", agi);
2852                         app = pbx_findapp("agi");
2853                         if (app) {
2854                                 agiexec = ast_strdupa(agi);
2855                                 ret = pbx_exec(qe->chan, app, agiexec);
2856                         } else
2857                                 ast_log(LOG_WARNING, "Asked to execute an AGI on this channel, but could not find application (agi)!\n");
2858                 }
2859                 ast_queue_log(queuename, qe->chan->uniqueid, member->membername, "CONNECT", "%ld|%s", (long) time(NULL) - qe->start, peer->uniqueid);
2860                 if (qe->parent->eventwhencalled)
2861                         manager_event(EVENT_FLAG_AGENT, "AgentConnect",
2862                                         "Queue: %s\r\n"
2863                                         "Uniqueid: %s\r\n"
2864                                         "Channel: %s\r\n"
2865                                         "Member: %s\r\n"
2866                                         "MemberName: %s\r\n"
2867                                         "Holdtime: %ld\r\n"
2868                                         "BridgedChannel: %s\r\n"
2869                                         "%s",
2870                                         queuename, qe->chan->uniqueid, peer->name, member->interface, member->membername,
2871                                         (long) time(NULL) - qe->start, peer->uniqueid,
2872                                         qe->parent->eventwhencalled == QUEUE_EVENT_VARIABLES ? vars2manager(qe->chan, vars, sizeof(vars)) : "");
2873                 ast_copy_string(oldcontext, qe->chan->context, sizeof(oldcontext));
2874                 ast_copy_string(oldexten, qe->chan->exten, sizeof(oldexten));
2875                 time(&callstart);
2876
2877                 bridge = ast_bridge_call(qe->chan,peer, &bridge_config);
2878
2879                 if (strcasecmp(oldcontext, qe->chan->context) || strcasecmp(oldexten, qe->chan->exten)) {
2880                         ast_queue_log(queuename, qe->chan->uniqueid, member->membername, "TRANSFER", "%s|%s|%ld|%ld",
2881                                 qe->chan->exten, qe->chan->context, (long) (callstart - qe->start),
2882                                 (long) (time(NULL) - callstart));
2883                         send_agent_complete(qe, queuename, peer, member, callstart, vars, sizeof(vars), TRANSFER);
2884                 } else if (qe->chan->_softhangup) {
2885                         ast_queue_log(queuename, qe->chan->uniqueid, member->membername, "COMPLETECALLER", "%ld|%ld|%d",
2886                                 (long) (callstart - qe->start), (long) (time(NULL) - callstart), qe->opos);
2887                         send_agent_complete(qe, queuename, peer, member, callstart, vars, sizeof(vars), CALLER);
2888                 } else {
2889                         ast_queue_log(queuename, qe->chan->uniqueid, member->membername, "COMPLETEAGENT", "%ld|%ld|%d",
2890                                 (long) (callstart - qe->start), (long) (time(NULL) - callstart), qe->opos);
2891                         send_agent_complete(qe, queuename, peer, member, callstart, vars, sizeof(vars), AGENT);
2892                 }
2893
2894                 if (bridge != AST_PBX_NO_HANGUP_PEER)
2895                         ast_hangup(peer);
2896                 update_queue(qe->parent, member);
2897                 res = bridge ? bridge : 1;
2898         }