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