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