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