Applications no longer need to call ast_module_user_add and ast_module_user_remove...
[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, int newholdtime)
1472 {
1473         int oldvalue;
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         ast_mutex_lock(&qe->parent->lock);
1480         oldvalue = qe->parent->holdtime;
1481         qe->parent->holdtime = (((oldvalue << 2) - oldvalue) + newholdtime) >> 2;
1482         ast_mutex_unlock(&qe->parent->lock);
1483 }
1484
1485
1486 static void leave_queue(struct queue_ent *qe)
1487 {
1488         struct call_queue *q;
1489         struct queue_ent *cur, *prev = NULL;
1490         int pos = 0;
1491
1492         if (!(q = qe->parent))
1493                 return;
1494         ast_mutex_lock(&q->lock);
1495
1496         prev = NULL;
1497         for (cur = q->head; cur; cur = cur->next) {
1498                 if (cur == qe) {
1499                         q->count--;
1500
1501                         /* Take us out of the queue */
1502                         manager_event(EVENT_FLAG_CALL, "Leave",
1503                                 "Channel: %s\r\nQueue: %s\r\nCount: %d\r\nUniqueid: %s\r\n",
1504                                 qe->chan->name, q->name,  q->count, qe->chan->uniqueid);
1505                         ast_debug(1, "Queue '%s' Leave, Channel '%s'\n", q->name, qe->chan->name );
1506                         /* Take us out of the queue */
1507                         if (prev)
1508                                 prev->next = cur->next;
1509                         else
1510                                 q->head = cur->next;
1511                 } else {
1512                         /* Renumber the people after us in the queue based on a new count */
1513                         cur->pos = ++pos;
1514                         prev = cur;
1515                 }
1516         }
1517         ast_mutex_unlock(&q->lock);
1518
1519         if (q->dead && !q->count) {     
1520                 /* It's dead and nobody is in it, so kill it */
1521                 AST_LIST_LOCK(&queues);
1522                 AST_LIST_REMOVE(&queues, q, list);
1523                 AST_LIST_UNLOCK(&queues);
1524                 destroy_queue(q);
1525         }
1526 }
1527
1528 /* Hang up a list of outgoing calls */
1529 static void hangupcalls(struct callattempt *outgoing, struct ast_channel *exception)
1530 {
1531         struct callattempt *oo;
1532
1533         while (outgoing) {
1534                 /* Hangup any existing lines we have open */
1535                 if (outgoing->chan && (outgoing->chan != exception))
1536                         ast_hangup(outgoing->chan);
1537                 oo = outgoing;
1538                 outgoing = outgoing->q_next;
1539                 ast_free(oo);
1540         }
1541 }
1542
1543 static int update_status(struct call_queue *q, struct member *member, int status)
1544 {
1545         struct member *cur;
1546
1547         /* Since a reload could have taken place, we have to traverse the list to
1548                 be sure it's still valid */
1549         ast_mutex_lock(&q->lock);
1550         for (cur = q->members; cur; cur = cur->next) {
1551                 if (member != cur)
1552                         continue;
1553
1554                 cur->status = status;
1555                 if (!q->maskmemberstatus) {
1556                         manager_event(EVENT_FLAG_AGENT, "QueueMemberStatus",
1557                                 "Queue: %s\r\n"
1558                                 "Location: %s\r\n"
1559                                 "MemberName: %s\r\n"
1560                                 "Membership: %s\r\n"
1561                                 "Penalty: %d\r\n"
1562                                 "CallsTaken: %d\r\n"
1563                                 "LastCall: %d\r\n"
1564                                 "Status: %d\r\n"
1565                                 "Paused: %d\r\n",
1566                                 q->name, cur->interface, cur->membername, cur->dynamic ? "dynamic" : "static",
1567                                 cur->penalty, cur->calls, (int)cur->lastcall, cur->status, cur->paused);
1568                 }
1569         }
1570         ast_mutex_unlock(&q->lock);
1571         return 0;
1572 }
1573
1574 static int update_dial_status(struct call_queue *q, struct member *member, int status)
1575 {
1576         if (status == AST_CAUSE_BUSY)
1577                 status = AST_DEVICE_BUSY;
1578         else if (status == AST_CAUSE_UNREGISTERED)
1579                 status = AST_DEVICE_UNAVAILABLE;
1580         else if (status == AST_CAUSE_NOSUCHDRIVER)
1581                 status = AST_DEVICE_INVALID;
1582         else
1583                 status = AST_DEVICE_UNKNOWN;
1584         return update_status(q, member, status);
1585 }
1586
1587 /* traverse all defined queues which have calls waiting and contain this member
1588    return 0 if no other queue has precedence (higher weight) or 1 if found  */
1589 static int compare_weight(struct call_queue *rq, struct member *member)
1590 {
1591         struct call_queue *q;
1592         struct member *mem;
1593         int found = 0;
1594         
1595         /* &qlock and &rq->lock already set by try_calling()
1596          * to solve deadlock */
1597         AST_LIST_TRAVERSE(&queues, q, list) {
1598                 if (q == rq) /* don't check myself, could deadlock */
1599                         continue;
1600                 ast_mutex_lock(&q->lock);
1601                 if (q->count && q->members) {
1602                         for (mem = q->members; mem; mem = mem->next) {
1603                                 if (strcmp(mem->interface, member->interface))
1604                                         continue;
1605
1606                                 ast_debug(1, "Found matching member %s in queue '%s'\n", mem->interface, q->name);
1607                                 if (q->weight > rq->weight) {
1608                                         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);
1609                                         found = 1;
1610                                         break;
1611                                 }
1612                         }
1613                 }
1614                 ast_mutex_unlock(&q->lock);
1615                 if (found)
1616                         break;
1617         }
1618         return found;
1619 }
1620
1621 /*! \brief common hangup actions */
1622 static void do_hang(struct callattempt *o)
1623 {
1624         o->stillgoing = 0;
1625         ast_hangup(o->chan);
1626         o->chan = NULL;
1627 }
1628
1629 static char *vars2manager(struct ast_channel *chan, char *vars, size_t len)
1630 {
1631         struct ast_str *buf = ast_str_alloca(len + 1);
1632         char *tmp;
1633
1634         if (pbx_builtin_serialize_variables(chan, &buf)) {
1635                 int i, j;
1636
1637                 /* convert "\n" to "\nVariable: " */
1638                 strcpy(vars, "Variable: ");
1639                 tmp = buf->str;
1640
1641                 for (i = 0, j = 10; (i < len - 1) && (j < len - 1); i++, j++) {
1642                         vars[j] = tmp[i];
1643
1644                         if (tmp[i + 1] == '\0')
1645                                 break;
1646                         if (tmp[i] == '\n') {
1647                                 vars[j] = '\r';
1648                                 vars[++j] = '\n';
1649
1650                                 ast_copy_string(&(vars[j]), "Variable: ", len - j);
1651                                 j += 9;
1652                         }
1653                 }
1654                 if (j > len - 1)
1655                         j = len - 1;
1656                 vars[j - 2] = '\r';
1657                 vars[j - 1] = '\n';
1658                 vars[j] = '\0';
1659         } else {
1660                 /* there are no channel variables; leave it blank */
1661                 *vars = '\0';
1662         }
1663         return vars;
1664 }
1665
1666 static int ring_entry(struct queue_ent *qe, struct callattempt *tmp, int *busies)
1667 {
1668         int res;
1669         int status;
1670         char tech[256];
1671         char *location;
1672
1673         /* on entry here, we know that tmp->chan == NULL */
1674         if (qe->parent->wrapuptime && (time(NULL) - tmp->lastcall < qe->parent->wrapuptime)) {
1675                 ast_debug(1, "Wrapuptime not yet expired for %s\n", tmp->interface);
1676                 if (qe->chan->cdr)
1677                         ast_cdr_busy(qe->chan->cdr);
1678                 tmp->stillgoing = 0;
1679                 (*busies)++;
1680                 return 0;
1681         }
1682
1683         if (!qe->parent->ringinuse && (tmp->member->status != AST_DEVICE_NOT_INUSE) && (tmp->member->status != AST_DEVICE_UNKNOWN)) {
1684                 ast_debug(1, "%s in use, can't receive call\n", tmp->interface);
1685                 if (qe->chan->cdr)
1686                         ast_cdr_busy(qe->chan->cdr);
1687                 tmp->stillgoing = 0;
1688                 return 0;
1689         }
1690
1691         if (tmp->member->paused) {
1692                 ast_debug(1, "%s paused, can't receive call\n", tmp->interface);
1693                 if (qe->chan->cdr)
1694                         ast_cdr_busy(qe->chan->cdr);
1695                 tmp->stillgoing = 0;
1696                 return 0;
1697         }
1698         if (use_weight && compare_weight(qe->parent,tmp->member)) {
1699                 ast_debug(1, "Priority queue delaying call to %s:%s\n", qe->parent->name, tmp->interface);
1700                 if (qe->chan->cdr)
1701                         ast_cdr_busy(qe->chan->cdr);
1702                 tmp->stillgoing = 0;
1703                 (*busies)++;
1704                 return 0;
1705         }
1706
1707         ast_copy_string(tech, tmp->interface, sizeof(tech));
1708         if ((location = strchr(tech, '/')))
1709                 *location++ = '\0';
1710         else
1711                 location = "";
1712
1713         /* Request the peer */
1714         tmp->chan = ast_request(tech, qe->chan->nativeformats, location, &status);
1715         if (!tmp->chan) {                       /* If we can't, just go on to the next call */
1716                 if (qe->chan->cdr)
1717                         ast_cdr_busy(qe->chan->cdr);
1718                 tmp->stillgoing = 0;
1719                 update_dial_status(qe->parent, tmp->member, status);
1720
1721                 ast_mutex_lock(&qe->parent->lock);
1722                 qe->parent->rrpos++;
1723                 ast_mutex_unlock(&qe->parent->lock);
1724
1725                 (*busies)++;
1726                 return 0;
1727         } else if (status != tmp->oldstatus)
1728                 update_dial_status(qe->parent, tmp->member, status);
1729         
1730         tmp->chan->appl = "AppQueue";
1731         tmp->chan->data = "(Outgoing Line)";
1732         tmp->chan->whentohangup = 0;
1733         if (tmp->chan->cid.cid_num)
1734                 ast_free(tmp->chan->cid.cid_num);
1735         tmp->chan->cid.cid_num = ast_strdup(qe->chan->cid.cid_num);
1736         if (tmp->chan->cid.cid_name)
1737                 ast_free(tmp->chan->cid.cid_name);
1738         tmp->chan->cid.cid_name = ast_strdup(qe->chan->cid.cid_name);
1739         if (tmp->chan->cid.cid_ani)
1740                 ast_free(tmp->chan->cid.cid_ani);
1741         tmp->chan->cid.cid_ani = ast_strdup(qe->chan->cid.cid_ani);
1742
1743         /* Inherit specially named variables from parent channel */
1744         ast_channel_inherit_variables(qe->chan, tmp->chan);
1745
1746         /* Presense of ADSI CPE on outgoing channel follows ours */
1747         tmp->chan->adsicpe = qe->chan->adsicpe;
1748
1749         /* Place the call, but don't wait on the answer */
1750         if ((res = ast_call(tmp->chan, location, 0))) {
1751                 /* Again, keep going even if there's an error */
1752                 ast_debug(1, "ast call on peer returned %d\n", res);
1753                 if (option_verbose > 2)
1754                         ast_verbose(VERBOSE_PREFIX_3 "Couldn't call %s\n", tmp->interface);
1755                 do_hang(tmp);
1756                 (*busies)++;
1757                 return 0;
1758         } else if (qe->parent->eventwhencalled) {
1759                 char vars[2048];
1760
1761                 manager_event(EVENT_FLAG_AGENT, "AgentCalled",
1762                                         "Queue: %s\r\n"
1763                                         "AgentCalled: %s\r\n"
1764                                         "ChannelCalling: %s\r\n"
1765                                         "DestinationChannel: %s\r\n"
1766                                         "CallerIDNum: %s\r\n"
1767                                         "CallerIDName: %s\r\n"
1768                                         "Context: %s\r\n"
1769                                         "Extension: %s\r\n"
1770                                         "Priority: %d\r\n"
1771                                         "%s",
1772                                         qe->parent->name, tmp->interface, qe->chan->name, tmp->chan->name,
1773                                         tmp->chan->cid.cid_num ? tmp->chan->cid.cid_num : "unknown",
1774                                         tmp->chan->cid.cid_name ? tmp->chan->cid.cid_name : "unknown",
1775                                         qe->chan->context, qe->chan->exten, qe->chan->priority,
1776                                         qe->parent->eventwhencalled == QUEUE_EVENT_VARIABLES ? vars2manager(qe->chan, vars, sizeof(vars)) : "");
1777                 if (option_verbose > 2)
1778                         ast_verbose(VERBOSE_PREFIX_3 "Called %s\n", tmp->interface);
1779         }
1780
1781         return 1;
1782 }
1783
1784 /*! \brief find the entry with the best metric, or NULL */
1785 static struct callattempt *find_best(struct callattempt *outgoing)
1786 {
1787         struct callattempt *best = NULL, *cur;
1788
1789         for (cur = outgoing; cur; cur = cur->q_next) {
1790                 if (cur->stillgoing &&                                  /* Not already done */
1791                         !cur->chan &&                                   /* Isn't already going */
1792                         (!best || cur->metric < best->metric)) {                /* We haven't found one yet, or it's better */
1793                         best = cur;
1794                 }
1795         }
1796
1797         return best;
1798 }
1799
1800 static int ring_one(struct queue_ent *qe, struct callattempt *outgoing, int *busies)
1801 {
1802         int ret = 0;
1803
1804         while (ret == 0) {
1805                 struct callattempt *best = find_best(outgoing);
1806                 if (!best) {
1807                         ast_debug(1, "Nobody left to try ringing in queue\n");
1808                         break;
1809                 }
1810                 if (qe->parent->strategy == QUEUE_STRATEGY_RINGALL) {
1811                         struct callattempt *cur;
1812                         /* Ring everyone who shares this best metric (for ringall) */
1813                         for (cur = outgoing; cur; cur = cur->q_next) {
1814                                 if (cur->stillgoing && !cur->chan && cur->metric <= best->metric) {
1815                                         ast_debug(1, "(Parallel) Trying '%s' with metric %d\n", cur->interface, cur->metric);
1816                                         ring_entry(qe, cur, busies);
1817                                 }
1818                         }
1819                 } else {
1820                         /* Ring just the best channel */
1821                         ast_debug(1, "Trying '%s' with metric %d\n", best->interface, best->metric);
1822                         ring_entry(qe, best, busies);
1823                 }
1824                 if (best->chan) /* break out with result = 1 */
1825                         ret = 1;
1826         }
1827
1828         return ret;
1829 }
1830
1831 static int store_next(struct queue_ent *qe, struct callattempt *outgoing)
1832 {
1833         struct callattempt *best = find_best(outgoing);
1834
1835         if (best) {
1836                 /* Ring just the best channel */
1837                 ast_debug(1, "Next is '%s' with metric %d\n", best->interface, best->metric);
1838                 qe->parent->rrpos = best->metric % 1000;
1839         } else {
1840                 /* Just increment rrpos */
1841                 if (qe->parent->wrapped) {
1842                         /* No more channels, start over */
1843                         qe->parent->rrpos = 0;
1844                 } else {
1845                         /* Prioritize next entry */
1846                         qe->parent->rrpos++;
1847                 }
1848         }
1849         qe->parent->wrapped = 0;
1850
1851         return 0;
1852 }
1853
1854 static int background_file(struct queue_ent *qe, struct ast_channel *chan, char *filename)
1855 {
1856         int res;
1857
1858         ast_stopstream(chan);
1859         res = ast_streamfile(chan, filename, chan->language);
1860
1861         if (!res) {
1862                 /* Wait for a keypress */
1863                 res = ast_waitstream(chan, AST_DIGIT_ANY);
1864                 if (res < 0 || !valid_exit(qe, res))
1865                         res = 0;
1866
1867                 /* Stop playback */
1868                 ast_stopstream(chan);
1869         }
1870         
1871         return res;
1872 }
1873
1874 static int say_periodic_announcement(struct queue_ent *qe)
1875 {
1876         int res = 0;
1877         time_t now;
1878
1879         /* Get the current time */
1880         time(&now);
1881
1882         /* Check to see if it is time to announce */
1883         if ((now - qe->last_periodic_announce_time) < qe->parent->periodicannouncefrequency)
1884                 return 0;
1885
1886         /* Stop the music on hold so we can play our own file */
1887         ast_moh_stop(qe->chan);
1888
1889         if (option_verbose > 2)
1890                 ast_verbose(VERBOSE_PREFIX_3 "Playing periodic announcement\n");
1891
1892         /* Check to make sure we have a sound file. If not, reset to the first sound file */
1893         if (qe->last_periodic_announce_sound >= MAX_PERIODIC_ANNOUNCEMENTS || !strlen(qe->parent->sound_periodicannounce[qe->last_periodic_announce_sound])) {
1894                 qe->last_periodic_announce_sound = 0;
1895         }
1896         
1897         /* play the announcement */
1898         res = background_file(qe, qe->chan, qe->parent->sound_periodicannounce[qe->last_periodic_announce_sound]);
1899
1900         /* Resume Music on Hold if the caller is going to stay in the queue */
1901         if (!res)
1902                 ast_moh_start(qe->chan, qe->moh, NULL);
1903
1904         /* update last_periodic_announce_time */
1905         qe->last_periodic_announce_time = now;
1906
1907         /* Update the current periodic announcement to the next announcement */
1908         qe->last_periodic_announce_sound++;
1909         
1910         return res;
1911 }
1912
1913 static void record_abandoned(struct queue_ent *qe)
1914 {
1915         ast_mutex_lock(&qe->parent->lock);
1916         set_queue_variables(qe);
1917         manager_event(EVENT_FLAG_AGENT, "QueueCallerAbandon",
1918                 "Queue: %s\r\n"
1919                 "Uniqueid: %s\r\n"
1920                 "Position: %d\r\n"
1921                 "OriginalPosition: %d\r\n"
1922                 "HoldTime: %d\r\n",
1923                 qe->parent->name, qe->chan->uniqueid, qe->pos, qe->opos, (int)(time(NULL) - qe->start));
1924
1925         qe->parent->callsabandoned++;
1926         ast_mutex_unlock(&qe->parent->lock);
1927 }
1928
1929 /*! \brief RNA == Ring No Answer. Common code that is executed when we try a queue member and they don't answer. */
1930 static void rna(int rnatime, struct queue_ent *qe, char *interface, char *membername)
1931 {
1932         if (option_verbose > 2)
1933                 ast_verbose( VERBOSE_PREFIX_3 "Nobody picked up in %d ms\n", rnatime);
1934         ast_queue_log(qe->parent->name, qe->chan->uniqueid, membername, "RINGNOANSWER", "%d", rnatime);
1935         if (qe->parent->autopause) {
1936                 if (!set_member_paused(qe->parent->name, interface, 1)) {
1937                         if (option_verbose > 2)
1938                                 ast_verbose( VERBOSE_PREFIX_3 "Auto-Pausing Queue Member %s in queue %s since they failed to answer.\n", interface, qe->parent->name);
1939                 } else {
1940                         if (option_verbose > 2)
1941                                 ast_verbose( VERBOSE_PREFIX_3 "Failed to pause Queue Member %s in queue %s!\n", interface, qe->parent->name);
1942                 }
1943         }
1944         return;
1945 }
1946
1947 #define AST_MAX_WATCHERS 256
1948
1949 static struct callattempt *wait_for_answer(struct queue_ent *qe, struct callattempt *outgoing, int *to, char *digit, int prebusies, int caller_disconnect, int forwardsallowed)
1950 {
1951         char *queue = qe->parent->name;
1952         struct callattempt *o;
1953         int status;
1954         int sentringing = 0;
1955         int numbusies = prebusies;
1956         int numnochan = 0;
1957         int stillgoing = 0;
1958         int orig = *to;
1959         struct ast_frame *f;
1960         struct callattempt *peer = NULL;
1961         struct ast_channel *winner;
1962         struct ast_channel *in = qe->chan;
1963         char on[80] = "";
1964         char membername[80] = "";
1965         long starttime = 0;
1966         long endtime = 0;       
1967
1968         starttime = (long) time(NULL);
1969         
1970         while (*to && !peer) {
1971                 int numlines, retry, pos = 1;
1972                 struct ast_channel *watchers[AST_MAX_WATCHERS];
1973                 watchers[0] = in;
1974
1975                 for (retry = 0; retry < 2; retry++) {
1976                         numlines = 0;
1977                         for (o = outgoing; o; o = o->q_next) { /* Keep track of important channels */
1978                                 if (o->stillgoing) {    /* Keep track of important channels */
1979                                         stillgoing = 1;
1980                                         if (o->chan)
1981                                                 watchers[pos++] = o->chan;
1982                                 }
1983                                 numlines++;
1984                         }
1985                         if (pos > 1 /* found */ || !stillgoing /* nobody listening */ ||
1986                                 (qe->parent->strategy != QUEUE_STRATEGY_RINGALL) /* ring would not be delivered */)
1987                                 break;
1988                         /* On "ringall" strategy we only move to the next penalty level
1989                            when *all* ringing phones are done in the current penalty level */
1990                         ring_one(qe, outgoing, &numbusies);
1991                         /* and retry... */
1992                 }
1993                 if (pos == 1 /* not found */) {
1994                         if (numlines == (numbusies + numnochan)) {
1995                                 ast_debug(1, "Everyone is busy at this time\n");
1996                         } else {
1997                                 ast_log(LOG_NOTICE, "No one is answering queue '%s' (%d/%d/%d)\n", queue, numlines, numbusies, numnochan);
1998                         }
1999                         *to = 0;
2000                         return NULL;
2001                 }
2002                 winner = ast_waitfor_n(watchers, pos, to);
2003                 for (o = outgoing; o; o = o->q_next) {
2004                         if (o->stillgoing && (o->chan) &&  (o->chan->_state == AST_STATE_UP)) {
2005                                 if (!peer) {
2006                                         if (option_verbose > 2)
2007                                                 ast_verbose( VERBOSE_PREFIX_3 "%s answered %s\n", o->chan->name, in->name);
2008                                         peer = o;
2009                                 }
2010                         } else if (o->chan && (o->chan == winner)) {
2011
2012                                 ast_copy_string(on, o->member->interface, sizeof(on));
2013                                 ast_copy_string(membername, o->member->membername, sizeof(membername));
2014
2015                                 if (!ast_strlen_zero(o->chan->call_forward) && !forwardsallowed) {
2016                                         if (option_verbose > 2)
2017                                                 ast_verbose(VERBOSE_PREFIX_3 "Forwarding %s to '%s' prevented.\n", in->name, o->chan->call_forward);
2018                                         numnochan++;
2019                                         do_hang(o);
2020                                         winner = NULL;
2021                                         continue;
2022                                 } else if (!ast_strlen_zero(o->chan->call_forward)) {
2023                                         char tmpchan[256];
2024                                         char *stuff;
2025                                         char *tech;
2026
2027                                         ast_copy_string(tmpchan, o->chan->call_forward, sizeof(tmpchan));
2028                                         if ((stuff = strchr(tmpchan, '/'))) {
2029                                                 *stuff++ = '\0';
2030                                                 tech = tmpchan;
2031                                         } else {
2032                                                 snprintf(tmpchan, sizeof(tmpchan), "%s@%s", o->chan->call_forward, o->chan->context);
2033                                                 stuff = tmpchan;
2034                                                 tech = "Local";
2035                                         }
2036                                         /* Before processing channel, go ahead and check for forwarding */
2037                                         if (option_verbose > 2)
2038                                                 ast_verbose(VERBOSE_PREFIX_3 "Now forwarding %s to '%s/%s' (thanks to %s)\n", in->name, tech, stuff, o->chan->name);
2039                                         /* Setup parameters */
2040                                         o->chan = ast_request(tech, in->nativeformats, stuff, &status);
2041                                         if (status != o->oldstatus)
2042                                                 update_dial_status(qe->parent, o->member, status);                                              
2043                                         if (!o->chan) {
2044                                                 ast_log(LOG_NOTICE, "Unable to create local channel for call forward to '%s/%s'\n", tech, stuff);
2045                                                 o->stillgoing = 0;
2046                                                 numnochan++;
2047                                         } else {
2048                                                 ast_channel_inherit_variables(in, o->chan);
2049                                                 if (o->chan->cid.cid_num)
2050                                                         ast_free(o->chan->cid.cid_num);
2051                                                 o->chan->cid.cid_num = ast_strdup(in->cid.cid_num);
2052
2053                                                 if (o->chan->cid.cid_name)
2054                                                         ast_free(o->chan->cid.cid_name);
2055                                                 o->chan->cid.cid_name = ast_strdup(in->cid.cid_name);
2056
2057                                                 ast_string_field_set(o->chan, accountcode, in->accountcode);
2058                                                 o->chan->cdrflags = in->cdrflags;
2059
2060                                                 if (in->cid.cid_ani) {
2061                                                         if (o->chan->cid.cid_ani)
2062                                                                 ast_free(o->chan->cid.cid_ani);
2063                                                         o->chan->cid.cid_ani = ast_strdup(in->cid.cid_ani);
2064                                                 }
2065                                                 if (o->chan->cid.cid_rdnis)
2066                                                         ast_free(o->chan->cid.cid_rdnis);
2067                                                 o->chan->cid.cid_rdnis = ast_strdup(S_OR(in->macroexten, in->exten));
2068                                                 if (ast_call(o->chan, tmpchan, 0)) {
2069                                                         ast_log(LOG_NOTICE, "Failed to dial on local channel for call forward to '%s'\n", tmpchan);
2070                                                         do_hang(o);
2071                                                         numnochan++;
2072                                                 }
2073                                         }
2074                                         /* Hangup the original channel now, in case we needed it */
2075                                         ast_hangup(winner);
2076                                         continue;
2077                                 }
2078                                 f = ast_read(winner);
2079                                 if (f) {
2080                                         if (f->frametype == AST_FRAME_CONTROL) {
2081                                                 switch (f->subclass) {
2082                                                 case AST_CONTROL_ANSWER:
2083                                                         /* This is our guy if someone answered. */
2084                                                         if (!peer) {
2085                                                                 if (option_verbose > 2)
2086                                                                         ast_verbose( VERBOSE_PREFIX_3 "%s answered %s\n", o->chan->name, in->name);
2087                                                                 peer = o;
2088                                                         }
2089                                                         break;
2090                                                 case AST_CONTROL_BUSY:
2091                                                         if (option_verbose > 2)
2092                                                                 ast_verbose( VERBOSE_PREFIX_3 "%s is busy\n", o->chan->name);
2093                                                         if (in->cdr)
2094                                                                 ast_cdr_busy(in->cdr);
2095                                                         do_hang(o);
2096                                                         endtime = (long) time(NULL);
2097                                                         endtime -= starttime;
2098                                                         rna(endtime*1000, qe, on, membername);
2099                                                         if (qe->parent->strategy != QUEUE_STRATEGY_RINGALL) {
2100                                                                 if (qe->parent->timeoutrestart)
2101                                                                         *to = orig;
2102                                                                 ring_one(qe, outgoing, &numbusies);
2103                                                         }
2104                                                         numbusies++;
2105                                                         break;
2106                                                 case AST_CONTROL_CONGESTION:
2107                                                         if (option_verbose > 2)
2108                                                                 ast_verbose( VERBOSE_PREFIX_3 "%s is circuit-busy\n", o->chan->name);
2109                                                         if (in->cdr)
2110                                                                 ast_cdr_busy(in->cdr);
2111                                                         endtime = (long) time(NULL);
2112                                                         endtime -= starttime;
2113                                                         rna(endtime*1000, qe, on, membername);
2114                                                         do_hang(o);
2115                                                         if (qe->parent->strategy != QUEUE_STRATEGY_RINGALL) {
2116                                                                 if (qe->parent->timeoutrestart)
2117                                                                         *to = orig;
2118                                                                 ring_one(qe, outgoing, &numbusies);
2119                                                         }
2120                                                         numbusies++;
2121                                                         break;
2122                                                 case AST_CONTROL_RINGING:
2123                                                         if (option_verbose > 2)
2124                                                                 ast_verbose( VERBOSE_PREFIX_3 "%s is ringing\n", o->chan->name);
2125                                                         if (!sentringing) {
2126 #if 0
2127                                                                 ast_indicate(in, AST_CONTROL_RINGING);
2128 #endif                                                          
2129                                                                 sentringing++;
2130                                                         }
2131                                                         break;
2132                                                 case AST_CONTROL_OFFHOOK:
2133                                                         /* Ignore going off hook */
2134                                                         break;
2135                                                 default:
2136                                                         ast_debug(1, "Dunno what to do with control type %d\n", f->subclass);
2137                                                 }
2138                                         }
2139                                         ast_frfree(f);
2140                                 } else {
2141                                         endtime = (long) time(NULL) - starttime;
2142                                         rna(endtime * 1000, qe, on, membername);
2143                                         do_hang(o);
2144                                         if (qe->parent->strategy != QUEUE_STRATEGY_RINGALL) {
2145                                                 if (qe->parent->timeoutrestart)
2146                                                         *to = orig;
2147                                                 ring_one(qe, outgoing, &numbusies);
2148                                         }
2149                                 }
2150                         }
2151                 }
2152                 if (winner == in) {
2153                         f = ast_read(in);
2154                         if (!f || ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_HANGUP))) {
2155                                 /* Got hung up */
2156                                 *to = -1;
2157                                 if (f)
2158                                         ast_frfree(f);
2159                                 return NULL;
2160                         }
2161                         if ((f->frametype == AST_FRAME_DTMF) && caller_disconnect && (f->subclass == '*')) {
2162                                 if (option_verbose > 3)
2163                                         ast_verbose(VERBOSE_PREFIX_3 "User hit %c to disconnect call.\n", f->subclass);
2164                                 *to = 0;
2165                                 ast_frfree(f);
2166                                 return NULL;
2167                         }
2168                         if ((f->frametype == AST_FRAME_DTMF) && valid_exit(qe, f->subclass)) {
2169                                 if (option_verbose > 3)
2170                                         ast_verbose(VERBOSE_PREFIX_3 "User pressed digit: %c\n", f->subclass);
2171                                 *to = 0;
2172                                 *digit = f->subclass;
2173                                 ast_frfree(f);
2174                                 return NULL;
2175                         }
2176                         ast_frfree(f);
2177                 }
2178                 if (!*to)
2179                         rna(orig, qe, on, membername);
2180         }
2181
2182         return peer;
2183 }
2184
2185 static int is_our_turn(struct queue_ent *qe)
2186 {
2187         struct queue_ent *ch;
2188         struct member *cur;
2189         int avl = 0;
2190         int idx = 0;
2191         int res;
2192
2193         if (!qe->parent->autofill) {
2194                 /* Atomically read the parent head -- does not need a lock */
2195                 ch = qe->parent->head;
2196                 /* If we are now at the top of the head, break out */
2197                 if (ch == qe) {
2198                         ast_debug(1, "It's our turn (%s).\n", qe->chan->name);
2199                         res = 1;
2200                 } else {
2201                         ast_debug(1, "It's not our turn (%s).\n", qe->chan->name);
2202                         res = 0;
2203                 }       
2204
2205         } else {
2206                 /* This needs a lock. How many members are available to be served? */
2207                 ast_mutex_lock(&qe->parent->lock);
2208                         
2209                 ch = qe->parent->head;
2210         
2211                 if (qe->parent->strategy == QUEUE_STRATEGY_RINGALL) {
2212                         ast_debug(1, "Even though there are %d available members, the strategy is ringall so only the head call is allowed in\n", avl);
2213                         avl = 1;
2214                 } else {
2215                         for (cur = qe->parent->members; cur; cur = cur->next) {
2216                                 switch (cur->status) {
2217                                 case AST_DEVICE_NOT_INUSE:
2218                                 case AST_DEVICE_UNKNOWN:
2219                                         avl++;
2220                                         break;
2221                                 }
2222                         }
2223                 }
2224
2225                 ast_debug(1, "There are %d available members.\n", avl);
2226         
2227                 while ((idx < avl) && (ch) && (ch != qe)) {
2228                         idx++;
2229                         ch = ch->next;                  
2230                 }
2231         
2232                 /* If the queue entry is within avl [the number of available members] calls from the top ... */
2233                 if (ch && idx < avl) {
2234                         ast_debug(1, "It's our turn (%s).\n", qe->chan->name);
2235                         res = 1;
2236                 } else {
2237                         ast_debug(1, "It's not our turn (%s).\n", qe->chan->name);
2238                         res = 0;
2239                 }
2240                 
2241                 ast_mutex_unlock(&qe->parent->lock);
2242         }
2243
2244         return res;
2245 }
2246
2247 static int wait_our_turn(struct queue_ent *qe, int ringing, enum queue_result *reason)
2248 {
2249         int res = 0;
2250
2251         /* This is the holding pen for callers 2 through maxlen */
2252         for (;;) {
2253                 enum queue_member_status stat;
2254
2255                 if (is_our_turn(qe))
2256                         break;
2257
2258                 /* If we have timed out, break out */
2259                 if (qe->expire && (time(NULL) > qe->expire)) {
2260                         *reason = QUEUE_TIMEOUT;
2261                         break;
2262                 }
2263
2264                 stat = get_member_status(qe->parent, qe->max_penalty);
2265
2266                 /* leave the queue if no agents, if enabled */
2267                 if (qe->parent->leavewhenempty && (stat == QUEUE_NO_MEMBERS)) {
2268                         *reason = QUEUE_LEAVEEMPTY;
2269                         ast_queue_log(qe->parent->name, qe->chan->uniqueid, "NONE", "EXITEMPTY", "%d|%d|%ld", qe->pos, qe->opos, (long) time(NULL) - qe->start);
2270                         leave_queue(qe);
2271                         break;
2272                 }
2273
2274                 /* leave the queue if no reachable agents, if enabled */
2275                 if ((qe->parent->leavewhenempty == QUEUE_EMPTY_STRICT) && (stat == QUEUE_NO_REACHABLE_MEMBERS || stat == QUEUE_NO_UNPAUSED_REACHABLE_MEMBERS)) {
2276                         *reason = QUEUE_LEAVEUNAVAIL;
2277                         ast_queue_log(qe->parent->name, qe->chan->uniqueid, "NONE", "EXITEMPTY", "%d|%d|%ld", qe->pos, qe->opos, (long) time(NULL) - qe->start);
2278                         leave_queue(qe);
2279                         break;
2280                 }
2281                 if ((qe->parent->leavewhenempty == QUEUE_EMPTY_LOOSE) && (stat == QUEUE_NO_REACHABLE_MEMBERS)) {
2282                         *reason = QUEUE_LEAVEUNAVAIL;
2283                         ast_queue_log(qe->parent->name, qe->chan->uniqueid, "NONE", "EXITEMPTY", "%d|%d|%ld", qe->pos, qe->opos, (long) time(NULL) - qe->start);
2284                         leave_queue(qe);
2285                         break;
2286                 }
2287
2288                 /* Make a position announcement, if enabled */
2289                 if (qe->parent->announcefrequency && !ringing &&
2290                         (res = say_position(qe)))
2291                         break;
2292
2293                 /* Make a periodic announcement, if enabled */
2294                 if (qe->parent->periodicannouncefrequency && !ringing &&
2295                         (res = say_periodic_announcement(qe)))
2296                         break;
2297
2298                 /* Wait a second before checking again */
2299                 if ((res = ast_waitfordigit(qe->chan, RECHECK * 1000)))
2300                         break;
2301         }
2302
2303         return res;
2304 }
2305
2306 static int update_queue(struct call_queue *q, struct member *member, int callcompletedinsl)
2307 {
2308         struct member *cur;
2309
2310         /* Since a reload could have taken place, we have to traverse the list to
2311                 be sure it's still valid */
2312         ast_mutex_lock(&q->lock);
2313         cur = q->members;
2314         while (cur) {
2315                 if (member == cur) {
2316                         time(&cur->lastcall);
2317                         cur->calls++;
2318                         break;
2319                 }
2320                 cur = cur->next;
2321         }
2322         q->callscompleted++;
2323         if (callcompletedinsl)
2324                 q->callscompletedinsl++;
2325         ast_mutex_unlock(&q->lock);
2326         return 0;
2327 }
2328
2329 static int calc_metric(struct call_queue *q, struct member *mem, int pos, struct queue_ent *qe, struct callattempt *tmp)
2330 {
2331         if (qe->max_penalty && (mem->penalty > qe->max_penalty))
2332                 return -1;
2333
2334         switch (q->strategy) {
2335         case QUEUE_STRATEGY_RINGALL:
2336                 /* Everyone equal, except for penalty */
2337                 tmp->metric = mem->penalty * 1000000;
2338                 break;
2339         case QUEUE_STRATEGY_RRMEMORY:
2340                 if (pos < q->rrpos) {
2341                         tmp->metric = 1000 + pos;
2342                 } else {
2343                         if (pos > q->rrpos)
2344                                 /* Indicate there is another priority */
2345                                 q->wrapped = 1;
2346                         tmp->metric = pos;
2347                 }
2348                 tmp->metric += mem->penalty * 1000000;
2349                 break;
2350         case QUEUE_STRATEGY_RANDOM:
2351                 tmp->metric = ast_random() % 1000;
2352                 tmp->metric += mem->penalty * 1000000;
2353                 break;
2354         case QUEUE_STRATEGY_FEWESTCALLS:
2355                 tmp->metric = mem->calls;
2356                 tmp->metric += mem->penalty * 1000000;
2357                 break;
2358         case QUEUE_STRATEGY_LEASTRECENT:
2359                 if (!mem->lastcall)
2360                         tmp->metric = 0;
2361                 else
2362                         tmp->metric = 1000000 - (time(NULL) - mem->lastcall);
2363                 tmp->metric += mem->penalty * 1000000;
2364                 break;
2365         default:
2366                 ast_log(LOG_WARNING, "Can't calculate metric for unknown strategy %d\n", q->strategy);
2367                 break;
2368         }
2369         return 0;
2370 }
2371
2372 enum agent_complete_reason {
2373         CALLER,
2374         AGENT,
2375         TRANSFER
2376 };
2377
2378 static void send_agent_complete(const struct queue_ent *qe, const char *queuename,
2379         const struct ast_channel *peer, const struct member *member, time_t callstart,
2380         char *vars, size_t vars_len, enum agent_complete_reason rsn)
2381 {
2382         const char *reason;
2383
2384         if (!qe->parent->eventwhencalled)
2385                 return;
2386
2387         switch (rsn) {
2388         case CALLER:
2389                 reason = "caller";
2390                 break;
2391         case AGENT:
2392                 reason = "agent";
2393                 break;
2394         case TRANSFER:
2395                 reason = "transfer";
2396                 break;
2397         }
2398
2399         manager_event(EVENT_FLAG_AGENT, "AgentComplete",
2400                 "Queue: %s\r\n"
2401                 "Uniqueid: %s\r\n"
2402                 "Channel: %s\r\n"
2403                 "Member: %s\r\n"
2404                 "MemberName: %s\r\n"
2405                 "HoldTime: %ld\r\n"
2406                 "TalkTime: %ld\r\n"
2407                 "Reason: %s\r\n"
2408                 "%s",
2409                 queuename, qe->chan->uniqueid, peer->name, member->interface, member->membername,
2410                 (long)(callstart - qe->start), (long)(time(NULL) - callstart), reason,
2411                 qe->parent->eventwhencalled == QUEUE_EVENT_VARIABLES ? vars2manager(qe->chan, vars, vars_len) : "");
2412 }
2413
2414 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)
2415 {
2416         struct member *cur;
2417         struct callattempt *outgoing = NULL; /* the list of calls we are building */
2418         int to;
2419         char oldexten[AST_MAX_EXTENSION]="";
2420         char oldcontext[AST_MAX_CONTEXT]="";
2421         char queuename[256]="";
2422         char interfacevar[256]="";
2423         struct ast_channel *peer;
2424         struct ast_channel *which;
2425         struct callattempt *lpeer;
2426         struct member *member;
2427         struct ast_app *app;
2428         int res = 0, bridge = 0;
2429         int numbusies = 0;
2430         int x=0;
2431         char *announce = NULL;
2432         char digit = 0;
2433         time_t callstart;
2434         time_t now = time(NULL);
2435         struct ast_bridge_config bridge_config;
2436         char nondataquality = 1;
2437         char *agiexec = NULL;
2438         char *macroexec = NULL;
2439         char *gosubexec = NULL;
2440         int ret = 0;
2441         const char *monitorfilename;
2442         const char *monitor_exec;
2443         const char *monitor_options;
2444         char tmpid[256], tmpid2[256];
2445         char meid[1024], meid2[1024];
2446         char mixmonargs[1512];
2447         struct ast_app *mixmonapp = NULL;
2448         char *p;
2449         char vars[2048];
2450         int forwardsallowed = 1;
2451         int callcompletedinsl;
2452
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                 time(&now);
2563                 recalc_holdtime(qe, (now - qe->start));
2564                 ast_mutex_lock(&qe->parent->lock);
2565                 callcompletedinsl = ((now - qe->start) <= qe->parent->servicelevel);
2566                 ast_mutex_unlock(&qe->parent->lock);
2567                 member = lpeer->member;
2568                 hangupcalls(outgoing, peer);
2569                 outgoing = NULL;
2570                 if (announce || qe->parent->reportholdtime || qe->parent->memberdelay) {
2571                         int res2;
2572
2573                         res2 = ast_autoservice_start(qe->chan);
2574                         if (!res2) {
2575                                 if (qe->parent->memberdelay) {
2576                                         ast_log(LOG_NOTICE, "Delaying member connect for %d seconds\n", qe->parent->memberdelay);
2577                                         res2 |= ast_safe_sleep(peer, qe->parent->memberdelay * 1000);
2578                                 }
2579                                 if (!res2 && announce) {
2580                                         if (play_file(peer, announce))
2581                                                 ast_log(LOG_WARNING, "Announcement file '%s' is unavailable, continuing anyway...\n", announce);
2582                                 }
2583                                 if (!res2 && qe->parent->reportholdtime) {
2584                                         if (!play_file(peer, qe->parent->sound_reporthold)) {
2585                                                 int holdtime;
2586
2587                                                 time(&now);
2588                                                 holdtime = abs((now - qe->start) / 60);
2589                                                 if (holdtime < 2) {
2590                                                         play_file(peer, qe->parent->sound_lessthan);
2591                                                         ast_say_number(peer, 2, AST_DIGIT_ANY, peer->language, NULL);
2592                                                 } else
2593                                                         ast_say_number(peer, holdtime, AST_DIGIT_ANY, peer->language, NULL);
2594                                                 play_file(peer, qe->parent->sound_minutes);
2595                                         }
2596                                 }
2597                         }
2598                         res2 |= ast_autoservice_stop(qe->chan);
2599                         if (peer->_softhangup) {
2600                                 /* Agent must have hung up */
2601                                 ast_log(LOG_WARNING, "Agent on %s hungup on the customer.  They're going to be pissed.\n", peer->name);
2602                                 ast_queue_log(queuename, qe->chan->uniqueid, member->membername, "AGENTDUMP", "%s", "");
2603                                 record_abandoned(qe);
2604                                 if (qe->parent->eventwhencalled)
2605                                         manager_event(EVENT_FLAG_AGENT, "AgentDump",
2606                                                         "Queue: %s\r\n"
2607                                                         "Uniqueid: %s\r\n"
2608                                                         "Channel: %s\r\n"
2609                                                         "Member: %s\r\n"
2610                                                         "MemberName: %s\r\n"
2611                                                         "%s",
2612                                                         queuename, qe->chan->uniqueid, peer->name, member->interface, member->membername,
2613                                                         qe->parent->eventwhencalled == QUEUE_EVENT_VARIABLES ? vars2manager(qe->chan, vars, sizeof(vars)) : "");
2614                                 ast_hangup(peer);
2615                                 goto out;
2616                         } else if (res2) {
2617                                 /* Caller must have hung up just before being connected*/
2618                                 ast_log(LOG_NOTICE, "Caller was about to talk to agent on %s but the caller hungup.\n", peer->name);
2619                                 ast_queue_log(queuename, qe->chan->uniqueid, member->membername, "ABANDON", "%d|%d|%ld", qe->pos, qe->opos, (long) time(NULL) - qe->start);
2620                                 record_abandoned(qe);
2621                                 ast_hangup(peer);
2622                                 return -1;
2623                         }
2624                 }
2625                 /* Stop music on hold */
2626                 ast_moh_stop(qe->chan);
2627                 /* If appropriate, log that we have a destination channel */
2628                 if (qe->chan->cdr)
2629                         ast_cdr_setdestchan(qe->chan->cdr, peer->name);
2630                 /* Make sure channels are compatible */
2631                 res = ast_channel_make_compatible(qe->chan, peer);
2632                 if (res < 0) {
2633                         ast_queue_log(queuename, qe->chan->uniqueid, member->membername, "SYSCOMPAT", "%s", "");
2634                         ast_log(LOG_WARNING, "Had to drop call because I couldn't make %s compatible with %s\n", qe->chan->name, peer->name);
2635                         record_abandoned(qe);
2636                         ast_hangup(peer);
2637                         return -1;
2638                 }
2639
2640                 /* Play announcement to the caller telling it's his turn if defined */
2641                 if (!ast_strlen_zero(qe->parent->sound_callerannounce)) {
2642                         if (play_file(qe->chan, qe->parent->sound_callerannounce))
2643                                 ast_log(LOG_WARNING, "Announcement file '%s' is unavailable, continuing anyway...\n", qe->parent->sound_callerannounce);
2644                 }
2645
2646                 /* Begin Monitoring */
2647                 if (qe->parent->monfmt && *qe->parent->monfmt) {
2648                         if (!qe->parent->montype) {
2649                                 ast_debug(1, "Starting Monitor as requested.\n");
2650                                 monitorfilename = pbx_builtin_getvar_helper(qe->chan, "MONITOR_FILENAME");
2651                                 if (pbx_builtin_getvar_helper(qe->chan, "MONITOR_EXEC") || pbx_builtin_getvar_helper(qe->chan, "MONITOR_EXEC_ARGS"))
2652                                         which = qe->chan;
2653                                 else
2654                                         which = peer;
2655                                 if (monitorfilename)
2656                                         ast_monitor_start(which, qe->parent->monfmt, monitorfilename, 1, X_REC_IN | X_REC_OUT);
2657                                 else if (qe->chan->cdr)
2658                                         ast_monitor_start(which, qe->parent->monfmt, qe->chan->cdr->uniqueid, 1, X_REC_IN | X_REC_OUT);
2659                                 else {
2660                                         /* Last ditch effort -- no CDR, make up something */
2661                                         snprintf(tmpid, sizeof(tmpid), "chan-%lx", ast_random());
2662                                         ast_monitor_start(which, qe->parent->monfmt, tmpid, 1, X_REC_IN | X_REC_OUT);
2663                                 }
2664                                 if (qe->parent->monjoin)
2665                                         ast_monitor_setjoinfiles(which, 1);
2666                         } else {
2667                                 ast_debug(1, "Starting MixMonitor as requested.\n");
2668                                 monitorfilename = pbx_builtin_getvar_helper(qe->chan, "MONITOR_FILENAME");
2669                                 if (!monitorfilename) {
2670                                         if (qe->chan->cdr)
2671                                                 ast_copy_string(tmpid, qe->chan->cdr->uniqueid, sizeof(tmpid)-1);
2672                                         else
2673                                                 snprintf(tmpid, sizeof(tmpid), "chan-%lx", ast_random());
2674                                 } else {
2675                                         ast_copy_string(tmpid2, monitorfilename, sizeof(tmpid2)-1);
2676                                         for (p = tmpid2; *p ; p++) {
2677                                                 if (*p == '^' && *(p+1) == '{') {
2678                                                         *p = '$';
2679                                                 }
2680                                         }
2681
2682                                         memset(tmpid, 0, sizeof(tmpid));
2683                                         pbx_substitute_variables_helper(qe->chan, tmpid2, tmpid, sizeof(tmpid) - 1);
2684                                 }
2685
2686                                 monitor_exec = pbx_builtin_getvar_helper(qe->chan, "MONITOR_EXEC");
2687                                 monitor_options = pbx_builtin_getvar_helper(qe->chan, "MONITOR_OPTIONS");
2688
2689                                 if (monitor_exec) {
2690                                         ast_copy_string(meid2, monitor_exec, sizeof(meid2)-1);
2691                                         for (p = meid2; *p ; p++) {
2692                                                 if (*p == '^' && *(p+1) == '{') {
2693                                                         *p = '$';
2694                                                 }
2695                                         }
2696
2697                                         memset(meid, 0, sizeof(meid));
2698                                         pbx_substitute_variables_helper(qe->chan, meid2, meid, sizeof(meid) - 1);
2699                                 }
2700         
2701                                 snprintf(tmpid2, sizeof(tmpid2)-1, "%s.%s", tmpid, qe->parent->monfmt);
2702
2703                                 mixmonapp = pbx_findapp("MixMonitor");
2704
2705                                 if (strchr(tmpid2, '|')) {
2706                                         ast_log(LOG_WARNING, "monitor-format (in queues.conf) and MONITOR_FILENAME cannot contain a '|'! Not recording.\n");
2707                                         mixmonapp = NULL;
2708                                 }
2709
2710                                 if (!monitor_options)
2711                                         monitor_options = "";
2712                                 
2713                                 if (strchr(monitor_options, '|')) {
2714                                         ast_log(LOG_WARNING, "MONITOR_OPTIONS cannot contain a '|'! Not recording.\n");
2715                                         mixmonapp = NULL;
2716                                 }
2717
2718                                 if (mixmonapp) {
2719                                         if (!ast_strlen_zero(monitor_exec))
2720                                                 snprintf(mixmonargs, sizeof(mixmonargs)-1, "%s|b%s|%s", tmpid2, monitor_options, monitor_exec);
2721                                         else
2722                                                 snprintf(mixmonargs, sizeof(mixmonargs)-1, "%s|b%s", tmpid2, monitor_options);
2723                                                 
2724                                         ast_debug(1, "Arguments being passed to MixMonitor: %s\n", mixmonargs);
2725
2726                                         ret = pbx_exec(qe->chan, mixmonapp, mixmonargs);
2727
2728                                 } else
2729                                         ast_log(LOG_WARNING, "Asked to run MixMonitor on this call, but cannot find the MixMonitor app!\n");
2730
2731                         }
2732                 }
2733                 /* Drop out of the queue at this point, to prepare for next caller */
2734                 leave_queue(qe);                        
2735                 if (!ast_strlen_zero(url) && ast_channel_supports_html(peer)) {
2736                         ast_debug(1, "app_queue: sendurl=%s.\n", url);
2737                         ast_channel_sendurl(peer, url);
2738                 }
2739                 
2740                 ast_mutex_lock(&qe->parent->lock);
2741                 /* if setinterfacevar is defined, make member variables available to the channel */
2742                 /* use  pbx_builtin_setvar to set a load of variables with one call */
2743                 if (qe->parent->setinterfacevar) {
2744                         snprintf(interfacevar,sizeof(interfacevar), "MEMBERINTERFACE=%s|MEMBERNAME=%s|MEMBERCALLS=%d|MEMBERLASTCALL=%ld|MEMBERPENALTY=%d|MEMBERDYNAMIC=%d",
2745                                 member->interface, member->membername, member->calls, (long)member->lastcall, member->penalty, member->dynamic);
2746                         pbx_builtin_setvar(qe->chan, interfacevar);
2747                 }
2748                 
2749                 /* if setqueueentryvar is defined, make queue entry (i.e. the caller) variables available to the channel */
2750                 /* use  pbx_builtin_setvar to set a load of variables with one call */
2751                 if (qe->parent->setqueueentryvar) {
2752                         snprintf(interfacevar,sizeof(interfacevar), "QEHOLDTIME=%ld|QEORIGINALPOS=%d",
2753                                 (long) time(NULL) - qe->start, qe->opos);
2754                         pbx_builtin_setvar(qe->chan, interfacevar);
2755                 }
2756         
2757                 /* try to set queue variables if configured to do so*/
2758                 set_queue_variables(qe);
2759                 ast_mutex_unlock(&qe->parent->lock);
2760                 
2761                 /* run a macro for this connection if defined. The macro simply returns, no action is taken on the result */
2762                 /* use macro from dialplan if passed as a option, otherwise use the default queue macro */
2763                 if (!ast_strlen_zero(macro)) {
2764                                 macroexec = ast_strdupa(macro);
2765                 } else {
2766                         if (qe->parent->membermacro)
2767                                 macroexec = ast_strdupa(qe->parent->membermacro);
2768                 }
2769
2770                 if (!ast_strlen_zero(macroexec)) {
2771                         ast_debug(1, "app_queue: macro=%s.\n", macroexec);
2772                         
2773                         res = ast_autoservice_start(qe->chan);
2774                         if (res) {
2775                                 ast_log(LOG_ERROR, "Unable to start autoservice on calling channel\n");
2776                                 res = -1;
2777                         }
2778                         
2779                         app = pbx_findapp("Macro");
2780                         
2781                         if (app) {
2782                                 res = pbx_exec(qe->chan, app, macroexec);
2783                                 ast_debug(1, "Macro exited with status %d\n", res);
2784                                 res = 0;
2785                         } else {
2786                                 ast_log(LOG_ERROR, "Could not find application Macro\n");
2787                                 res = -1;
2788                         }
2789                 
2790                         if (ast_autoservice_stop(qe->chan) < 0) {
2791                                 ast_log(LOG_ERROR, "Could not stop autoservice on calling channel\n");
2792                                 res = -1;
2793                         }
2794                 }
2795
2796                 /* run a gosub for this connection if defined. The gosub simply returns, no action is taken on the result */
2797                 /* use gosub from dialplan if passed as a option, otherwise use the default queue gosub */
2798                 if (!ast_strlen_zero(gosub)) {
2799                                 gosubexec = ast_strdupa(gosub);
2800                 } else {
2801                         if (qe->parent->membergosub)
2802                                 gosubexec = ast_strdupa(qe->parent->membergosub);
2803                 }
2804
2805                 if (!ast_strlen_zero(gosubexec)) {
2806                         if (option_debug)
2807                                 ast_log(LOG_DEBUG, "app_queue: gosub=%s.\n", gosubexec);
2808                         
2809                         res = ast_autoservice_start(qe->chan);
2810                         if (res) {
2811                                 ast_log(LOG_ERROR, "Unable to start autoservice on calling channel\n");
2812                                 res = -1;
2813                         }
2814                         
2815                         app = pbx_findapp("Gosub");
2816                         
2817                         if (app) {
2818                                 char *gosub_args, *gosub_argstart;
2819
2820                                 /* Set where we came from */
2821                                 ast_copy_string(qe->chan->context, "app_dial_gosub_virtual_context", sizeof(qe->chan->context));
2822                                 ast_copy_string(qe->chan->exten, "s", sizeof(qe->chan->exten));
2823                                 qe->chan->priority = 0;
2824
2825                                 gosub_argstart = strchr(gosubexec, '|');
2826                                 if (gosub_argstart) {
2827                                         *gosub_argstart = 0;
2828                                         asprintf(&gosub_args, "%s|s|1(%s)", gosubexec, gosub_argstart + 1);
2829                                         *gosub_argstart = '|';
2830                                 } else {
2831                                         asprintf(&gosub_args, "%s|s|1", gosubexec);
2832                                 }
2833                                 if (gosub_args) {
2834                                         res = pbx_exec(qe->chan, app, gosub_args);
2835                                         ast_pbx_run(qe->chan);
2836                                         free(gosub_args);
2837                                         if (option_debug)
2838                                                 ast_log(LOG_DEBUG, "Gosub exited with status %d\n", res);
2839                                 } else
2840                                         ast_log(LOG_ERROR, "Could not Allocate string for Gosub arguments -- Gosub Call Aborted!\n");
2841                                 
2842                                 res = 0;
2843                         } else {
2844                                 ast_log(LOG_ERROR, "Could not find application Gosub\n");
2845                                 res = -1;
2846                         }
2847                 
2848                         if (ast_autoservice_stop(qe->chan) < 0) {
2849                                 ast_log(LOG_ERROR, "Could not stop autoservice on calling channel\n");
2850                                 res = -1;
2851                         }
2852                 }
2853
2854                 if (!ast_strlen_zero(agi)) {
2855                         ast_debug(1, "app_queue: agi=%s.\n", agi);
2856                         app = pbx_findapp("agi");
2857                         if (app) {
2858                                 agiexec = ast_strdupa(agi);
2859                                 ret = pbx_exec(qe->chan, app, agiexec);
2860                         } else
2861                                 ast_log(LOG_WARNING, "Asked to execute an AGI on this channel, but could not find application (agi)!\n");
2862                 }
2863                 ast_queue_log(queuename, qe->chan->uniqueid, member->membername, "CONNECT", "%ld|%s", (long) time(NULL) - qe->start, peer->uniqueid);
2864                 if (qe->parent->eventwhencalled)
2865                         manager_event(EVENT_FLAG_AGENT, "AgentConnect",
2866                                         "Queue: %s\r\n"
2867                                         "Uniqueid: %s\r\n"
2868                                         "Channel: %s\r\n"
2869                                         "Member: %s\r\n"
2870                                         "MemberName: %s\r\n"
2871                                         "Holdtime: %ld\r\n"
2872                                         "BridgedChannel: %s\r\n"
2873                                         "%s",
2874                                         queuename, qe->chan->uniqueid, peer->name, member->interface, member->membername,
2875                                         (long) time(NULL) - qe->start, peer->uniqueid,
2876                                         qe->parent->eventwhencalled == QUEUE_EVENT_VARIABLES ? vars2manager(qe->chan, vars, sizeof(vars)) : "");
2877                 ast_copy_string(oldcontext, qe->chan->context, sizeof(oldcontext));
2878                 ast_copy_string(oldexten, qe->chan->exten, sizeof(oldexten));
2879                 time(&callstart);
2880
2881                 bridge = ast_bridge_call(qe->chan,peer, &bridge_config);
2882
2883                 if (strcasecmp(oldcontext, qe->chan->context) || strcasecmp(oldexten, qe->chan->exten)) {
2884                         ast_queue_log(queuename, qe->chan->uniqueid, member->membername, "TRANSFER", "%s|%s|%ld|%ld",
2885                                 qe->chan->exten, qe->chan->context, (long) (callstart - qe->start),
2886                                 (long) (time(NULL) - callstart));
2887                         send_agent_complete(qe, queuename, peer, member, callstart, vars, sizeof(vars), TRANSFER);
2888                 } else if (qe->chan->_softhangup) {
2889                         ast_queue_log(queuename, qe->chan->uniqueid, member->membername, "COMPLETECALLER", "%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), CALLER);
2892                 } else {
2893                         ast_queue_log(queuename, qe->chan->uniqueid, member->membername, "COMPLETEAGENT", "%ld|%ld|%d",
2894                                 (long) (callstart - qe->start), (long) (time(NULL) - callstart), qe->opos);
2895                         send_agent_complete(qe, queuename, peer, member, callstart, vars, sizeof(vars), AGENT);
2896                 }
2897
2898                 if