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