f7c14dec673df608479e5ef3f3c94af7b7546380
[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                 if (option_debug > 2)
563                         ast_log(LOG_DEBUG, "Device '%s/%s' changed to state '%d' (%s) but we don't care because they're not a member of any queue.\n", technology, loc, sc->state, devstate2str(sc->state));
564                 return NULL;
565         }
566
567         if (option_debug)
568                 ast_log(LOG_DEBUG, "Device '%s/%s' changed to state '%d' (%s)\n", technology, loc, sc->state, devstate2str(sc->state));
569         AST_LIST_LOCK(&queues);
570         AST_LIST_TRAVERSE(&queues, q, list) {
571                 ast_mutex_lock(&q->lock);
572                 for (cur = q->members; cur; cur = cur->next) {
573                         char *interface;
574                         char *slash_pos;
575                         interface = ast_strdupa(cur->interface);
576                         if ((slash_pos = strchr(interface, '/')))
577                                 if ((slash_pos = strchr(slash_pos + 1, '/')))
578                                         *slash_pos = '\0';
579
580                         if (strcasecmp(sc->dev, interface))
581                                 continue;
582
583                         if (cur->status != sc->state) {
584                                 cur->status = sc->state;
585                                 if (q->maskmemberstatus)
586                                         continue;
587
588                                 manager_event(EVENT_FLAG_AGENT, "QueueMemberStatus",
589                                         "Queue: %s\r\n"
590                                         "Location: %s\r\n"
591                                         "MemberName: %s\r\n"
592                                         "Membership: %s\r\n"
593                                         "Penalty: %d\r\n"
594                                         "CallsTaken: %d\r\n"
595                                         "LastCall: %d\r\n"
596                                         "Status: %d\r\n"
597                                         "Paused: %d\r\n",
598                                         q->name, cur->interface, cur->membername, cur->dynamic ? "dynamic" : "static",
599                                         cur->penalty, cur->calls, (int)cur->lastcall, cur->status, cur->paused);
600                         }
601                 }
602                 ast_mutex_unlock(&q->lock);
603         }
604         AST_LIST_UNLOCK(&queues);
605
606         return NULL;
607 }
608
609 /*!
610  * \brief Data used by the device state thread
611  */
612 static struct {
613         /*! Set to 1 to stop the thread */
614         unsigned int stop:1;
615         /*! The device state monitoring thread */
616         pthread_t thread;
617         /*! Lock for the state change queue */
618         ast_mutex_t lock;
619         /*! Condition for the state change queue */
620         ast_cond_t cond;
621         /*! Queue of state changes */
622         AST_LIST_HEAD_NOLOCK(, statechange) state_change_q;
623 } device_state = {
624         .thread = AST_PTHREADT_NULL,
625 };
626
627 static void *device_state_thread(void *data)
628 {
629         struct statechange *sc;
630
631         while (!device_state.stop) {
632                 ast_mutex_lock(&device_state.lock);
633                 while (!(sc = AST_LIST_REMOVE_HEAD(&device_state.state_change_q, entry)))
634                         ast_cond_wait(&device_state.cond, &device_state.lock);
635                 ast_mutex_unlock(&device_state.lock);
636
637                 /* Check to see if we were woken up to see the request to stop */
638                 if (device_state.stop)
639                         return NULL;
640
641                 handle_statechange(sc);
642
643                 free(sc);
644         }
645
646         return NULL;
647 }
648
649 static int statechange_queue(const char *dev, enum ast_device_state state)
650 {
651         struct statechange *sc;
652
653         if (!(sc = ast_calloc(1, sizeof(*sc) + strlen(dev) + 1)))
654                 return 0;
655
656         sc->state = state;
657         strcpy(sc->dev, dev);
658
659         ast_mutex_lock(&device_state.lock);
660         AST_LIST_INSERT_TAIL(&device_state.state_change_q, sc, entry);
661         ast_cond_signal(&device_state.cond);
662         ast_mutex_unlock(&device_state.lock);
663
664         return 0;
665 }
666
667 static void device_state_cb(const struct ast_event *event, void *unused)
668 {
669         enum ast_device_state state;
670         const char *device;
671
672         state = ast_event_get_ie_uint(event, AST_EVENT_IE_STATE);
673         device = ast_event_get_ie_str(event, AST_EVENT_IE_DEVICE);
674
675         if (ast_strlen_zero(device)) {
676                 ast_log(LOG_ERROR, "Received invalid event that had no device IE\n");
677                 return;
678         }
679
680         statechange_queue(device, state);
681 }
682
683 static struct member *create_queue_member(const char *interface, const char *membername, int penalty, int paused)
684 {
685         struct member *cur;
686         
687         if ((cur = ast_calloc(1, sizeof(*cur)))) {
688                 cur->penalty = penalty;
689                 cur->paused = paused;
690                 ast_copy_string(cur->interface, interface, sizeof(cur->interface));
691                 ast_copy_string(cur->membername, membername, sizeof(cur->membername));
692                 if (!strchr(cur->interface, '/'))
693                         ast_log(LOG_WARNING, "No location at interface '%s'\n", interface);
694                 cur->status = ast_device_state(interface);
695         }
696
697         return cur;
698 }
699
700 static struct call_queue *alloc_queue(const char *queuename)
701 {
702         struct call_queue *q;
703
704         if ((q = ast_calloc(1, sizeof(*q)))) {
705                 ast_mutex_init(&q->lock);
706                 ast_copy_string(q->name, queuename, sizeof(q->name));
707         }
708         return q;
709 }
710
711 static void init_queue(struct call_queue *q)
712 {
713         int i;
714
715         q->dead = 0;
716         q->retry = DEFAULT_RETRY;
717         q->timeout = -1;
718         q->maxlen = 0;
719         q->announcefrequency = 0;
720         q->minannouncefrequency = DEFAULT_MIN_ANNOUNCE_FREQUENCY;
721         q->announceholdtime = 0;
722         q->roundingseconds = 0; /* Default - don't announce seconds */
723         q->servicelevel = 0;
724         q->ringinuse = 1;
725         q->setinterfacevar = 0;
726         q->setqueuevar = 0;
727         q->setqueueentryvar = 0;
728         q->autofill = autofill_default;
729         q->montype = montype_default;
730         q->membermacro[0] = '\0';
731         q->moh[0] = '\0';
732         q->announce[0] = '\0';
733         q->context[0] = '\0';
734         q->monfmt[0] = '\0';
735         q->periodicannouncefrequency = 0;
736         ast_copy_string(q->sound_next, "queue-youarenext", sizeof(q->sound_next));
737         ast_copy_string(q->sound_thereare, "queue-thereare", sizeof(q->sound_thereare));
738         ast_copy_string(q->sound_calls, "queue-callswaiting", sizeof(q->sound_calls));
739         ast_copy_string(q->sound_holdtime, "queue-holdtime", sizeof(q->sound_holdtime));
740         ast_copy_string(q->sound_minutes, "queue-minutes", sizeof(q->sound_minutes));
741         ast_copy_string(q->sound_seconds, "queue-seconds", sizeof(q->sound_seconds));
742         ast_copy_string(q->sound_thanks, "queue-thankyou", sizeof(q->sound_thanks));
743         ast_copy_string(q->sound_lessthan, "queue-less-than", sizeof(q->sound_lessthan));
744         ast_copy_string(q->sound_reporthold, "queue-reporthold", sizeof(q->sound_reporthold));
745         ast_copy_string(q->sound_periodicannounce[0], "queue-periodic-announce", sizeof(q->sound_periodicannounce[0]));
746         for (i = 1; i < MAX_PERIODIC_ANNOUNCEMENTS; i++) {
747                 q->sound_periodicannounce[i][0]='\0';
748         }
749 }
750
751 static void clear_queue(struct call_queue *q)
752 {
753         q->holdtime = 0;
754         q->callscompleted = 0;
755         q->callsabandoned = 0;
756         q->callscompletedinsl = 0;
757         q->wrapuptime = 0;
758 }
759
760 static int add_to_interfaces(const char *interface)
761 {
762         struct member_interface *curint;
763
764         AST_LIST_LOCK(&interfaces);
765         AST_LIST_TRAVERSE(&interfaces, curint, list) {
766                 if (!strcasecmp(curint->interface, interface))
767                         break;
768         }
769
770         if (curint) {
771                 AST_LIST_UNLOCK(&interfaces);
772                 return 0;
773         }
774
775         if (option_debug)
776                 ast_log(LOG_DEBUG, "Adding %s to the list of interfaces that make up all of our queue members.\n", interface);
777         
778         if ((curint = ast_calloc(1, sizeof(*curint)))) {
779                 ast_copy_string(curint->interface, interface, sizeof(curint->interface));
780                 AST_LIST_INSERT_HEAD(&interfaces, curint, list);
781         }
782         AST_LIST_UNLOCK(&interfaces);
783
784         return 0;
785 }
786
787 static int interface_exists_global(const char *interface)
788 {
789         struct call_queue *q;
790         struct member *mem;
791         int ret = 0;
792
793         AST_LIST_LOCK(&queues);
794         AST_LIST_TRAVERSE(&queues, q, list) {
795                 ast_mutex_lock(&q->lock);
796                 for (mem = q->members; mem && !ret; mem = mem->next) {
797                         if (!strcasecmp(interface, mem->interface))
798                                 ret = 1;
799                 }
800                 ast_mutex_unlock(&q->lock);
801                 if (ret)
802                         break;
803         }
804         AST_LIST_UNLOCK(&queues);
805
806         return ret;
807 }
808
809 static int remove_from_interfaces(const char *interface)
810 {
811         struct member_interface *curint;
812
813         AST_LIST_LOCK(&interfaces);
814         AST_LIST_TRAVERSE_SAFE_BEGIN(&interfaces, curint, list) {
815                 if (!strcasecmp(curint->interface, interface)) {
816                         if (!interface_exists_global(interface)) {
817                                 if (option_debug)
818                                         ast_log(LOG_DEBUG, "Removing %s from the list of interfaces that make up all of our queue members.\n", interface);
819                                 AST_LIST_REMOVE_CURRENT(&interfaces, list);
820                                 ast_free(curint);
821                         }
822                         break;
823                 }
824         }
825         AST_LIST_TRAVERSE_SAFE_END;
826         AST_LIST_UNLOCK(&interfaces);
827
828         return 0;
829 }
830
831 static void clear_and_free_interfaces(void)
832 {
833         struct member_interface *curint;
834
835         AST_LIST_LOCK(&interfaces);
836         while ((curint = AST_LIST_REMOVE_HEAD(&interfaces, list)))
837                 ast_free(curint);
838         AST_LIST_UNLOCK(&interfaces);
839 }
840
841 /*! \brief Configure a queue parameter.
842 \par
843    For error reporting, line number is passed for .conf static configuration.
844    For Realtime queues, linenum is -1.
845    The failunknown flag is set for config files (and static realtime) to show
846    errors for unknown parameters. It is cleared for dynamic realtime to allow
847    extra fields in the tables. */
848 static void queue_set_param(struct call_queue *q, const char *param, const char *val, int linenum, int failunknown)
849 {
850         if (!strcasecmp(param, "musicclass") || 
851                 !strcasecmp(param, "music") || !strcasecmp(param, "musiconhold")) {
852                 ast_copy_string(q->moh, val, sizeof(q->moh));
853         } else if (!strcasecmp(param, "announce")) {
854                 ast_copy_string(q->announce, val, sizeof(q->announce));
855         } else if (!strcasecmp(param, "context")) {
856                 ast_copy_string(q->context, val, sizeof(q->context));
857         } else if (!strcasecmp(param, "timeout")) {
858                 q->timeout = atoi(val);
859                 if (q->timeout < 0)
860                         q->timeout = DEFAULT_TIMEOUT;
861         } else if (!strcasecmp(param, "ringinuse")) {
862                 q->ringinuse = ast_true(val);
863         } else if (!strcasecmp(param, "setinterfacevar")) {
864                 q->setinterfacevar = ast_true(val);
865         } else if (!strcasecmp(param, "setqueuevar")) {
866                 q->setqueuevar = ast_true(val);
867         } else if (!strcasecmp(param, "setqueueentryvar")) {
868                 q->setqueueentryvar = ast_true(val);
869         } else if (!strcasecmp(param, "monitor-join")) {
870                 q->monjoin = ast_true(val);
871         } else if (!strcasecmp(param, "monitor-format")) {
872                 ast_copy_string(q->monfmt, val, sizeof(q->monfmt));
873         } else if (!strcasecmp(param, "membermacro")) {
874                 ast_copy_string(q->membermacro, val, sizeof(q->membermacro));
875         } else if (!strcasecmp(param, "queue-youarenext")) {
876                 ast_copy_string(q->sound_next, val, sizeof(q->sound_next));
877         } else if (!strcasecmp(param, "queue-thereare")) {
878                 ast_copy_string(q->sound_thereare, val, sizeof(q->sound_thereare));
879         } else if (!strcasecmp(param, "queue-callswaiting")) {
880                 ast_copy_string(q->sound_calls, val, sizeof(q->sound_calls));
881         } else if (!strcasecmp(param, "queue-holdtime")) {
882                 ast_copy_string(q->sound_holdtime, val, sizeof(q->sound_holdtime));
883         } else if (!strcasecmp(param, "queue-minutes")) {
884                 ast_copy_string(q->sound_minutes, val, sizeof(q->sound_minutes));
885         } else if (!strcasecmp(param, "queue-seconds")) {
886                 ast_copy_string(q->sound_seconds, val, sizeof(q->sound_seconds));
887         } else if (!strcasecmp(param, "queue-lessthan")) {
888                 ast_copy_string(q->sound_lessthan, val, sizeof(q->sound_lessthan));
889         } else if (!strcasecmp(param, "queue-thankyou")) {
890                 ast_copy_string(q->sound_thanks, val, sizeof(q->sound_thanks));
891         } else if (!strcasecmp(param, "queue-reporthold")) {
892                 ast_copy_string(q->sound_reporthold, val, sizeof(q->sound_reporthold));
893         } else if (!strcasecmp(param, "announce-frequency")) {
894                 q->announcefrequency = atoi(val);
895         } else if (!strcasecmp(param, "min-announce-frequency")) {
896                 q->minannouncefrequency = atoi(val);
897                 ast_log(LOG_DEBUG, "%s=%s for queue '%s'\n", param, val, q->name);
898         } else if (!strcasecmp(param, "announce-round-seconds")) {
899                 q->roundingseconds = atoi(val);
900                 /* Rounding to any other values just doesn't make sense... */
901                 if (!(q->roundingseconds == 0 || q->roundingseconds == 1 || q->roundingseconds == 5 || q->roundingseconds == 10
902                         || q->roundingseconds == 15 || q->roundingseconds == 20 || q->roundingseconds == 30)) {
903                         if (linenum >= 0) {
904                                 ast_log(LOG_WARNING, "'%s' isn't a valid value for %s "
905                                         "using 0 instead for queue '%s' at line %d of queues.conf\n",
906                                         val, param, q->name, linenum);
907                         } else {
908                                 ast_log(LOG_WARNING, "'%s' isn't a valid value for %s "
909                                         "using 0 instead for queue '%s'\n", val, param, q->name);
910                         }
911                         q->roundingseconds=0;
912                 }
913         } else if (!strcasecmp(param, "announce-holdtime")) {
914                 if (!strcasecmp(val, "once"))
915                         q->announceholdtime = ANNOUNCEHOLDTIME_ONCE;
916                 else if (ast_true(val))
917                         q->announceholdtime = ANNOUNCEHOLDTIME_ALWAYS;
918                 else
919                         q->announceholdtime = 0;
920         } else if (!strcasecmp(param, "periodic-announce")) {
921                 if (strchr(val, '|')) {
922                         char *s, *buf = ast_strdupa(val);
923                         unsigned int i = 0;
924
925                         while ((s = strsep(&buf, "|"))) {
926                                 ast_copy_string(q->sound_periodicannounce[i], s, sizeof(q->sound_periodicannounce[i]));
927                                 i++;
928                                 if (i == MAX_PERIODIC_ANNOUNCEMENTS)
929                                         break;
930                         }
931                 } else {
932                         ast_copy_string(q->sound_periodicannounce[0], val, sizeof(q->sound_periodicannounce[0]));
933                 }
934         } else if (!strcasecmp(param, "periodic-announce-frequency")) {
935                 q->periodicannouncefrequency = atoi(val);
936         } else if (!strcasecmp(param, "retry")) {
937                 q->retry = atoi(val);
938                 if (q->retry <= 0)
939                         q->retry = DEFAULT_RETRY;
940         } else if (!strcasecmp(param, "wrapuptime")) {
941                 q->wrapuptime = atoi(val);
942         } else if (!strcasecmp(param, "autofill")) {
943                 q->autofill = ast_true(val);
944         } else if (!strcasecmp(param, "monitor-type")) {
945                 if (!strcasecmp(val, "mixmonitor"))
946                         q->montype = 1;
947         } else if (!strcasecmp(param, "autopause")) {
948                 q->autopause = ast_true(val);
949         } else if (!strcasecmp(param, "maxlen")) {
950                 q->maxlen = atoi(val);
951                 if (q->maxlen < 0)
952                         q->maxlen = 0;
953         } else if (!strcasecmp(param, "servicelevel")) {
954                 q->servicelevel= atoi(val);
955         } else if (!strcasecmp(param, "strategy")) {
956                 q->strategy = strat2int(val);
957                 if (q->strategy < 0) {
958                         ast_log(LOG_WARNING, "'%s' isn't a valid strategy for queue '%s', using ringall instead\n",
959                                 val, q->name);
960                         q->strategy = QUEUE_STRATEGY_RINGALL;
961                 }
962         } else if (!strcasecmp(param, "joinempty")) {
963                 if (!strcasecmp(val, "loose"))
964                         q->joinempty = QUEUE_EMPTY_LOOSE;
965                 else if (!strcasecmp(val, "strict"))
966                         q->joinempty = QUEUE_EMPTY_STRICT;
967                 else if (ast_true(val))
968                         q->joinempty = QUEUE_EMPTY_NORMAL;
969                 else
970                         q->joinempty = 0;
971         } else if (!strcasecmp(param, "leavewhenempty")) {
972                 if (!strcasecmp(val, "loose"))
973                         q->leavewhenempty = QUEUE_EMPTY_LOOSE;
974                 else if (!strcasecmp(val, "strict"))
975                         q->leavewhenempty = QUEUE_EMPTY_STRICT;
976                 else if (ast_true(val))
977                         q->leavewhenempty = QUEUE_EMPTY_NORMAL;
978                 else
979                         q->leavewhenempty = 0;
980         } else if (!strcasecmp(param, "eventmemberstatus")) {
981                 q->maskmemberstatus = !ast_true(val);
982         } else if (!strcasecmp(param, "eventwhencalled")) {
983                 if (!strcasecmp(val, "vars")) {
984                         q->eventwhencalled = QUEUE_EVENT_VARIABLES;
985                 } else {
986                         q->eventwhencalled = ast_true(val);
987                 }
988         } else if (!strcasecmp(param, "reportholdtime")) {
989                 q->reportholdtime = ast_true(val);
990         } else if (!strcasecmp(param, "memberdelay")) {
991                 q->memberdelay = atoi(val);
992         } else if (!strcasecmp(param, "weight")) {
993                 q->weight = atoi(val);
994                 if (q->weight)
995                         use_weight++;
996                 /* With Realtime queues, if the last queue using weights is deleted in realtime,
997                    we will not see any effect on use_weight until next reload. */
998         } else if (!strcasecmp(param, "timeoutrestart")) {
999                 q->timeoutrestart = ast_true(val);
1000         } else if (failunknown) {
1001                 if (linenum >= 0) {
1002                         ast_log(LOG_WARNING, "Unknown keyword in queue '%s': %s at line %d of queues.conf\n",
1003                                 q->name, param, linenum);
1004                 } else {
1005                         ast_log(LOG_WARNING, "Unknown keyword in queue '%s': %s\n", q->name, param);
1006                 }
1007         }
1008 }
1009
1010 static void rt_handle_member_record(struct call_queue *q, char *interface, const char *membername, const char *penalty_str, const char *paused_str)
1011 {
1012         struct member *m, *prev_m;
1013         int penalty = 0;
1014         int paused  = 0;
1015
1016         if (penalty_str) {
1017                 penalty = atoi(penalty_str);
1018                 if (penalty < 0)
1019                         penalty = 0;
1020         }
1021
1022         if (paused_str) {
1023                 paused = atoi(paused_str);
1024                 if (paused < 0)
1025                         paused = 0;
1026         }
1027
1028         /* Find the member, or the place to put a new one. */
1029         for (m = q->members, prev_m = NULL;
1030                 m && strcmp(m->interface, interface);
1031                 prev_m = m, m = m->next);
1032
1033         /* Create a new one if not found, else update penalty */
1034         if (!m) {
1035                 if ((m = create_queue_member(interface, membername, penalty, paused))) {
1036                         m->dead = 0;
1037                         add_to_interfaces(interface);
1038                         if (prev_m) {
1039                                 prev_m->next = m;
1040                         } else {
1041                                 q->members = m;
1042                         }
1043                 }
1044         } else {
1045                 m->dead = 0;    /* Do not delete this one. */
1046                 if (paused_str)
1047                         m->paused = paused;
1048                 m->penalty = penalty;
1049         }
1050 }
1051
1052 static void free_members(struct call_queue *q, int all)
1053 {
1054         /* Free non-dynamic members */
1055         struct member *curm, *next, *prev = NULL;
1056
1057         for (curm = q->members; curm; curm = next) {
1058                 next = curm->next;
1059                 if (all || !curm->dynamic) {
1060                         if (prev)
1061                                 prev->next = next;
1062                         else
1063                                 q->members = next;
1064                         remove_from_interfaces(curm->interface);
1065                         ast_free(curm);
1066                 } else
1067                         prev = curm;
1068         }
1069 }
1070
1071 static void destroy_queue(struct call_queue *q)
1072 {
1073         free_members(q, 1);
1074         ast_mutex_destroy(&q->lock);
1075         ast_free(q);
1076 }
1077
1078 /*!\brief Reload a single queue via realtime.
1079    \return Return the queue, or NULL if it doesn't exist.
1080    \note Should be called with the global qlock locked. */
1081 static struct call_queue *find_queue_by_name_rt(const char *queuename, struct ast_variable *queue_vars, struct ast_config *member_config)
1082 {
1083         struct ast_variable *v;
1084         struct call_queue *q;
1085         struct member *m, *prev_m, *next_m;
1086         char *interface = NULL;
1087         char *tmp, *tmp_name;
1088         char tmpbuf[64];        /* Must be longer than the longest queue param name. */
1089
1090         /* Find the queue in the in-core list (we will create a new one if not found). */
1091         AST_LIST_TRAVERSE(&queues, q, list) {
1092                 if (!strcasecmp(q->name, queuename))
1093                         break;
1094         }
1095
1096         /* Static queues override realtime. */
1097         if (q) {
1098                 ast_mutex_lock(&q->lock);
1099                 if (!q->realtime) {
1100                         if (q->dead) {
1101                                 ast_mutex_unlock(&q->lock);
1102                                 return NULL;
1103                         } else {
1104                                 ast_mutex_unlock(&q->lock);
1105                                 return q;
1106                         }
1107                 }
1108         } else if (!member_config)
1109                 /* Not found in the list, and it's not realtime ... */
1110                 return NULL;
1111
1112         /* Check if queue is defined in realtime. */
1113         if (!queue_vars) {
1114                 /* Delete queue from in-core list if it has been deleted in realtime. */
1115                 if (q) {
1116                         /*! \note Hmm, can't seem to distinguish a DB failure from a not
1117                            found condition... So we might delete an in-core queue
1118                            in case of DB failure. */
1119                         if (option_debug)
1120                                 ast_log(LOG_DEBUG, "Queue %s not found in realtime.\n", queuename);
1121
1122                         q->dead = 1;
1123                         /* Delete if unused (else will be deleted when last caller leaves). */
1124                         if (!q->count) {
1125                                 /* Delete. */
1126                                 AST_LIST_REMOVE(&queues, q, list);
1127                                 ast_mutex_unlock(&q->lock);
1128                                 destroy_queue(q);
1129                         } else
1130                                 ast_mutex_unlock(&q->lock);
1131                 }
1132                 return NULL;
1133         }
1134
1135         /* Create a new queue if an in-core entry does not exist yet. */
1136         if (!q) {
1137                 if (!(q = alloc_queue(queuename)))
1138                         return NULL;
1139                 ast_mutex_lock(&q->lock);
1140                 clear_queue(q);
1141                 q->realtime = 1;
1142                 AST_LIST_INSERT_HEAD(&queues, q, list);
1143         }
1144         init_queue(q);          /* Ensure defaults for all parameters not set explicitly. */
1145
1146         memset(tmpbuf, 0, sizeof(tmpbuf));
1147         for (v = queue_vars; v; v = v->next) {
1148                 /* Convert to dashes `-' from underscores `_' as the latter are more SQL friendly. */
1149                 if ((tmp = strchr(v->name, '_'))) {
1150                         ast_copy_string(tmpbuf, v->name, sizeof(tmpbuf));
1151                         tmp_name = tmpbuf;
1152                         tmp = tmp_name;
1153                         while ((tmp = strchr(tmp, '_')))
1154                                 *tmp++ = '-';
1155                 } else
1156                         tmp_name = v->name;
1157                 queue_set_param(q, tmp_name, v->value, -1, 0);
1158         }
1159
1160         /* Temporarily set non-dynamic members dead so we can detect deleted ones. */
1161         for (m = q->members; m; m = m->next) {
1162                 if (!m->dynamic)
1163                         m->dead = 1;
1164         }
1165
1166         while ((interface = ast_category_browse(member_config, interface))) {
1167                 rt_handle_member_record(q, interface,
1168                         S_OR(ast_variable_retrieve(member_config, interface, "membername"), interface),
1169                         ast_variable_retrieve(member_config, interface, "penalty"),
1170                         ast_variable_retrieve(member_config, interface, "paused"));
1171         }
1172
1173         /* Delete all realtime members that have been deleted in DB. */
1174         m = q->members;
1175         prev_m = NULL;
1176         while (m) {
1177                 next_m = m->next;
1178                 if (m->dead) {
1179                         if (prev_m) {
1180                                 prev_m->next = next_m;
1181                         } else {
1182                                 q->members = next_m;
1183                         }
1184                         remove_from_interfaces(m->interface);
1185                         ast_free(m);
1186                 } else {
1187                         prev_m = m;
1188                 }
1189                 m = next_m;
1190         }
1191
1192         ast_mutex_unlock(&q->lock);
1193
1194         return q;
1195 }
1196
1197 static struct call_queue *load_realtime_queue(const char *queuename)
1198 {
1199         struct ast_variable *queue_vars;
1200         struct ast_config *member_config = NULL;
1201         struct call_queue *q;
1202
1203         /* Find the queue in the in-core list first. */
1204         AST_LIST_LOCK(&queues);
1205         AST_LIST_TRAVERSE(&queues, q, list) {
1206                 if (!strcasecmp(q->name, queuename)) {
1207                         break;
1208                 }
1209         }
1210         AST_LIST_UNLOCK(&queues);
1211
1212         if (!q || q->realtime) {
1213                 /*! \note Load from realtime before taking the global qlock, to avoid blocking all
1214                    queue operations while waiting for the DB.
1215
1216                    This will be two separate database transactions, so we might
1217                    see queue parameters as they were before another process
1218                    changed the queue and member list as it was after the change.
1219                    Thus we might see an empty member list when a queue is
1220                    deleted. In practise, this is unlikely to cause a problem. */
1221
1222                 queue_vars = ast_load_realtime("queues", "name", queuename, NULL);
1223                 if (queue_vars) {
1224                         member_config = ast_load_realtime_multientry("queue_members", "interface LIKE", "%", "queue_name", queuename, NULL);
1225                         if (!member_config) {
1226                                 ast_log(LOG_ERROR, "no queue_members defined in your config (extconfig.conf).\n");
1227                                 return NULL;
1228                         }
1229                 }
1230
1231                 AST_LIST_LOCK(&queues);
1232
1233                 q = find_queue_by_name_rt(queuename, queue_vars, member_config);
1234                 if (member_config)
1235                         ast_config_destroy(member_config);
1236                 if (queue_vars)
1237                         ast_variables_destroy(queue_vars);
1238
1239                 AST_LIST_UNLOCK(&queues);
1240         }
1241         return q;
1242 }
1243
1244 static int join_queue(char *queuename, struct queue_ent *qe, enum queue_result *reason)
1245 {
1246         struct call_queue *q;
1247         struct queue_ent *cur, *prev = NULL;
1248         int res = -1;
1249         int pos = 0;
1250         int inserted = 0;
1251         enum queue_member_status stat;
1252
1253         if (!(q = load_realtime_queue(queuename)))
1254                 return res;
1255
1256         AST_LIST_LOCK(&queues);
1257         ast_mutex_lock(&q->lock);
1258
1259         /* This is our one */
1260         stat = get_member_status(q, qe->max_penalty);
1261         if (!q->joinempty && (stat == QUEUE_NO_MEMBERS))
1262                 *reason = QUEUE_JOINEMPTY;
1263         else if ((q->joinempty == QUEUE_EMPTY_STRICT) && (stat == QUEUE_NO_REACHABLE_MEMBERS || stat == QUEUE_NO_UNPAUSED_REACHABLE_MEMBERS))
1264                 *reason = QUEUE_JOINUNAVAIL;
1265         else if ((q->joinempty == QUEUE_EMPTY_LOOSE) && (stat == QUEUE_NO_REACHABLE_MEMBERS))
1266                 *reason = QUEUE_JOINUNAVAIL;
1267         else if (q->maxlen && (q->count >= q->maxlen))
1268                 *reason = QUEUE_FULL;
1269         else {
1270                 /* There's space for us, put us at the right position inside
1271                  * the queue.
1272                  * Take into account the priority of the calling user */
1273                 inserted = 0;
1274                 prev = NULL;
1275                 cur = q->head;
1276                 while (cur) {
1277                         /* We have higher priority than the current user, enter
1278                          * before him, after all the other users with priority
1279                          * higher or equal to our priority. */
1280                         if ((!inserted) && (qe->prio > cur->prio)) {
1281                                 insert_entry(q, prev, qe, &pos);
1282                                 inserted = 1;
1283                         }
1284                         cur->pos = ++pos;
1285                         prev = cur;
1286                         cur = cur->next;
1287                 }
1288                 /* No luck, join at the end of the queue */
1289                 if (!inserted)
1290                         insert_entry(q, prev, qe, &pos);
1291                 ast_copy_string(qe->moh, q->moh, sizeof(qe->moh));
1292                 ast_copy_string(qe->announce, q->announce, sizeof(qe->announce));
1293                 ast_copy_string(qe->context, q->context, sizeof(qe->context));
1294                 q->count++;
1295                 res = 0;
1296                 manager_event(EVENT_FLAG_CALL, "Join",
1297                         "Channel: %s\r\nCallerID: %s\r\nCallerIDName: %s\r\nQueue: %s\r\nPosition: %d\r\nCount: %d\r\nUniqueid: %s\r\n",
1298                         qe->chan->name,
1299                         S_OR(qe->chan->cid.cid_num, "unknown"), /* XXX somewhere else it is <unknown> */
1300                         S_OR(qe->chan->cid.cid_name, "unknown"),
1301                         q->name, qe->pos, q->count, qe->chan->uniqueid );
1302                 if (option_debug)
1303                         ast_log(LOG_DEBUG, "Queue '%s' Join, Channel '%s', Position '%d'\n", q->name, qe->chan->name, qe->pos );
1304         }
1305         ast_mutex_unlock(&q->lock);
1306         AST_LIST_UNLOCK(&queues);
1307
1308         return res;
1309 }
1310
1311 static int play_file(struct ast_channel *chan, char *filename)
1312 {
1313         int res;
1314
1315         ast_stopstream(chan);
1316         res = ast_streamfile(chan, filename, chan->language);
1317         if (!res)
1318                 res = ast_waitstream(chan, AST_DIGIT_ANY);
1319         ast_stopstream(chan);
1320
1321         return res;
1322 }
1323
1324 static int valid_exit(struct queue_ent *qe, char digit)
1325 {
1326         int digitlen = strlen(qe->digits);
1327
1328         /* Prevent possible buffer overflow */
1329         if (digitlen < sizeof(qe->digits) - 2) {
1330                 qe->digits[digitlen] = digit;
1331                 qe->digits[digitlen + 1] = '\0';
1332         } else {
1333                 qe->digits[0] = '\0';
1334                 return 0;
1335         }
1336
1337         /* If there's no context to goto, short-circuit */
1338         if (ast_strlen_zero(qe->context))
1339                 return 0;
1340
1341         /* If the extension is bad, then reset the digits to blank */
1342         if (!ast_canmatch_extension(qe->chan, qe->context, qe->digits, 1, qe->chan->cid.cid_num)) {
1343                 qe->digits[0] = '\0';
1344                 return 0;
1345         }
1346
1347         /* We have an exact match */
1348         if (!ast_goto_if_exists(qe->chan, qe->context, qe->digits, 1)) {
1349                 /* Return 1 on a successful goto */
1350                 return 1;
1351         }
1352
1353         return 0;
1354 }
1355
1356 static int say_position(struct queue_ent *qe)
1357 {
1358         int res = 0, avgholdmins, avgholdsecs;
1359         time_t now;
1360
1361         /* Let minannouncefrequency seconds pass between the start of each position announcement */
1362         time(&now);
1363         if ((now - qe->last_pos) < qe->parent->minannouncefrequency)
1364                 return 0;
1365
1366         /* If either our position has changed, or we are over the freq timer, say position */
1367         if ((qe->last_pos_said == qe->pos) && ((now - qe->last_pos) < qe->parent->announcefrequency))
1368                 return 0;
1369
1370         ast_moh_stop(qe->chan);
1371         /* Say we're next, if we are */
1372         if (qe->pos == 1) {
1373                 res = play_file(qe->chan, qe->parent->sound_next);
1374                 if (res && valid_exit(qe, res))
1375                         goto playout;
1376                 else
1377                         goto posout;
1378         } else {
1379                 res = play_file(qe->chan, qe->parent->sound_thereare);
1380                 if (res && valid_exit(qe, res))
1381                         goto playout;
1382                 res = ast_say_number(qe->chan, qe->pos, AST_DIGIT_ANY, qe->chan->language, (char *) NULL); /* Needs gender */
1383                 if (res && valid_exit(qe, res))
1384                         goto playout;
1385                 res = play_file(qe->chan, qe->parent->sound_calls);
1386                 if (res && valid_exit(qe, res))
1387                         goto playout;
1388         }
1389         /* Round hold time to nearest minute */
1390         avgholdmins = abs(((qe->parent->holdtime + 30) - (now - qe->start)) / 60);
1391
1392         /* If they have specified a rounding then round the seconds as well */
1393         if (qe->parent->roundingseconds) {
1394                 avgholdsecs = (abs(((qe->parent->holdtime + 30) - (now - qe->start))) - 60 * avgholdmins) / qe->parent->roundingseconds;
1395                 avgholdsecs *= qe->parent->roundingseconds;
1396         } else {
1397                 avgholdsecs = 0;
1398         }
1399
1400         if (option_verbose > 2)
1401                 ast_verbose(VERBOSE_PREFIX_3 "Hold time for %s is %d minutes %d seconds\n", qe->parent->name, avgholdmins, avgholdsecs);
1402
1403         /* If the hold time is >1 min, if it's enabled, and if it's not
1404            supposed to be only once and we have already said it, say it */
1405         if ((avgholdmins+avgholdsecs) > 0 && (qe->parent->announceholdtime) &&
1406                 (!(qe->parent->announceholdtime == ANNOUNCEHOLDTIME_ONCE) && qe->last_pos)) {
1407                 res = play_file(qe->chan, qe->parent->sound_holdtime);
1408                 if (res && valid_exit(qe, res))
1409                         goto playout;
1410
1411                 if (avgholdmins > 0) {
1412                         if (avgholdmins < 2) {
1413                                 res = play_file(qe->chan, qe->parent->sound_lessthan);
1414                                 if (res && valid_exit(qe, res))
1415                                         goto playout;
1416
1417                                 res = ast_say_number(qe->chan, 2, AST_DIGIT_ANY, qe->chan->language, NULL);
1418                                 if (res && valid_exit(qe, res))
1419                                         goto playout;
1420                         } else {
1421                                 res = ast_say_number(qe->chan, avgholdmins, AST_DIGIT_ANY, qe->chan->language, NULL);
1422                                 if (res && valid_exit(qe, res))
1423                                         goto playout;
1424                         }
1425                         
1426                         res = play_file(qe->chan, qe->parent->sound_minutes);
1427                         if (res && valid_exit(qe, res))
1428                                 goto playout;
1429                 }
1430                 if (avgholdsecs>0) {
1431                         res = ast_say_number(qe->chan, avgholdsecs, AST_DIGIT_ANY, qe->chan->language, NULL);
1432                         if (res && valid_exit(qe, res))
1433                                 goto playout;
1434
1435                         res = play_file(qe->chan, qe->parent->sound_seconds);
1436                         if (res && valid_exit(qe, res))
1437                                 goto playout;
1438                 }
1439
1440         }
1441
1442 posout:
1443         if (option_verbose > 2)
1444                 ast_verbose(VERBOSE_PREFIX_3 "Told %s in %s their queue position (which was %d)\n",
1445                         qe->chan->name, qe->parent->name, qe->pos);
1446         res = play_file(qe->chan, qe->parent->sound_thanks);
1447         if (res && !valid_exit(qe, res))
1448                 res = 0;
1449
1450 playout:
1451         /* Set our last_pos indicators */
1452         qe->last_pos = now;
1453         qe->last_pos_said = qe->pos;
1454
1455         /* Don't restart music on hold if we're about to exit the caller from the queue */
1456         if (!res)
1457                 ast_moh_start(qe->chan, qe->moh, NULL);
1458
1459         return res;
1460 }
1461
1462 static void recalc_holdtime(struct queue_ent *qe)
1463 {
1464         int oldvalue, newvalue;
1465
1466         /* Calculate holdtime using a recursive boxcar filter */
1467         /* Thanks to SRT for this contribution */
1468         /* 2^2 (4) is the filter coefficient; a higher exponent would give old entries more weight */
1469
1470         newvalue = time(NULL) - qe->start;
1471
1472         ast_mutex_lock(&qe->parent->lock);
1473         if (newvalue <= qe->parent->servicelevel)
1474                 qe->parent->callscompletedinsl++;
1475         oldvalue = qe->parent->holdtime;
1476         qe->parent->holdtime = (((oldvalue << 2) - oldvalue) + newvalue) >> 2;
1477         ast_mutex_unlock(&qe->parent->lock);
1478 }
1479
1480
1481 static void leave_queue(struct queue_ent *qe)
1482 {
1483         struct call_queue *q;
1484         struct queue_ent *cur, *prev = NULL;
1485         int pos = 0;
1486
1487         if (!(q = qe->parent))
1488                 return;
1489         ast_mutex_lock(&q->lock);
1490
1491         prev = NULL;
1492         for (cur = q->head; cur; cur = cur->next) {
1493                 if (cur == qe) {
1494                         q->count--;
1495
1496                         /* Take us out of the queue */
1497                         manager_event(EVENT_FLAG_CALL, "Leave",
1498                                 "Channel: %s\r\nQueue: %s\r\nCount: %d\r\nUniqueid: %s\r\n",
1499                                 qe->chan->name, q->name,  q->count, qe->chan->uniqueid);
1500                         if (option_debug)
1501                                 ast_log(LOG_DEBUG, "Queue '%s' Leave, Channel '%s'\n", q->name, qe->chan->name );
1502                         /* Take us out of the queue */
1503                         if (prev)
1504                                 prev->next = cur->next;
1505                         else
1506                                 q->head = cur->next;
1507                 } else {
1508                         /* Renumber the people after us in the queue based on a new count */
1509                         cur->pos = ++pos;
1510                         prev = cur;
1511                 }
1512         }
1513         ast_mutex_unlock(&q->lock);
1514
1515         if (q->dead && !q->count) {     
1516                 /* It's dead and nobody is in it, so kill it */
1517                 AST_LIST_LOCK(&queues);
1518                 AST_LIST_REMOVE(&queues, q, list);
1519                 AST_LIST_UNLOCK(&queues);
1520                 destroy_queue(q);
1521         }
1522 }
1523
1524 /* Hang up a list of outgoing calls */
1525 static void hangupcalls(struct callattempt *outgoing, struct ast_channel *exception)
1526 {
1527         struct callattempt *oo;
1528
1529         while (outgoing) {
1530                 /* Hangup any existing lines we have open */
1531                 if (outgoing->chan && (outgoing->chan != exception))
1532                         ast_hangup(outgoing->chan);
1533                 oo = outgoing;
1534                 outgoing = outgoing->q_next;
1535                 ast_free(oo);
1536         }
1537 }
1538
1539 static int update_status(struct call_queue *q, struct member *member, int status)
1540 {
1541         struct member *cur;
1542
1543         /* Since a reload could have taken place, we have to traverse the list to
1544                 be sure it's still valid */
1545         ast_mutex_lock(&q->lock);
1546         for (cur = q->members; cur; cur = cur->next) {
1547                 if (member != cur)
1548                         continue;
1549
1550                 cur->status = status;
1551                 if (!q->maskmemberstatus) {
1552                         manager_event(EVENT_FLAG_AGENT, "QueueMemberStatus",
1553                                 "Queue: %s\r\n"
1554                                 "Location: %s\r\n"
1555                                 "MemberName: %s\r\n"
1556                                 "Membership: %s\r\n"
1557                                 "Penalty: %d\r\n"
1558                                 "CallsTaken: %d\r\n"
1559                                 "LastCall: %d\r\n"
1560                                 "Status: %d\r\n"
1561                                 "Paused: %d\r\n",
1562                                 q->name, cur->interface, cur->membername, cur->dynamic ? "dynamic" : "static",
1563                                 cur->penalty, cur->calls, (int)cur->lastcall, cur->status, cur->paused);
1564                 }
1565         }
1566         ast_mutex_unlock(&q->lock);
1567         return 0;
1568 }
1569
1570 static int update_dial_status(struct call_queue *q, struct member *member, int status)
1571 {
1572         if (status == AST_CAUSE_BUSY)
1573                 status = AST_DEVICE_BUSY;
1574         else if (status == AST_CAUSE_UNREGISTERED)
1575                 status = AST_DEVICE_UNAVAILABLE;
1576         else if (status == AST_CAUSE_NOSUCHDRIVER)
1577                 status = AST_DEVICE_INVALID;
1578         else
1579                 status = AST_DEVICE_UNKNOWN;
1580         return update_status(q, member, status);
1581 }
1582
1583 /* traverse all defined queues which have calls waiting and contain this member
1584    return 0 if no other queue has precedence (higher weight) or 1 if found  */
1585 static int compare_weight(struct call_queue *rq, struct member *member)
1586 {
1587         struct call_queue *q;
1588         struct member *mem;
1589         int found = 0;
1590         
1591         /* &qlock and &rq->lock already set by try_calling()
1592          * to solve deadlock */
1593         AST_LIST_TRAVERSE(&queues, q, list) {
1594                 if (q == rq) /* don't check myself, could deadlock */
1595                         continue;
1596                 ast_mutex_lock(&q->lock);
1597                 if (q->count && q->members) {
1598                         for (mem = q->members; mem; mem = mem->next) {
1599                                 if (strcmp(mem->interface, member->interface))
1600                                         continue;
1601
1602                                 if (option_debug)
1603                                         ast_log(LOG_DEBUG, "Found matching member %s in queue '%s'\n", mem->interface, q->name);
1604                                 if (q->weight > rq->weight) {
1605                                         if (option_debug)
1606                                                 ast_log(LOG_DEBUG, "Queue '%s' (weight %d, calls %d) is preferred over '%s' (weight %d, calls %d)\n", q->name, q->weight, q->count, rq->name, rq->weight, rq->count);
1607                                         found = 1;
1608                                         break;
1609                                 }
1610                         }
1611                 }
1612                 ast_mutex_unlock(&q->lock);
1613                 if (found)
1614                         break;
1615         }
1616         return found;
1617 }
1618
1619 /*! \brief common hangup actions */
1620 static void do_hang(struct callattempt *o)
1621 {
1622         o->stillgoing = 0;
1623         ast_hangup(o->chan);
1624         o->chan = NULL;
1625 }
1626
1627 static char *vars2manager(struct ast_channel *chan, char *vars, size_t len)
1628 {
1629         struct ast_str *buf = ast_str_alloca(len + 1);
1630         char *tmp;
1631
1632         if (pbx_builtin_serialize_variables(chan, &buf)) {
1633                 int i, j;
1634
1635                 /* convert "\n" to "\nVariable: " */
1636                 strcpy(vars, "Variable: ");
1637                 tmp = buf->str;
1638
1639                 for (i = 0, j = 10; (i < len - 1) && (j < len - 1); i++, j++) {
1640                         vars[j] = tmp[i];
1641
1642                         if (tmp[i + 1] == '\0')
1643                                 break;
1644                         if (tmp[i] == '\n') {
1645                                 vars[j] = '\r';
1646                                 vars[++j] = '\n';
1647
1648                                 ast_copy_string(&(vars[j]), "Variable: ", len - j);
1649                                 j += 9;
1650                         }
1651                 }
1652                 if (j > len - 1)
1653                         j = len - 1;
1654                 vars[j - 2] = '\r';
1655                 vars[j - 1] = '\n';
1656                 vars[j] = '\0';
1657         } else {
1658                 /* there are no channel variables; leave it blank */
1659                 *vars = '\0';
1660         }
1661         return vars;
1662 }
1663
1664 static int ring_entry(struct queue_ent *qe, struct callattempt *tmp, int *busies)
1665 {
1666         int res;
1667         int status;
1668         char tech[256];
1669         char *location;
1670
1671         /* on entry here, we know that tmp->chan == NULL */
1672         if (qe->parent->wrapuptime && (time(NULL) - tmp->lastcall < qe->parent->wrapuptime)) {
1673                 if (option_debug)
1674                         ast_log(LOG_DEBUG, "Wrapuptime not yet expired for %s\n", tmp->interface);
1675                 if (qe->chan->cdr)
1676                         ast_cdr_busy(qe->chan->cdr);
1677                 tmp->stillgoing = 0;
1678                 (*busies)++;
1679                 return 0;
1680         }
1681
1682         if (!qe->parent->ringinuse && (tmp->member->status != AST_DEVICE_NOT_INUSE) && (tmp->member->status != AST_DEVICE_UNKNOWN)) {
1683                 if (option_debug)
1684                         ast_log(LOG_DEBUG, "%s in use, can't receive call\n", tmp->interface);
1685                 if (qe->chan->cdr)
1686                         ast_cdr_busy(qe->chan->cdr);
1687                 tmp->stillgoing = 0;
1688                 return 0;
1689         }
1690
1691         if (tmp->member->paused) {
1692                 if (option_debug)
1693                         ast_log(LOG_DEBUG, "%s paused, can't receive call\n", tmp->interface);
1694                 if (qe->chan->cdr)
1695                         ast_cdr_busy(qe->chan->cdr);
1696                 tmp->stillgoing = 0;
1697                 return 0;
1698         }
1699         if (use_weight && compare_weight(qe->parent,tmp->member)) {
1700                 if (option_debug)
1701                         ast_log(LOG_DEBUG, "Priority queue delaying call to %s:%s\n", qe->parent->name, tmp->interface);
1702                 if (qe->chan->cdr)
1703                         ast_cdr_busy(qe->chan->cdr);
1704                 tmp->stillgoing = 0;
1705                 (*busies)++;
1706                 return 0;
1707         }
1708
1709         ast_copy_string(tech, tmp->interface, sizeof(tech));
1710         if ((location = strchr(tech, '/')))
1711                 *location++ = '\0';
1712         else
1713                 location = "";
1714
1715         /* Request the peer */
1716         tmp->chan = ast_request(tech, qe->chan->nativeformats, location, &status);
1717         if (!tmp->chan) {                       /* If we can't, just go on to the next call */
1718                 if (qe->chan->cdr)
1719                         ast_cdr_busy(qe->chan->cdr);
1720                 tmp->stillgoing = 0;
1721                 update_dial_status(qe->parent, tmp->member, status);
1722
1723                 ast_mutex_lock(&qe->parent->lock);
1724                 qe->parent->rrpos++;
1725                 ast_mutex_unlock(&qe->parent->lock);
1726
1727                 (*busies)++;
1728                 return 0;
1729         } else if (status != tmp->oldstatus)
1730                 update_dial_status(qe->parent, tmp->member, status);
1731         
1732         tmp->chan->appl = "AppQueue";
1733         tmp->chan->data = "(Outgoing Line)";
1734         tmp->chan->whentohangup = 0;
1735         if (tmp->chan->cid.cid_num)
1736                 ast_free(tmp->chan->cid.cid_num);
1737         tmp->chan->cid.cid_num = ast_strdup(qe->chan->cid.cid_num);
1738         if (tmp->chan->cid.cid_name)
1739                 ast_free(tmp->chan->cid.cid_name);
1740         tmp->chan->cid.cid_name = ast_strdup(qe->chan->cid.cid_name);
1741         if (tmp->chan->cid.cid_ani)
1742                 ast_free(tmp->chan->cid.cid_ani);
1743         tmp->chan->cid.cid_ani = ast_strdup(qe->chan->cid.cid_ani);
1744
1745         /* Inherit specially named variables from parent channel */
1746         ast_channel_inherit_variables(qe->chan, tmp->chan);
1747
1748         /* Presense of ADSI CPE on outgoing channel follows ours */
1749         tmp->chan->adsicpe = qe->chan->adsicpe;
1750
1751         /* Place the call, but don't wait on the answer */
1752         if ((res = ast_call(tmp->chan, location, 0))) {
1753                 /* Again, keep going even if there's an error */
1754                 if (option_debug)
1755                         ast_log(LOG_DEBUG, "ast call on peer returned %d\n", res);
1756                 if (option_verbose > 2)
1757                         ast_verbose(VERBOSE_PREFIX_3 "Couldn't call %s\n", tmp->interface);
1758                 do_hang(tmp);
1759                 (*busies)++;
1760                 return 0;
1761         } else if (qe->parent->eventwhencalled) {
1762                 char vars[2048];
1763
1764                 manager_event(EVENT_FLAG_AGENT, "AgentCalled",
1765                                         "AgentCalled: %s\r\n"
1766                                         "ChannelCalling: %s\r\n"
1767                                         "CallerIDNum: %s\r\n"
1768                                         "CallerIDName: %s\r\n"
1769                                         "Context: %s\r\n"
1770                                         "Extension: %s\r\n"
1771                                         "Priority: %d\r\n"
1772                                         "%s",
1773                                         tmp->interface, qe->chan->name,
1774                                         tmp->chan->cid.cid_num ? tmp->chan->cid.cid_num : "unknown",
1775                                         tmp->chan->cid.cid_name ? tmp->chan->cid.cid_name : "unknown",
1776                                         qe->chan->context, qe->chan->exten, qe->chan->priority,
1777                                         qe->parent->eventwhencalled == QUEUE_EVENT_VARIABLES ? vars2manager(qe->chan, vars, sizeof(vars)) : "");
1778                 if (option_verbose > 2)
1779                         ast_verbose(VERBOSE_PREFIX_3 "Called %s\n", tmp->interface);
1780         }
1781
1782         return 1;
1783 }
1784
1785 /*! \brief find the entry with the best metric, or NULL */
1786 static struct callattempt *find_best(struct callattempt *outgoing)
1787 {
1788         struct callattempt *best = NULL, *cur;
1789
1790         for (cur = outgoing; cur; cur = cur->q_next) {
1791                 if (cur->stillgoing &&                                  /* Not already done */
1792                         !cur->chan &&                                   /* Isn't already going */
1793                         (!best || cur->metric < best->metric)) {                /* We haven't found one yet, or it's better */
1794                         best = cur;
1795                 }
1796         }
1797
1798         return best;
1799 }
1800
1801 static int ring_one(struct queue_ent *qe, struct callattempt *outgoing, int *busies)
1802 {
1803         int ret = 0;
1804
1805         while (ret == 0) {
1806                 struct callattempt *best = find_best(outgoing);
1807                 if (!best) {
1808                         if (option_debug)
1809                                 ast_log(LOG_DEBUG, "Nobody left to try ringing in queue\n");
1810                         break;
1811                 }
1812                 if (qe->parent->strategy == QUEUE_STRATEGY_RINGALL) {
1813                         struct callattempt *cur;
1814                         /* Ring everyone who shares this best metric (for ringall) */
1815                         for (cur = outgoing; cur; cur = cur->q_next) {
1816                                 if (cur->stillgoing && !cur->chan && cur->metric <= best->metric) {
1817                                         if (option_debug)
1818                                                 ast_log(LOG_DEBUG, "(Parallel) Trying '%s' with metric %d\n", cur->interface, cur->metric);
1819                                         ring_entry(qe, cur, busies);
1820                                 }
1821                         }
1822                 } else {
1823                         /* Ring just the best channel */
1824                         if (option_debug)
1825                                 ast_log(LOG_DEBUG, "Trying '%s' with metric %d\n", best->interface, best->metric);
1826                         ring_entry(qe, best, busies);
1827                 }
1828                 if (best->chan) /* break out with result = 1 */
1829                         ret = 1;
1830         }
1831
1832         return ret;
1833 }
1834
1835 static int store_next(struct queue_ent *qe, struct callattempt *outgoing)
1836 {
1837         struct callattempt *best = find_best(outgoing);
1838
1839         if (best) {
1840                 /* Ring just the best channel */
1841                 if (option_debug)
1842                         ast_log(LOG_DEBUG, "Next is '%s' with metric %d\n", best->interface, best->metric);
1843                 qe->parent->rrpos = best->metric % 1000;
1844         } else {
1845                 /* Just increment rrpos */
1846                 if (qe->parent->wrapped) {
1847                         /* No more channels, start over */
1848                         qe->parent->rrpos = 0;
1849                 } else {
1850                         /* Prioritize next entry */
1851                         qe->parent->rrpos++;
1852                 }
1853         }
1854         qe->parent->wrapped = 0;
1855
1856         return 0;
1857 }
1858
1859 static int background_file(struct queue_ent *qe, struct ast_channel *chan, char *filename)
1860 {
1861         int res;
1862
1863         ast_stopstream(chan);
1864         res = ast_streamfile(chan, filename, chan->language);
1865
1866         if (!res) {
1867                 /* Wait for a keypress */
1868                 res = ast_waitstream(chan, AST_DIGIT_ANY);
1869                 if (res < 0 || !valid_exit(qe, res))
1870                         res = 0;
1871
1872                 /* Stop playback */
1873                 ast_stopstream(chan);
1874         }
1875         
1876         return res;
1877 }
1878
1879 static int say_periodic_announcement(struct queue_ent *qe)
1880 {
1881         int res = 0;
1882         time_t now;
1883
1884         /* Get the current time */
1885         time(&now);
1886
1887         /* Check to see if it is time to announce */
1888         if ((now - qe->last_periodic_announce_time) < qe->parent->periodicannouncefrequency)
1889                 return 0;
1890
1891         /* Stop the music on hold so we can play our own file */
1892         ast_moh_stop(qe->chan);
1893
1894         if (option_verbose > 2)
1895                 ast_verbose(VERBOSE_PREFIX_3 "Playing periodic announcement\n");
1896
1897         /* Check to make sure we have a sound file. If not, reset to the first sound file */
1898         if (qe->last_periodic_announce_sound >= MAX_PERIODIC_ANNOUNCEMENTS || !strlen(qe->parent->sound_periodicannounce[qe->last_periodic_announce_sound])) {
1899                 qe->last_periodic_announce_sound = 0;
1900         }
1901         
1902         /* play the announcement */
1903         res = background_file(qe, qe->chan, qe->parent->sound_periodicannounce[qe->last_periodic_announce_sound]);
1904
1905         /* Resume Music on Hold if the caller is going to stay in the queue */
1906         if (!res)
1907                 ast_moh_start(qe->chan, qe->moh, NULL);
1908
1909         /* update last_periodic_announce_time */
1910         qe->last_periodic_announce_time = now;
1911
1912         /* Update the current periodic announcement to the next announcement */
1913         qe->last_periodic_announce_sound++;
1914         
1915         return res;
1916 }
1917
1918 static void record_abandoned(struct queue_ent *qe)
1919 {
1920         ast_mutex_lock(&qe->parent->lock);
1921         set_queue_variables(qe);
1922         manager_event(EVENT_FLAG_AGENT, "QueueCallerAbandon",
1923                 "Queue: %s\r\n"
1924                 "Uniqueid: %s\r\n"
1925                 "Position: %d\r\n"
1926                 "OriginalPosition: %d\r\n"
1927                 "HoldTime: %d\r\n",
1928                 qe->parent->name, qe->chan->uniqueid, qe->pos, qe->opos, (int)(time(NULL) - qe->start));
1929
1930         qe->parent->callsabandoned++;
1931         ast_mutex_unlock(&qe->parent->lock);
1932 }
1933
1934 /*! \brief RNA == Ring No Answer. Common code that is executed when we try a queue member and they don't answer. */
1935 static void rna(int rnatime, struct queue_ent *qe, char *interface, char *membername)
1936 {
1937         if (option_verbose > 2)
1938                 ast_verbose( VERBOSE_PREFIX_3 "Nobody picked up in %d ms\n", rnatime);
1939         ast_queue_log(qe->parent->name, qe->chan->uniqueid, membername, "RINGNOANSWER", "%d", rnatime);
1940         if (qe->parent->autopause) {
1941                 if (!set_member_paused(qe->parent->name, interface, 1)) {
1942                         if (option_verbose > 2)
1943                                 ast_verbose( VERBOSE_PREFIX_3 "Auto-Pausing Queue Member %s in queue %s since they failed to answer.\n", interface, qe->parent->name);
1944                 } else {
1945                         if (option_verbose > 2)
1946                                 ast_verbose( VERBOSE_PREFIX_3 "Failed to pause Queue Member %s in queue %s!\n", interface, qe->parent->name);
1947                 }
1948         }
1949         return;
1950 }
1951
1952 #define AST_MAX_WATCHERS 256
1953
1954 static struct callattempt *wait_for_answer(struct queue_ent *qe, struct callattempt *outgoing, int *to, char *digit, int prebusies, int caller_disconnect, int forwardsallowed)
1955 {
1956         char *queue = qe->parent->name;
1957         struct callattempt *o;
1958         int status;
1959         int sentringing = 0;
1960         int numbusies = prebusies;
1961         int numnochan = 0;
1962         int stillgoing = 0;
1963         int orig = *to;
1964         struct ast_frame *f;
1965         struct callattempt *peer = NULL;
1966         struct ast_channel *winner;
1967         struct ast_channel *in = qe->chan;
1968         char on[80] = "";
1969         char membername[80] = "";
1970         long starttime = 0;
1971         long endtime = 0;       
1972
1973         starttime = (long) time(NULL);
1974         
1975         while (*to && !peer) {
1976                 int numlines, retry, pos = 1;
1977                 struct ast_channel *watchers[AST_MAX_WATCHERS];
1978                 watchers[0] = in;
1979
1980                 for (retry = 0; retry < 2; retry++) {
1981                         numlines = 0;
1982                         for (o = outgoing; o; o = o->q_next) { /* Keep track of important channels */
1983                                 if (o->stillgoing) {    /* Keep track of important channels */
1984                                         stillgoing = 1;
1985                                         if (o->chan)
1986                                                 watchers[pos++] = o->chan;
1987                                 }
1988                                 numlines++;
1989                         }
1990                         if (pos > 1 /* found */ || !stillgoing /* nobody listening */ ||
1991                                 (qe->parent->strategy != QUEUE_STRATEGY_RINGALL) /* ring would not be delivered */)
1992                                 break;
1993                         /* On "ringall" strategy we only move to the next penalty level
1994                            when *all* ringing phones are done in the current penalty level */
1995                         ring_one(qe, outgoing, &numbusies);
1996                         /* and retry... */
1997                 }
1998                 if (pos == 1 /* not found */) {
1999                         if (numlines == (numbusies + numnochan)) {
2000                                 if (option_debug)
2001                                         ast_log(LOG_DEBUG, "Everyone is busy at this time\n");
2002                         } else {
2003                                 ast_log(LOG_NOTICE, "No one is answering queue '%s' (%d/%d/%d)\n", queue, numlines, numbusies, numnochan);
2004                         }
2005                         *to = 0;
2006                         return NULL;
2007                 }
2008                 winner = ast_waitfor_n(watchers, pos, to);
2009                 for (o = outgoing; o; o = o->q_next) {
2010                         if (o->stillgoing && (o->chan) &&  (o->chan->_state == AST_STATE_UP)) {
2011                                 if (!peer) {
2012                                         if (option_verbose > 2)
2013                                                 ast_verbose( VERBOSE_PREFIX_3 "%s answered %s\n", o->chan->name, in->name);
2014                                         peer = o;
2015                                 }
2016                         } else if (o->chan && (o->chan == winner)) {
2017
2018                                 ast_copy_string(on, o->member->interface, sizeof(on));
2019                                 ast_copy_string(membername, o->member->membername, sizeof(membername));
2020
2021                                 if (!ast_strlen_zero(o->chan->call_forward) && !forwardsallowed) {
2022                                         if (option_verbose > 2)
2023                                                 ast_verbose(VERBOSE_PREFIX_3 "Forwarding %s to '%s' prevented.\n", in->name, o->chan->call_forward);
2024                                         numnochan++;
2025                                         do_hang(o);
2026                                         winner = NULL;
2027                                         continue;
2028                                 } else if (!ast_strlen_zero(o->chan->call_forward)) {
2029                                         char tmpchan[256];
2030                                         char *stuff;
2031                                         char *tech;
2032
2033                                         ast_copy_string(tmpchan, o->chan->call_forward, sizeof(tmpchan));
2034                                         if ((stuff = strchr(tmpchan, '/'))) {
2035                                                 *stuff++ = '\0';
2036                                                 tech = tmpchan;
2037                                         } else {
2038                                                 snprintf(tmpchan, sizeof(tmpchan), "%s@%s", o->chan->call_forward, o->chan->context);
2039                                                 stuff = tmpchan;
2040                                                 tech = "Local";
2041                                         }
2042                                         /* Before processing channel, go ahead and check for forwarding */
2043                                         if (option_verbose > 2)
2044                                                 ast_verbose(VERBOSE_PREFIX_3 "Now forwarding %s to '%s/%s' (thanks to %s)\n", in->name, tech, stuff, o->chan->name);
2045                                         /* Setup parameters */
2046                                         o->chan = ast_request(tech, in->nativeformats, stuff, &status);
2047                                         if (status != o->oldstatus)
2048                                                 update_dial_status(qe->parent, o->member, status);                                              
2049                                         if (!o->chan) {
2050                                                 ast_log(LOG_NOTICE, "Unable to create local channel for call forward to '%s/%s'\n", tech, stuff);
2051                                                 o->stillgoing = 0;
2052                                                 numnochan++;
2053                                         } else {
2054                                                 ast_channel_inherit_variables(in, o->chan);
2055                                                 if (o->chan->cid.cid_num)
2056                                                         ast_free(o->chan->cid.cid_num);
2057                                                 o->chan->cid.cid_num = ast_strdup(in->cid.cid_num);
2058
2059                                                 if (o->chan->cid.cid_name)
2060                                                         ast_free(o->chan->cid.cid_name);
2061                                                 o->chan->cid.cid_name = ast_strdup(in->cid.cid_name);
2062
2063                                                 ast_string_field_set(o->chan, accountcode, in->accountcode);
2064                                                 o->chan->cdrflags = in->cdrflags;
2065
2066                                                 if (in->cid.cid_ani) {
2067                                                         if (o->chan->cid.cid_ani)
2068                                                                 ast_free(o->chan->cid.cid_ani);
2069                                                         o->chan->cid.cid_ani = ast_strdup(in->cid.cid_ani);
2070                                                 }
2071                                                 if (o->chan->cid.cid_rdnis)
2072                                                         ast_free(o->chan->cid.cid_rdnis);
2073                                                 o->chan->cid.cid_rdnis = ast_strdup(S_OR(in->macroexten, in->exten));
2074                                                 if (ast_call(o->chan, tmpchan, 0)) {
2075                                                         ast_log(LOG_NOTICE, "Failed to dial on local channel for call forward to '%s'\n", tmpchan);
2076                                                         do_hang(o);
2077                                                         numnochan++;
2078                                                 }
2079                                         }
2080                                         /* Hangup the original channel now, in case we needed it */
2081                                         ast_hangup(winner);
2082                                         continue;
2083                                 }
2084                                 f = ast_read(winner);
2085                                 if (f) {
2086                                         if (f->frametype == AST_FRAME_CONTROL) {
2087                                                 switch (f->subclass) {
2088                                                 case AST_CONTROL_ANSWER:
2089                                                         /* This is our guy if someone answered. */
2090                                                         if (!peer) {
2091                                                                 if (option_verbose > 2)
2092                                                                         ast_verbose( VERBOSE_PREFIX_3 "%s answered %s\n", o->chan->name, in->name);
2093                                                                 peer = o;
2094                                                         }
2095                                                         break;
2096                                                 case AST_CONTROL_BUSY:
2097                                                         if (option_verbose > 2)
2098                                                                 ast_verbose( VERBOSE_PREFIX_3 "%s is busy\n", o->chan->name);
2099                                                         if (in->cdr)
2100                                                                 ast_cdr_busy(in->cdr);
2101                                                         do_hang(o);
2102                                                         endtime = (long) time(NULL);
2103                                                         endtime -= starttime;
2104                                                         rna(endtime*1000, qe, on, membername);
2105                                                         if (qe->parent->strategy != QUEUE_STRATEGY_RINGALL) {
2106                                                                 if (qe->parent->timeoutrestart)
2107                                                                         *to = orig;
2108                                                                 ring_one(qe, outgoing, &numbusies);
2109                                                         }
2110                                                         numbusies++;
2111                                                         break;
2112                                                 case AST_CONTROL_CONGESTION:
2113                                                         if (option_verbose > 2)
2114                                                                 ast_verbose( VERBOSE_PREFIX_3 "%s is circuit-busy\n", o->chan->name);
2115                                                         if (in->cdr)
2116                                                                 ast_cdr_busy(in->cdr);
2117                                                         endtime = (long) time(NULL);
2118                                                         endtime -= starttime;
2119                                                         rna(endtime*1000, qe, on, membername);
2120                                                         do_hang(o);
2121                                                         if (qe->parent->strategy != QUEUE_STRATEGY_RINGALL) {
2122                                                                 if (qe->parent->timeoutrestart)
2123                                                                         *to = orig;
2124                                                                 ring_one(qe, outgoing, &numbusies);
2125                                                         }
2126                                                         numbusies++;
2127                                                         break;
2128                                                 case AST_CONTROL_RINGING:
2129                                                         if (option_verbose > 2)
2130                                                                 ast_verbose( VERBOSE_PREFIX_3 "%s is ringing\n", o->chan->name);
2131                                                         if (!sentringing) {
2132 #if 0
2133                                                                 ast_indicate(in, AST_CONTROL_RINGING);
2134 #endif                                                          
2135                                                                 sentringing++;
2136                                                         }
2137                                                         break;
2138                                                 case AST_CONTROL_OFFHOOK:
2139                                                         /* Ignore going off hook */
2140                                                         break;
2141                                                 default:
2142                                                         if (option_debug)
2143                                                                 ast_log(LOG_DEBUG, "Dunno what to do with control type %d\n", f->subclass);
2144                                                 }
2145                                         }
2146                                         ast_frfree(f);
2147                                 } else {
2148                                         endtime = (long) time(NULL) - starttime;
2149                                         rna(endtime * 1000, qe, on, membername);
2150                                         do_hang(o);
2151                                         if (qe->parent->strategy != QUEUE_STRATEGY_RINGALL) {
2152                                                 if (qe->parent->timeoutrestart)
2153                                                         *to = orig;
2154                                                 ring_one(qe, outgoing, &numbusies);
2155                                         }
2156                                 }
2157                         }
2158                 }
2159                 if (winner == in) {
2160                         f = ast_read(in);
2161                         if (!f || ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_HANGUP))) {
2162                                 /* Got hung up */
2163                                 *to = -1;
2164                                 if (f)
2165                                         ast_frfree(f);
2166                                 return NULL;
2167                         }
2168                         if ((f->frametype == AST_FRAME_DTMF) && caller_disconnect && (f->subclass == '*')) {
2169                                 if (option_verbose > 3)
2170                                         ast_verbose(VERBOSE_PREFIX_3 "User hit %c to disconnect call.\n", f->subclass);
2171                                 *to = 0;
2172                                 ast_frfree(f);
2173                                 return NULL;
2174                         }
2175                         if ((f->frametype == AST_FRAME_DTMF) && valid_exit(qe, f->subclass)) {
2176                                 if (option_verbose > 3)
2177                                         ast_verbose(VERBOSE_PREFIX_3 "User pressed digit: %c\n", f->subclass);
2178                                 *to = 0;
2179                                 *digit = f->subclass;
2180                                 ast_frfree(f);
2181                                 return NULL;
2182                         }
2183                         ast_frfree(f);
2184                 }
2185                 if (!*to)
2186                         rna(orig, qe, on, membername);
2187         }
2188
2189         return peer;
2190 }
2191
2192 static int is_our_turn(struct queue_ent *qe)
2193 {
2194         struct queue_ent *ch;
2195         struct member *cur;
2196         int avl = 0;
2197         int idx = 0;
2198         int res;
2199
2200         if (!qe->parent->autofill) {
2201                 /* Atomically read the parent head -- does not need a lock */
2202                 ch = qe->parent->head;
2203                 /* If we are now at the top of the head, break out */
2204                 if (ch == qe) {
2205                         if (option_debug)
2206                                 ast_log(LOG_DEBUG, "It's our turn (%s).\n", qe->chan->name);
2207                         res = 1;
2208                 } else {
2209                         if (option_debug)
2210                                 ast_log(LOG_DEBUG, "It's not our turn (%s).\n", qe->chan->name);
2211                         res = 0;
2212                 }       
2213
2214         } else {
2215                 /* This needs a lock. How many members are available to be served? */
2216                 ast_mutex_lock(&qe->parent->lock);
2217                         
2218                 ch = qe->parent->head;
2219         
2220                 if (qe->parent->strategy == QUEUE_STRATEGY_RINGALL) {
2221                         if (option_debug)
2222                                 ast_log(LOG_DEBUG, "Even though there are %d available members, the strategy is ringall so only the head call is allowed in\n", avl);
2223                         avl = 1;
2224                 } else {
2225                         for (cur = qe->parent->members; cur; cur = cur->next) {
2226                                 switch (cur->status) {
2227                                 case AST_DEVICE_NOT_INUSE:
2228                                 case AST_DEVICE_UNKNOWN:
2229                                         avl++;
2230                                         break;
2231                                 }
2232                         }
2233                 }
2234
2235                 if (option_debug)
2236                         ast_log(LOG_DEBUG, "There are %d available members.\n", avl);
2237         
2238                 while ((idx < avl) && (ch) && (ch != qe)) {
2239                         idx++;
2240                         ch = ch->next;                  
2241                 }
2242         
2243                 /* If the queue entry is within avl [the number of available members] calls from the top ... */
2244                 if (ch && idx < avl) {
2245                         if (option_debug)
2246                                 ast_log(LOG_DEBUG, "It's our turn (%s).\n", qe->chan->name);
2247                         res = 1;
2248                 } else {
2249                         if (option_debug)
2250                                 ast_log(LOG_DEBUG, "It's not our turn (%s).\n", qe->chan->name);
2251                         res = 0;
2252                 }
2253                 
2254                 ast_mutex_unlock(&qe->parent->lock);
2255         }
2256
2257         return res;
2258 }
2259
2260 static int wait_our_turn(struct queue_ent *qe, int ringing, enum queue_result *reason)
2261 {
2262         int res = 0;
2263
2264         /* This is the holding pen for callers 2 through maxlen */
2265         for (;;) {
2266                 enum queue_member_status stat;
2267
2268                 if (is_our_turn(qe))
2269                         break;
2270
2271                 /* If we have timed out, break out */
2272                 if (qe->expire && (time(NULL) > qe->expire)) {
2273                         *reason = QUEUE_TIMEOUT;
2274                         break;
2275                 }
2276
2277                 stat = get_member_status(qe->parent, qe->max_penalty);
2278
2279                 /* leave the queue if no agents, if enabled */
2280                 if (qe->parent->leavewhenempty && (stat == QUEUE_NO_MEMBERS)) {
2281                         *reason = QUEUE_LEAVEEMPTY;
2282                         ast_queue_log(qe->parent->name, qe->chan->uniqueid, "NONE", "EXITEMPTY", "%d|%d|%ld", qe->pos, qe->opos, (long) time(NULL) - qe->start);
2283                         leave_queue(qe);
2284                         break;
2285                 }
2286
2287                 /* leave the queue if no reachable agents, if enabled */
2288                 if ((qe->parent->leavewhenempty == QUEUE_EMPTY_STRICT) && (stat == QUEUE_NO_REACHABLE_MEMBERS || stat == QUEUE_NO_UNPAUSED_REACHABLE_MEMBERS)) {
2289                         *reason = QUEUE_LEAVEUNAVAIL;
2290                         ast_queue_log(qe->parent->name, qe->chan->uniqueid, "NONE", "EXITEMPTY", "%d|%d|%ld", qe->pos, qe->opos, (long) time(NULL) - qe->start);
2291                         leave_queue(qe);
2292                         break;
2293                 }
2294                 if ((qe->parent->leavewhenempty == QUEUE_EMPTY_LOOSE) && (stat == QUEUE_NO_REACHABLE_MEMBERS)) {
2295                         *reason = QUEUE_LEAVEUNAVAIL;
2296                         ast_queue_log(qe->parent->name, qe->chan->uniqueid, "NONE", "EXITEMPTY", "%d|%d|%ld", qe->pos, qe->opos, (long) time(NULL) - qe->start);
2297                         leave_queue(qe);
2298                         break;
2299                 }
2300
2301                 /* Make a position announcement, if enabled */
2302                 if (qe->parent->announcefrequency && !ringing &&
2303                         (res = say_position(qe)))
2304                         break;
2305
2306                 /* Make a periodic announcement, if enabled */
2307                 if (qe->parent->periodicannouncefrequency && !ringing &&
2308                         (res = say_periodic_announcement(qe)))
2309                         break;
2310
2311                 /* Wait a second before checking again */
2312                 if ((res = ast_waitfordigit(qe->chan, RECHECK * 1000)))
2313                         break;
2314         }
2315
2316         return res;
2317 }
2318
2319 static int update_queue(struct call_queue *q, struct member *member)
2320 {
2321         struct member *cur;
2322
2323         /* Since a reload could have taken place, we have to traverse the list to
2324                 be sure it's still valid */
2325         ast_mutex_lock(&q->lock);
2326         cur = q->members;
2327         while (cur) {
2328                 if (member == cur) {
2329                         time(&cur->lastcall);
2330                         cur->calls++;
2331                         break;
2332                 }
2333                 cur = cur->next;
2334         }
2335         q->callscompleted++;
2336         ast_mutex_unlock(&q->lock);
2337         return 0;
2338 }
2339
2340 static int calc_metric(struct call_queue *q, struct member *mem, int pos, struct queue_ent *qe, struct callattempt *tmp)
2341 {
2342         if (qe->max_penalty && (mem->penalty > qe->max_penalty))
2343                 return -1;
2344
2345         switch (q->strategy) {
2346         case QUEUE_STRATEGY_RINGALL:
2347                 /* Everyone equal, except for penalty */
2348                 tmp->metric = mem->penalty * 1000000;
2349                 break;
2350         case QUEUE_STRATEGY_RRMEMORY:
2351                 if (pos < q->rrpos) {
2352                         tmp->metric = 1000 + pos;
2353                 } else {
2354                         if (pos > q->rrpos)
2355                                 /* Indicate there is another priority */
2356                                 q->wrapped = 1;
2357                         tmp->metric = pos;
2358                 }
2359                 tmp->metric += mem->penalty * 1000000;
2360                 break;
2361         case QUEUE_STRATEGY_RANDOM:
2362                 tmp->metric = ast_random() % 1000;
2363                 tmp->metric += mem->penalty * 1000000;
2364                 break;
2365         case QUEUE_STRATEGY_FEWESTCALLS:
2366                 tmp->metric = mem->calls;
2367                 tmp->metric += mem->penalty * 1000000;
2368                 break;
2369         case QUEUE_STRATEGY_LEASTRECENT:
2370                 if (!mem->lastcall)
2371                         tmp->metric = 0;
2372                 else
2373                         tmp->metric = 1000000 - (time(NULL) - mem->lastcall);
2374                 tmp->metric += mem->penalty * 1000000;
2375                 break;
2376         default:
2377                 ast_log(LOG_WARNING, "Can't calculate metric for unknown strategy %d\n", q->strategy);
2378                 break;
2379         }
2380         return 0;
2381 }
2382
2383 enum agent_complete_reason {
2384         CALLER,
2385         AGENT,
2386         TRANSFER
2387 };
2388
2389 static void send_agent_complete(const struct queue_ent *qe, const char *queuename,
2390         const struct ast_channel *peer, const struct member *member, time_t callstart,
2391         char *vars, size_t vars_len, enum agent_complete_reason rsn)
2392 {
2393         const char *reason;
2394
2395         if (!qe->parent->eventwhencalled)
2396                 return;
2397
2398         switch (rsn) {
2399         case CALLER:
2400                 reason = "caller";
2401                 break;
2402         case AGENT:
2403                 reason = "agent";
2404                 break;
2405         case TRANSFER:
2406                 reason = "transfer";
2407                 break;
2408         }
2409
2410         manager_event(EVENT_FLAG_AGENT, "AgentComplete",
2411                 "Queue: %s\r\n"
2412                 "Uniqueid: %s\r\n"
2413                 "Channel: %s\r\n"
2414                 "Member: %s\r\n"
2415                 "MemberName: %s\r\n"
2416                 "HoldTime: %ld\r\n"
2417                 "TalkTime: %ld\r\n"
2418                 "Reason: %s\r\n"
2419                 "%s",
2420                 queuename, qe->chan->uniqueid, peer->name, member->interface, member->membername,
2421                 (long)(callstart - qe->start), (long)(time(NULL) - callstart), reason,
2422                 qe->parent->eventwhencalled == QUEUE_EVENT_VARIABLES ? vars2manager(qe->chan, vars, vars_len) : "");
2423 }
2424
2425 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)
2426 {
2427         struct member *cur;
2428         struct callattempt *outgoing = NULL; /* the list of calls we are building */
2429         int to;
2430         char oldexten[AST_MAX_EXTENSION]="";
2431         char oldcontext[AST_MAX_CONTEXT]="";
2432         char queuename[256]="";
2433         char interfacevar[256]="";
2434         struct ast_channel *peer;
2435         struct ast_channel *which;
2436         struct callattempt *lpeer;
2437         struct member *member;
2438         struct ast_app *app;
2439         int res = 0, bridge = 0;
2440         int numbusies = 0;
2441         int x=0;
2442         char *announce = NULL;
2443         char digit = 0;
2444         time_t callstart;
2445         time_t now = time(NULL);
2446         struct ast_bridge_config bridge_config;
2447         char nondataquality = 1;
2448         char *agiexec = NULL;
2449         char *macroexec = NULL;
2450         int ret = 0;
2451         const char *monitorfilename;
2452         const char *monitor_exec;
2453         const char *monitor_options;
2454         char tmpid[256], tmpid2[256];
2455         char meid[1024], meid2[1024];
2456         char mixmonargs[1512];
2457         struct ast_app *mixmonapp = NULL;
2458         char *p;
2459         char vars[2048];
2460         int forwardsallowed = 1;
2461         memset(&bridge_config, 0, sizeof(bridge_config));
2462         time(&now);
2463                 
2464         for (; options && *options; options++)
2465                 switch (*options) {
2466                 case 't':
2467                         ast_set_flag(&(bridge_config.features_callee), AST_FEATURE_REDIRECT);
2468                         break;
2469                 case 'T':
2470                         ast_set_flag(&(bridge_config.features_caller), AST_FEATURE_REDIRECT);
2471                         break;
2472                 case 'w':
2473                         ast_set_flag(&(bridge_config.features_callee), AST_FEATURE_AUTOMON);
2474                         break;
2475                 case 'W':
2476                         ast_set_flag(&(bridge_config.features_caller), AST_FEATURE_AUTOMON);
2477                         break;
2478                 case 'd':
2479                         nondataquality = 0;
2480                         break;
2481                 case 'h':
2482                         ast_set_flag(&(bridge_config.features_callee), AST_FEATURE_DISCONNECT);
2483                         break;
2484                 case 'H':
2485                         ast_set_flag(&(bridge_config.features_caller), AST_FEATURE_DISCONNECT);
2486                         break;
2487                 case 'n':
2488                         if ((now - qe->start >= qe->parent->timeout))
2489                                 *go_on = 1;
2490                         break;
2491                 case 'i':
2492                         forwardsallowed = 0;
2493                         break;
2494                 }
2495
2496         /* Hold the lock while we setup the outgoing calls */
2497         if (use_weight)
2498                 AST_LIST_LOCK(&queues);
2499         ast_mutex_lock(&qe->parent->lock);
2500         if (option_debug)
2501                 ast_log(LOG_DEBUG, "%s is trying to call a queue member.\n",
2502                                                         qe->chan->name);
2503         ast_copy_string(queuename, qe->parent->name, sizeof(queuename));
2504         cur = qe->parent->members;
2505         if (!ast_strlen_zero(qe->announce))
2506                 announce = qe->announce;
2507         if (!ast_strlen_zero(announceoverride))
2508                 announce = announceoverride;
2509
2510         for (; cur; cur = cur->next) {
2511                 struct callattempt *tmp = ast_calloc(1, sizeof(*tmp));
2512
2513                 if (!tmp) {
2514                         ast_mutex_unlock(&qe->parent->lock);
2515                         if (use_weight)
2516                                 AST_LIST_UNLOCK(&queues);
2517                         goto out;
2518                 }
2519                 tmp->stillgoing = -1;
2520                 tmp->member = cur;              /* Never directly dereference!  Could change on reload */
2521                 tmp->oldstatus = cur->status;
2522                 tmp->lastcall = cur->lastcall;
2523                 ast_copy_string(tmp->interface, cur->interface, sizeof(tmp->interface));
2524                 /* Special case: If we ring everyone, go ahead and ring them, otherwise
2525                    just calculate their metric for the appropriate strategy */
2526                 if (!calc_metric(qe->parent, cur, x++, qe, tmp)) {
2527                         /* Put them in the list of outgoing thingies...  We're ready now.
2528                            XXX If we're forcibly removed, these outgoing calls won't get
2529                            hung up XXX */
2530                         tmp->q_next = outgoing;
2531                         outgoing = tmp;         
2532                         /* If this line is up, don't try anybody else */
2533                         if (outgoing->chan && (outgoing->chan->_state == AST_STATE_UP))
2534                                 break;
2535                 } else {
2536                         ast_free(tmp);
2537                 }
2538         }
2539         if (qe->expire && (!qe->parent->timeout || (qe->expire - now) <= qe->parent->timeout))
2540                 to = (qe->expire - now) * 1000;
2541         else
2542                 to = (qe->parent->timeout) ? qe->parent->timeout * 1000 : -1;
2543         ring_one(qe, outgoing, &numbusies);
2544         ast_mutex_unlock(&qe->parent->lock);
2545         if (use_weight)
2546                 AST_LIST_UNLOCK(&queues);
2547         lpeer = wait_for_answer(qe, outgoing, &to, &digit, numbusies, ast_test_flag(&(bridge_config.features_caller), AST_FEATURE_DISCONNECT), forwardsallowed);
2548         ast_mutex_lock(&qe->parent->lock);
2549         if (qe->parent->strategy == QUEUE_STRATEGY_RRMEMORY) {
2550                 store_next(qe, outgoing);
2551         }
2552         ast_mutex_unlock(&qe->parent->lock);
2553         peer = lpeer ? lpeer->chan : NULL;
2554         if (!peer) {
2555                 if (to) {
2556                         /* Must gotten hung up */
2557                         res = -1;
2558                 } else {
2559                         res = digit;
2560                 }
2561                 if (option_debug)
2562                         ast_log(LOG_DEBUG, "%s: Nobody answered.\n", qe->chan->name);
2563         } else { /* peer is valid */
2564                 /* Ah ha!  Someone answered within the desired timeframe.  Of course after this
2565                    we will always return with -1 so that it is hung up properly after the
2566                    conversation.  */
2567                 qe->handled++;
2568                 if (!strcmp(qe->chan->tech->type, "Zap"))
2569                         ast_channel_setoption(qe->chan, AST_OPTION_TONE_VERIFY, &nondataquality, sizeof(nondataquality), 0);
2570                 if (!strcmp(peer->tech->type, "Zap"))
2571                         ast_channel_setoption(peer, AST_OPTION_TONE_VERIFY, &nondataquality, sizeof(nondataquality), 0);
2572                 /* Update parameters for the queue */
2573                 recalc_holdtime(qe);
2574                 member = lpeer->member;
2575                 hangupcalls(outgoing, peer);
2576                 outgoing = NULL;
2577                 if (announce || qe->parent->reportholdtime || qe->parent->memberdelay) {
2578                         int res2;
2579
2580                         res2 = ast_autoservice_start(qe->chan);
2581                         if (!res2) {
2582                                 if (qe->parent->memberdelay) {
2583                                         ast_log(LOG_NOTICE, "Delaying member connect for %d seconds\n", qe->parent->memberdelay);
2584                                         res2 |= ast_safe_sleep(peer, qe->parent->memberdelay * 1000);
2585                                 }
2586                                 if (!res2 && announce) {
2587                                         if (play_file(peer, announce))
2588                                                 ast_log(LOG_WARNING, "Announcement file '%s' is unavailable, continuing anyway...\n", announce);
2589                                 }
2590                                 if (!res2 && qe->parent->reportholdtime) {
2591                                         if (!play_file(peer, qe->parent->sound_reporthold)) {
2592                                                 int holdtime;
2593
2594                                                 time(&now);
2595                                                 holdtime = abs((now - qe->start) / 60);
2596                                                 if (holdtime < 2) {
2597                                                         play_file(peer, qe->parent->sound_lessthan);
2598                                                         ast_say_number(peer, 2, AST_DIGIT_ANY, peer->language, NULL);
2599                                                 } else
2600                                                         ast_say_number(peer, holdtime, AST_DIGIT_ANY, peer->language, NULL);
2601                                                 play_file(peer, qe->parent->sound_minutes);
2602                                         }
2603                                 }
2604                         }
2605                         res2 |= ast_autoservice_stop(qe->chan);
2606                         if (peer->_softhangup) {
2607                                 /* Agent must have hung up */
2608                                 ast_log(LOG_WARNING, "Agent on %s hungup on the customer.  They're going to be pissed.\n", peer->name);
2609                                 ast_queue_log(queuename, qe->chan->uniqueid, member->membername, "AGENTDUMP", "%s", "");
2610                                 record_abandoned(qe);
2611                                 if (qe->parent->eventwhencalled)
2612                                         manager_event(EVENT_FLAG_AGENT, "AgentDump",
2613                                                         "Queue: %s\r\n"
2614                                                         "Uniqueid: %s\r\n"
2615                                                         "Channel: %s\r\n"
2616                                                         "Member: %s\r\n"
2617                                                         "MemberName: %s\r\n"
2618                                                         "%s",
2619                                                         queuename, qe->chan->uniqueid, peer->name, member->interface, member->membername,
2620                                                         qe->parent->eventwhencalled == QUEUE_EVENT_VARIABLES ? vars2manager(qe->chan, vars, sizeof(vars)) : "");
2621                                 ast_hangup(peer);
2622                                 goto out;
2623                         } else if (res2) {
2624                                 /* Caller must have hung up just before being connected*/
2625                                 ast_log(LOG_NOTICE, "Caller was about to talk to agent on %s but the caller hungup.\n", peer->name);
2626                                 ast_queue_log(queuename, qe->chan->uniqueid, member->membername, "ABANDON", "%d|%d|%ld", qe->pos, qe->opos, (long) time(NULL) - qe->start);
2627                                 record_abandoned(qe);
2628                                 ast_hangup(peer);
2629                                 return -1;
2630                         }
2631                 }
2632                 /* Stop music on hold */
2633                 ast_moh_stop(qe->chan);
2634                 /* If appropriate, log that we have a destination channel */
2635                 if (qe->chan->cdr)
2636                         ast_cdr_setdestchan(qe->chan->cdr, peer->name);
2637                 /* Make sure channels are compatible */
2638                 res = ast_channel_make_compatible(qe->chan, peer);
2639                 if (res < 0) {
2640                         ast_queue_log(queuename, qe->chan->uniqueid, member->membername, "SYSCOMPAT", "%s", "");
2641                         ast_log(LOG_WARNING, "Had to drop call because I couldn't make %s compatible with %s\n", qe->chan->name, peer->name);
2642                         record_abandoned(qe);
2643                         ast_hangup(peer);
2644                         return -1;
2645                 }
2646                 /* Begin Monitoring */
2647                 if (qe->parent->monfmt && *qe->parent->monfmt) {
2648                         if (!qe->parent->montype) {
2649                                 if (option_debug)
2650                                         ast_log(LOG_DEBUG, "Starting Monitor as requested.\n");
2651                                 monitorfilename = pbx_builtin_getvar_helper(qe->chan, "MONITOR_FILENAME");
2652                                 if (pbx_builtin_getvar_helper(qe->chan, "MONITOR_EXEC") || pbx_builtin_getvar_helper(qe->chan, "MONITOR_EXEC_ARGS"))
2653                                         which = qe->chan;
2654                                 else
2655                                         which = peer;
2656                                 if (monitorfilename)
2657                                         ast_monitor_start(which, qe->parent->monfmt, monitorfilename, 1 );
2658                                 else if (qe->chan->cdr)
2659                                         ast_monitor_start(which, qe->parent->monfmt, qe->chan->cdr->uniqueid, 1 );
2660                                 else {
2661                                         /* Last ditch effort -- no CDR, make up something */
2662                                         snprintf(tmpid, sizeof(tmpid), "chan-%lx", ast_random());
2663                                         ast_monitor_start(which, qe->parent->monfmt, tmpid, 1 );
2664                                 }
2665                                 if (qe->parent->monjoin)
2666                                         ast_monitor_setjoinfiles(which, 1);
2667                         } else {
2668                                 if (option_debug)
2669                                         ast_log(LOG_DEBUG, "Starting MixMonitor as requested.\n");
2670                                 monitorfilename = pbx_builtin_getvar_helper(qe->chan, "MONITOR_FILENAME");
2671                                 if (!monitorfilename) {
2672                                         if (qe->chan->cdr)
2673                                                 ast_copy_string(tmpid, qe->chan->cdr->uniqueid, sizeof(tmpid)-1);
2674                                         else
2675                                                 snprintf(tmpid, sizeof(tmpid), "chan-%lx", ast_random());
2676                                 } else {
2677                                         ast_copy_string(tmpid2, monitorfilename, sizeof(tmpid2)-1);
2678                                         for (p = tmpid2; *p ; p++) {
2679                                                 if (*p == '^' && *(p+1) == '{') {
2680                                                         *p = '$';
2681                                                 }
2682                                         }
2683
2684                                         memset(tmpid, 0, sizeof(tmpid));
2685                                         pbx_substitute_variables_helper(qe->chan, tmpid2, tmpid, sizeof(tmpid) - 1);
2686                                 }
2687
2688                                 monitor_exec = pbx_builtin_getvar_helper(qe->chan, "MONITOR_EXEC");
2689                                 monitor_options = pbx_builtin_getvar_helper(qe->chan, "MONITOR_OPTIONS");
2690
2691                                 if (monitor_exec) {
2692                                         ast_copy_string(meid2, monitor_exec, sizeof(meid2)-1);
2693                                         for (p = meid2; *p ; p++) {
2694                                                 if (*p == '^' && *(p+1) == '{') {
2695                                                         *p = '$';
2696                                                 }
2697                                         }
2698
2699                                         memset(meid, 0, sizeof(meid));
2700                                         pbx_substitute_variables_helper(qe->chan, meid2, meid, sizeof(meid) - 1);
2701                                 }
2702         
2703                                 snprintf(tmpid2, sizeof(tmpid2)-1, "%s.%s", tmpid, qe->parent->monfmt);
2704
2705                                 mixmonapp = pbx_findapp("MixMonitor");
2706
2707                                 if (strchr(tmpid2, '|')) {
2708                                         ast_log(LOG_WARNING, "monitor-format (in queues.conf) and MONITOR_FILENAME cannot contain a '|'! Not recording.\n");
2709                                         mixmonapp = NULL;
2710                                 }
2711
2712                                 if (!monitor_options)
2713                                         monitor_options = "";
2714                                 
2715                                 if (strchr(monitor_options, '|')) {
2716                                         ast_log(LOG_WARNING, "MONITOR_OPTIONS cannot contain a '|'! Not recording.\n");
2717                                         mixmonapp = NULL;
2718                                 }
2719
2720                                 if (mixmonapp) {
2721                                         if (!ast_strlen_zero(monitor_exec))
2722                                                 snprintf(mixmonargs, sizeof(mixmonargs)-1, "%s|b%s|%s", tmpid2, monitor_options, monitor_exec);
2723                                         else
2724                                                 snprintf(mixmonargs, sizeof(mixmonargs)-1, "%s|b%s", tmpid2, monitor_options);
2725                                                 
2726                                         if (option_debug)
2727                                                 ast_log(LOG_DEBUG, "Arguments being passed to MixMonitor: %s\n", mixmonargs);
2728
2729                                         ret = pbx_exec(qe->chan, mixmonapp, mixmonargs);
2730
2731                                 } else
2732                                         ast_log(LOG_WARNING, "Asked to run MixMonitor on this call, but cannot find the MixMonitor app!\n");
2733
2734                         }
2735                 }
2736                 /* Drop out of the queue at this point, to prepare for next caller */
2737                 leave_queue(qe);                        
2738                 if (!ast_strlen_zero(url) && ast_channel_supports_html(peer)) {
2739                         if (option_debug)
2740                                 ast_log(LOG_DEBUG, "app_queue: sendurl=%s.\n", url);
2741                         ast_channel_sendurl(peer, url);
2742                 }
2743                 
2744                 ast_mutex_lock(&qe->parent->lock);
2745                 /* if setinterfacevar is defined, make member variables available to the channel */
2746                 /* use  pbx_builtin_setvar to set a load of variables with one call */
2747                 if (qe->parent->setinterfacevar) {
2748                         snprintf(interfacevar,sizeof(interfacevar), "MEMBERINTERFACE=%s|MEMBERNAME=%s|MEMBERCALLS=%d|MEMBERLASTCALL=%ld|MEMBERPENALTY=%d|MEMBERDYNAMIC=%d",
2749                                 member->interface, member->membername, member->calls, (long)member->lastcall, member->penalty, member->dynamic);
2750                         pbx_builtin_setvar(qe->chan, interfacevar);
2751                 }
2752                 
2753                 /* if setqueueentryvar is defined, make queue entry (i.e. the caller) variables available to the channel */
2754                 /* use  pbx_builtin_setvar to set a load of variables with one call */
2755                 if (qe->parent->setqueueentryvar) {
2756                         snprintf(interfacevar,sizeof(interfacevar), "QEHOLDTIME=%ld|QEORIGINALPOS=%d",
2757                                 (long) time(NULL) - qe->start, qe->opos);
2758                         pbx_builtin_setvar(qe->chan, interfacevar);
2759                 }
2760         
2761                 /* try to set queue variables if configured to do so*/
2762                 set_queue_variables(qe);
2763                 ast_mutex_unlock(&qe->parent->lock);
2764                 
2765                 /* run a macro for this connection if defined. The macro simply returns, no action is taken on the result */
2766                 /* use macro from dialplan if passed as a option, otherwise use the default queue macro */
2767                 if (!ast_strlen_zero(macro)) {
2768                                 macroexec = ast_strdupa(macro);
2769                 } else {
2770                         if (qe->parent->membermacro)
2771                                 macroexec = ast_strdupa(qe->parent->membermacro);
2772                 }
2773
2774                 if (!ast_strlen_zero(macroexec)) {
2775                         if (option_debug)
2776                                 ast_log(LOG_DEBUG, "app_queue: macro=%s.\n", macroexec);
2777                         
2778                         res = ast_autoservice_start(qe->chan);
2779                         if (res) {
2780                                 ast_log(LOG_ERROR, "Unable to start autoservice on calling channel\n");
2781                                 res = -1;
2782                         }
2783                         
2784                         app = pbx_findapp("Macro");
2785                         
2786                         if (app) {
2787                                 res = pbx_exec(qe->chan, app, macroexec);
2788                                 if (option_debug)
2789                                         ast_log(LOG_DEBUG, "Macro exited with status %d\n", res);
2790                                 res = 0;
2791                         } else {
2792                                 ast_log(LOG_ERROR, "Could not find application Macro\n");
2793                                 res = -1;
2794                         }
2795                 
2796                         if (ast_autoservice_stop(qe->chan) < 0) {
2797                                 ast_log(LOG_ERROR, "Could not stop autoservice on calling channel\n");
2798                                 res = -1;
2799                         }
2800                 }
2801
2802                 if (!ast_strlen_zero(agi)) {
2803                         if (option_debug)
2804                                 ast_log(LOG_DEBUG, "app_queue: agi=%s.\n", agi);
2805                         app = pbx_findapp("agi");
2806                         if (app) {
2807                                 agiexec = ast_strdupa(agi);
2808                                 ret = pbx_exec(qe->chan, app, agiexec);
2809                         } else
2810                                 ast_log(LOG_WARNING, "Asked to execute an AGI on this channel, but could not find application (agi)!\n");
2811                 }
2812                 ast_queue_log(queuename, qe->chan->uniqueid, member->membername, "CONNECT", "%ld|%s", (long) time(NULL) - qe->start, peer->uniqueid);
2813                 if (qe->parent->eventwhencalled)
2814                         manager_event(EVENT_FLAG_AGENT, "AgentConnect",
2815                                         "Queue: %s\r\n"
2816                                         "Uniqueid: %s\r\n"
2817                                         "Channel: %s\r\n"
2818                                         "Member: %s\r\n"
2819                                         "MemberName: %s\r\n"
2820                                         "Holdtime: %ld\r\n"
2821                                         "BridgedChannel: %s\r\n"
2822                                         "%s",
2823                                         queuename, qe->chan->uniqueid, peer->name, member->interface, member->membername,
2824                                         (long) time(NULL) - qe->start, peer->uniqueid,
2825                                         qe->parent->eventwhencalled == QUEUE_EVENT_VARIABLES ? vars2manager(qe->chan, vars, sizeof(vars)) : "");
2826                 ast_copy_string(oldcontext, qe->chan->context, sizeof(oldcontext));
2827                 ast_copy_string(oldexten, qe->chan->exten, sizeof(oldexten));
2828                 time(&callstart);
2829
2830                 bridge = ast_bridge_call(qe->chan,peer, &bridge_config);
2831
2832                 if (strcasecmp(oldcontext, qe->chan->context) || strcasecmp(oldexten, qe->chan->exten)) {
2833                         ast_queue_log(queuename, qe->chan->uniqueid, member->membername, "TRANSFER", "%s|%s|%ld|%ld",
2834                                 qe->chan->exten, qe->chan->context, (long) (callstart - qe->start),
2835                                 (long) (time(NULL) - callstart));
2836                         send_agent_complete(qe, queuename, peer, member, callstart, vars, sizeof(vars), TRANSFER);
2837                 } else if (qe->chan->_softhangup) {
2838                         ast_queue_log(queuename, qe->chan->uniqueid, member->membername, "COMPLETECALLER", "%ld|%ld|%d",
2839                                 (long) (callstart - qe->start), (long) (time(NULL) - callstart), qe->opos);
2840                         send_agent_complete(qe, queuename, peer, member, callstart, vars, sizeof(vars), CALLER);
2841                 } else {
2842                         ast_queue_log(queuename, qe->chan->uniqueid, member->membername, "COMPLETEAGENT", "%ld|%ld|%d",
2843                                 (long) (callstart - qe->start), (long) (time(NULL) - callstart), qe->opos);
2844                         send_agent_complete(qe, queuename, peer, member, callstart, vars, sizeof(vars), AGENT);
2845                 }
2846
2847                 if (bridge != AST_PBX_NO_HANGUP_PEER)
2848                         ast_hangup(peer);
2849                 update_queue(qe->parent, member);
2850                 res = bridge ? bridge : 1;
2851         }
2852 out:
2853         hangupcalls(outgoing, NULL);
2854
2855         return res;
2856 }
2857
2858 static int wait_a_bit(struct queue_ent *qe)
2859 {
2860         /* Don't need to hold the lock while we setup the outgoing calls */
2861         int retrywait = qe->parent->retry * 1000;
2862
2863         return ast_waitfordigit(qe->chan, retrywait);
2864 }
2865
2866 static struct member *interface_exists(struct call_queue *q, const char *interface)
2867 {
2868         struct member *mem;
2869
2870         if (!q)
2871                 return NULL;
2872
2873         for (mem = q->members; mem; mem = mem->next) {
2874                 if (!strcasecmp(interface, mem->interface))
2875                         return mem;
2876         }
2877
2878         return NULL;
2879 }
2880
2881
2882 /* Dump all members in a specific queue to the database
2883  *
2884  * <pm_family>/<queuename> = <interface>;<penalty>;<paused>[|...]
2885  *
2886  */
2887 static void dump_queue_members(struct call_queue *pm_queue)
2888 {
2889         struct member *cur_member;
2890         char value[PM_MAX_LEN];
2891         int value_len = 0;
2892         int res;
2893
2894         memset(value, 0, sizeof(value));
2895
2896         if (!pm_queue)
2897                 return;
2898
2899         for (cur_member = pm_queue->members; cur_member; cur_member = cur_member->next) {
2900                 if (!cur_member->dynamic)
2901                         continue;
2902
2903                 res = snprintf(value + value_len, sizeof(value) - value_len, "%s;%d;%d;%s%s",
2904                         cur_member->interface, cur_member->penalty, cur_member->paused, cur_member->membername,
2905                         cur_member->next ? "|" : "");
2906                 if (res != strlen(value + value_len)) {
2907                         ast_log(LOG_WARNING, "Could not create persistent member string, out of space\n");
2908                         break;
2909                 }
2910                 value_len += res;
2911         }
2912         
2913         if (value_len && !cur_member) {
2914                 if (ast_db_put(pm_family, pm_queue->name, value))
2915                         ast_log(LOG_WARNING, "failed to create persistent dynamic entry!\n");
2916         } else
2917                 /* Delete the entry if the queue is empty or there is an error */
2918                 ast_db_del(pm_family, pm_queue->name);
2919 }
2920
2921 static int remove_from_queue(const char *queuename, const char *interface)
2922 {
2923         struct call_queue *q;
2924         struct member *last_member, *look;
2925         int res = RES_NOSUCHQUEUE;
2926
2927         AST_LIST_LOCK(&queues);
2928         AST_LIST_TRAVERSE(&queues, q, list) {
2929                 ast_mutex_lock(&q->lock);
2930                 if (strcmp(q->name, queuename)) {
2931                         ast_mutex_unlock(&q->lock);
2932                         continue;
2933                 }
2934
2935                 if ((last_member = interface_exists(q, interface))) {
2936                         if ((look = q->members) == last_member) {
2937                                 q->members = last_member->next;
2938                         } else {
2939                                 while (look != NULL) {
2940                                         if (look->next == last_member) {
2941                                                 look->next = last_member->next;
2942                                                 break;
2943                                         } else {
2944                                                 look = look->next;
2945                                         }
2946                                 }
2947                         }
2948                         manager_event(EVENT_FLAG_AGENT, "QueueMemberRemoved",
2949                                 "Queue: %s\r\n"
2950                                 "Location: %s\r\n"
2951                                 "MemberName: %s\r\n",
2952                                 q->name, last_member->interface, last_member->membername);
2953                         ast_free(last_member);
2954                         
2955                         if (queue_persistent_members)
2956                                 dump_queue_members(q);
2957                         
2958                         res = RES_OKAY;
2959                 } else {
2960                         res = RES_EXISTS;
2961                 }
2962                 ast_mutex_unlock(&q->lock);
2963                 break;
2964         }
2965
2966         if (res == RES_OKAY)
2967                 remove_from_interfaces(interface);
2968
2969         AST_LIST_UNLOCK(&queues);
2970
2971         return res;
2972 }
2973
2974
2975 static int add_to_queue(const char *queuename, const char *interface, const char *membername, int penalty, int paused, int dump)
2976 {
2977         struct call_queue *q;
2978         struct member *new_member;
2979         int res = RES_NOSUCHQUEUE;
2980
2981         /* \note Ensure the appropriate realtime queue is loaded.  Note that this
2982          * short-circuits if the queue is already in memory. */
2983         if (!(q = load_realtime_queue(queuename)))
2984                 return res;
2985
2986         AST_LIST_LOCK(&queues);
2987
2988         ast_mutex_lock(&q->lock);
2989         if (interface_exists(q, interface) == NULL) {
2990                 add_to_interfaces(interface);
2991                 if ((new_member = create_queue_member(interface, membername, penalty, paused))) {
2992                         new_member->dynamic = 1;
2993                         new_member->next = q->members;
2994                         q->members = new_member;
2995                         manager_event(EVENT_FLAG_AGENT, "QueueMemberAdded",
2996                                 "Queue: %s\r\n"
2997                                 "Location: %s\r\n"
2998                                 "MemberName: %s\r\n"
2999                                 "Membership: %s\r\n"
3000                                 "Penalty: %d\r\n"
3001                                 "CallsTaken: %d\r\n"
3002                                 "LastCall: %d\r\n"
3003                                 "Status: %d\r\n"
3004                                 "Paused: %d\r\n",
3005                                 q->name, new_member->interface, new_member->membername,
3006                                 new_member->dynamic ? "dynamic" : "static",
3007                                 new_member->penalty, new_member->calls, (int) new_member->lastcall,
3008                                 new_member->status, new_member->paused);
3009                         
3010                         if (dump)
3011                                 dump_queue_members(q);
3012                         
3013                         res = RES_OKAY;
3014                 } else {
3015                         res = RES_OUTOFMEMORY;
3016                 }
3017         } else {
3018                 res = RES_EXISTS;
3019         }
3020         ast_mutex_unlock(&q->lock);
3021         AST_LIST_UNLOCK(&queues);
3022
3023         return res;
3024 }
3025
3026 static int set_member_paused(const char *queuename, const char *interface, int paused)
3027 {
3028         int found = 0;
3029         struct call_queue *q;
3030         struct member *mem;
3031
3032         /* Special event for when all queues are paused - individual events still generated */
3033         /* XXX In all other cases, we use the membername, but since this affects all queues, we cannot */
3034         if (ast_strlen_zero(queuename))
3035                 ast_queue_log("NONE", "NONE", interface, (paused ? "PAUSEALL" : "UNPAUSEALL"), "%s", "");
3036
3037         AST_LIST_LOCK(&queues);
3038         AST_LIST_TRAVERSE(&queues, q, list) {
3039                 ast_mutex_lock(&q->lock);
3040                 if (ast_strlen_zero(queuename) || !strcasecmp(q->name, queuename)) {
3041                         if ((mem = interface_exists(q, interface))) {
3042                                 found++;
3043                                 if (mem->paused == paused) {
3044                                         if (option_debug)
3045                                                 ast_log(LOG_DEBUG, "%spausing already-%spaused queue member %s:%s\n", (paused ? "" : "un"), (paused ? "" : "un"), q->name, interface);
3046                                 }
3047                                 mem->paused = paused;
3048
3049                                 if (queue_persistent_members)
3050                                         dump_queue_members(q);
3051
3052                                 ast_queue_log(q->name, "NONE", mem->membername, (paused ? "PAUSE" : "UNPAUSE"), "%s", "");
3053
3054                                 manager_event(EVENT_FLAG_AGENT, "QueueMemberPaused",
3055                                         "Queue: %s\r\n"
3056                                         "Location: %s\r\n"
3057                                         "MemberName: %s\r\n"
3058                                         "Paused: %d\r\n",
3059                                                 q->name, mem->interface, mem->membername, paused);
3060                         }
3061                 }
3062                 ast_mutex_unlock(&q->lock);
3063         }
3064         AST_LIST_UNLOCK(&queues);
3065
3066         return found ? RESULT_SUCCESS : RESULT_FAILURE;
3067 }
3068
3069 /* Reload dynamic queue members persisted into the astdb */
3070 static void reload_queue_members(void)
3071 {
3072         char *cur_ptr;  
3073         char *queue_name;
3074         char *member;
3075         char *interface;
3076         char *membername;
3077         char *penalty_tok;
3078         int penalty = 0;
3079         char *paused_tok;
3080         int paused = 0;
3081         struct ast_db_entry *db_tree;
3082         struct ast_db_entry *entry;
3083         struct call_queue *cur_queue;
3084         char queue_data[PM_MAX_LEN];
3085
3086         AST_LIST_LOCK(&queues);
3087
3088         /* Each key in 'pm_family' is the name of a queue */
3089         db_tree = ast_db_gettree(pm_family, NULL);
3090         for (entry = db_tree; entry; entry = entry->next) {
3091
3092                 queue_name = entry->key + strlen(pm_family) + 2;
3093
3094                 AST_LIST_TRAVERSE(&queues, cur_queue, list) {
3095                         ast_mutex_lock(&cur_queue->lock);
3096                         if (!strcmp(queue_name, cur_queue->name))
3097                                 break;
3098                         ast_mutex_unlock(&cur_queue->lock);
3099                 }
3100                 
3101                 if (!cur_queue)
3102                         cur_queue = load_realtime_queue(queue_name);
3103
3104                 if (!cur_queue) {
3105                         /* If the queue no longer exists, remove it from the
3106                          * database */
3107                         ast_log(LOG_WARNING, "Error loading persistent queue: '%s': it does not exist\n", queue_name);
3108                         ast_db_del(pm_family, queue_name);
3109                         continue;
3110                 } else
3111                         ast_mutex_unlock(&cur_queue->lock);
3112
3113                 if (ast_db_get(pm_family, queue_name, queue_data, PM_MAX_LEN))
3114                         continue;
3115
3116                 cur_ptr = queue_data;
3117                 while ((member = strsep(&cur_ptr, "|"))) {
3118                         if (ast_strlen_zero(member))
3119                                 continue;
3120
3121                         interface = strsep(&member, ";");
3122                         penalty_tok = strsep(&member, ";");
3123                         paused_tok = strsep(&member, ";");
3124                         membername = strsep(&member, ";");
3125
3126                         if (!penalty_tok) {
3127                                 ast_log(LOG_WARNING, "Error parsing persistent member string for '%s' (penalty)\n", queue_name);
3128                                 break;
3129                         }
3130                         penalty = strtol(penalty_tok, NULL, 10);
3131                         if (errno == ERANGE) {
3132                                 ast_log(LOG_WARNING, "Error converting penalty: %s: Out of range.\n", penalty_tok);
3133                                 break;
3134                         }
3135                         
3136                         if (!paused_tok) {
3137                                 ast_log(LOG_WARNING, "Error parsing persistent member string for '%s' (paused)\n", queue_name);
3138                                 break;
3139                         }
3140                         paused = strtol(paused_tok, NULL, 10);
3141                         if ((errno == ERANGE) || paused < 0 || paused > 1) {
3142                                 ast_log(LOG_WARNING, "Error converting paused: %s: Expected 0 or 1.\n", paused_tok);
3143                                 break;
3144                         }
3145                         if (ast_strlen_zero(membername))
3146                                 membername = interface;
3147
3148                         if (option_debug)
3149                                 ast_log(LOG_DEBUG, "Reload Members: Queue: %s  Member: %s  Name: %s  Penalty: %d  Paused: %d\n", queue_name, interface, membername, penalty, paused);
3150                         
3151                         if (add_to_queue(queue_name, interface, membername, penalty, paused, 0) == RES_OUTOFMEMORY) {
3152                                 ast_log(LOG_ERROR, "Out of Memory when reloading persistent queue member\n");
3153                                 break;
3154                         }
3155                 }
3156         }
3157
3158         AST_LIST_UNLOCK(&queues);
3159         if (db_tree) {
3160                 ast_log(LOG_NOTICE, "Queue members successfully reloaded from database.\n");
3161                 ast_db_freetree(db_tree);
3162         }
3163 }
3164
3165 static int pqm_exec(struct ast_channel *chan, void *data)
3166 {
3167         struct ast_module_user *lu;
3168         char *parse;
3169         AST_DECLARE_APP_ARGS(args,
3170                 AST_APP_ARG(queuename);
3171                 AST_APP_ARG(interface);
3172                 AST_APP_ARG(options);
3173         );
3174
3175         if (ast_strlen_zero(data)) {
3176                 ast_log(LOG_WARNING, "PauseQueueMember requires an argument ([queuename]|interface[|options])\n");
3177                 return -1;
3178         }
3179
3180         parse = ast_strdupa(data);
3181
3182         AST_STANDARD_APP_ARGS(args, parse);
3183
3184         lu = ast_module_user_add(chan);
3185
3186         if (args.options) {
3187         }
3188
3189         if (ast_strlen_zero(args.interface)) {
3190                 ast_log(LOG_WARNING, "Missing interface argument to PauseQueueMember ([queuename]|interface[|options])\n");
3191                 ast_module_user_remove(lu);
3192                 return -1;
3193         }
3194
3195         if (set_member_paused(args.queuename, args.interface, 1)) {
3196                 ast_log(LOG_WARNING, "Attempt to pause interface %s, not found\n", args.interface);
3197                 ast_module_user_remove(lu);
3198                 pbx_builtin_setvar_helper(chan, "PQMSTATUS", "NOTFOUND");
3199                 return -1;
3200         }
3201
3202         ast_module_user_remove(lu);
3203         pbx_builtin_setvar_helper(chan, "PQMSTATUS", "PAUSED");
3204
3205         return 0;
3206 }
3207
3208 static int upqm_exec(struct ast_channel *chan, void *data)
3209 {
3210         struct ast_module_user *lu;
3211         char *parse;
3212         AST_DECLARE_APP_ARGS(args,
3213                 AST_APP_ARG(queuename);
3214                 AST_APP_ARG(interface);
3215                 AST_APP_ARG(options);
3216         );
3217
3218         if (ast_strlen_zero(data)) {
3219                 ast_log(LOG_WARNING, "UnpauseQueueMember requires an argument ([queuename]|interface[|options])\n");
3220                 return -1;
3221         }
3222
3223         parse = ast_strdupa(data);
3224
3225         AST_STANDARD_APP_ARGS(args, parse);
3226
3227         lu = ast_module_user_add(chan);
3228
3229         if (args.options) {
3230         }
3231
3232         if (ast_strlen_zero(args.interface)) {
3233                 ast_log(LOG_WARNING, "Missing interface argument to PauseQueueMember ([queuename]|interface[|options])\n");
3234                 ast_module_user_remove(lu);
3235                 return -1;
3236         }
3237
3238         if (set_member_paused(args.queuename, args.interface, 0)) {
3239                 ast_log(LOG_WARNING, "Attempt to unpause interface %s, not found\n", args.interface);
3240                 ast_module_user_remove(lu);
3241                 pbx_builtin_setvar_helper(chan, "UPQMSTATUS", "NOTFOUND");
3242                 return -1;
3243         }
3244
3245         ast_module_user_remove(lu);
3246         pbx_builtin_setvar_helper(chan, "UPQMSTATUS", "UNPAUSED");
3247
3248         return 0;
3249 }
3250
3251 static int rqm_exec(struct ast_channel *chan, void *data)
3252 {
3253         int res=-1;
3254         struct ast_module_user *lu;
3255         char *parse, *temppos = NULL;
3256         AST_DECLARE_APP_ARGS(args,
3257                 AST_APP_ARG(queuename);
3258                 AST_APP_ARG(interface);
3259                 AST_APP_ARG(options);
3260         );
3261
3262
3263         if (ast_strlen_zero(data)) {
3264                 ast_log(LOG_WARNING, "RemoveQueueMember requires an argument (queuename[|interface[|options]])\n");
3265                 return -1;
3266         }
3267
3268         parse = ast_strdupa(data);
3269
3270         AST_STANDARD_APP_ARGS(args, parse);
3271
3272         lu = ast_module_user_add(chan);
3273
3274         if (ast_strlen_zero(args.interface)) {
3275                 args.interface = ast_strdupa(chan->name);
3276                 temppos = strrchr(args.interface, '-');
3277                 if (temppos)
3278                         *temppos = '\0';
3279         }
3280
3281         if (args.options) {
3282         }
3283
3284         switch (remove_from_queue(args.queuename, args.interface)) {
3285         case RES_OKAY:
3286                 ast_queue_log(args.queuename, chan->uniqueid, args.interface, "REMOVEMEMBER", "%s", "");
3287                 ast_log(LOG_NOTICE, "Removed interface '%s' from queue '%s'\n", args.interface, args.queuename);
3288                 pbx_builtin_setvar_helper(chan, "RQMSTATUS", "REMOVED");
3289                 res = 0;
3290                 break;
3291         case RES_EXISTS:
3292                 if (option_debug)
3293                         ast_log(LOG_DEBUG, "Unable to remove interface '%s' from queue '%s': Not there\n", args.interface, args.queuename);
3294                 pbx_builtin_setvar_helper(chan, "RQMSTATUS", "NOTINQUEUE");
3295                 res = 0;
3296                 break;
3297         case RES_NOSUCHQUEUE:
3298                 ast_log(LOG_WARNING, "Unable to remove interface from queue '%s': No such queue\n", args.queuename);
3299                 pbx_builtin_setvar_helper(chan, "RQMSTATUS", "NOSUCHQUEUE");
3300                 res = 0;
3301                 break;
3302         }
3303
3304         ast_module_user_remove(lu);
3305
3306         return res;
3307 }
3308
3309 static int aqm_exec(struct ast_channel *chan, void *data)
3310 {
3311         int res=-1;
3312         struct ast_module_user *lu;
3313         char *parse, *temppos = NULL;
3314         AST_DECLARE_APP_ARGS(args,
3315                 AST_APP_ARG(queuename);
3316                 AST_APP_ARG(interface);
3317                 AST_APP_ARG(penalty);
3318                 AST_APP_ARG(options);
3319                 AST_APP_ARG(membername);
3320         );
3321         int penalty = 0;
3322
3323         if (ast_strlen_zero(data)) {
3324                 ast_log(LOG_WARNING, "AddQueueMember requires an argument (queuename[|[interface]|[penalty][|options][|membername]])\n");
3325                 return -1;
3326         }
3327
3328         parse = ast_strdupa(data);
3329
3330         AST_STANDARD_APP_ARGS(args, parse);
3331
3332         lu = ast_module_user_add(chan);
3333
3334         if (ast_strlen_zero(args.interface)) {
3335                 args.interface = ast_strdupa(chan->name);
3336                 temppos = strrchr(args.interface, '-');
3337                 if (temppos)
3338                         *temppos = '\0';
3339         }
3340
3341         if (!ast_strlen_zero(args.penalty)) {
3342                 if ((sscanf(args.penalty, "%d", &penalty) != 1) || penalty < 0) {
3343                         ast_log(LOG_WARNING, "Penalty '%s' is invalid, must be an integer >= 0\n", args.penalty);
3344                         penalty = 0;
3345                 }
3346         }
3347         
3348         if (args.options) {
3349         }
3350
3351         if (ast_strlen_zero(args.membername))
3352                 args.membername = args.interface;
3353
3354