265c82dcd49e9992d81f47f037bf4201f9266cc6
[asterisk/asterisk.git] / apps / app_queue.c
1 /*
2  * Asterisk -- A telephony toolkit for Linux.
3  *
4  * True call queues with optional send URL on answer
5  * 
6  * Copyright (C) 1999, Mark Spencer
7  *
8  * Mark Spencer <markster@linux-support.net>
9  *
10  * This program is free software, distributed under the terms of
11  * the GNU General Public License
12  */
13
14 #include <asterisk/lock.h>
15 #include <asterisk/file.h>
16 #include <asterisk/logger.h>
17 #include <asterisk/channel.h>
18 #include <asterisk/pbx.h>
19 #include <asterisk/options.h>
20 #include <asterisk/module.h>
21 #include <asterisk/translate.h>
22 #include <asterisk/say.h>
23 #include <asterisk/parking.h>
24 #include <asterisk/musiconhold.h>
25 #include <asterisk/cli.h>
26 #include <asterisk/manager.h> /* JDG */
27 #include <asterisk/config.h>
28 #include <stdlib.h>
29 #include <errno.h>
30 #include <unistd.h>
31 #include <string.h>
32 #include <stdlib.h>
33 #include <stdio.h>
34 #include <sys/time.h>
35 #include <sys/signal.h>
36 #include <netinet/in.h>
37
38 #include <pthread.h>
39
40 #define QUEUE_STRATEGY_RINGALL          0
41 #define QUEUE_STRATEGY_ROUNDROBIN       1
42 #define QUEUE_STRATEGY_LEASTRECENT      2
43 #define QUEUE_STRATEGY_FEWESTCALLS      3
44 #define QUEUE_STRATEGY_RANDOM           4
45
46 static struct strategy {
47         int strategy;
48         char *name;
49 } strategies[] = {
50         { QUEUE_STRATEGY_RINGALL, "ringall" },
51         { QUEUE_STRATEGY_ROUNDROBIN, "roundrobin" },
52         { QUEUE_STRATEGY_LEASTRECENT, "leastrecent" },
53         { QUEUE_STRATEGY_FEWESTCALLS, "fewestcalls" },
54         { QUEUE_STRATEGY_RANDOM, "random" },
55 };
56
57 #define DEFAULT_RETRY           5
58 #define DEFAULT_TIMEOUT         15
59 #define RECHECK                         1               /* Recheck every second to see we we're at the top yet */
60
61 static char *tdesc = "True Call Queueing";
62
63 static char *app = "Queue";
64
65 static char *synopsis = "Queue a call for a call queue";
66
67 static char *descrip =
68 "  Queue(queuename[|options[|URL][|announceoverride]]):\n"
69 "Queues an incoming call in a particular call queue as defined in queues.conf.\n"
70 "  This application returns -1 if the originating channel hangs up, or if the\n"
71 "call is bridged and  either of the parties in the bridge terminate the call.\n"
72 "Returns 0 if the queue is full, nonexistant, or has no members.\n"
73 "The option string may contain zero or more of the following characters:\n"
74 "      't' -- allow the called user transfer the calling user\n"
75 "      'T' -- to allow the calling user to transfer the call.\n"
76 "      'd' -- data-quality (modem) call (minimum delay).\n"
77 "      'H' -- allow caller to hang up by hitting *.\n"
78 "  In addition to transferring the call, a call may be parked and then picked\n"
79 "up by another user.\n"
80 "  The optionnal URL will be sent to the called party if the channel supports\n"
81 "it.\n";
82
83 // [PHM 06/26/03]
84 static char *app_aqm = "AddQueueMember" ;
85 static char *app_aqm_synopsis = "Dynamically adds queue members" ;
86 static char *app_aqm_descrip =
87 "   AddQueueMember(queuename[|interface]):\n"
88 "Dynamically adds interface to an existing queue\n"
89 "Returns -1 if there is an error.\n"
90 "Example: AddQueueMember(techsupport|SIP/3000)\n"
91 "";
92
93 static char *app_rqm = "RemoveQueueMember" ;
94 static char *app_rqm_synopsis = "Dynamically removes queue members" ;
95 static char *app_rqm_descrip =
96 "   RemoveQueueMember(queuename[|interface]):\n"
97 "Dynamically removes interface to an existing queue\n"
98 "Returns -1 if there is an error.\n"
99 "Example: RemoveQueueMember(techsupport|SIP/3000)\n"
100 "";
101
102
103
104
105 /* We define a customer "local user" structure because we
106    use it not only for keeping track of what is in use but
107    also for keeping track of who we're dialing. */
108
109 struct localuser {
110         struct ast_channel *chan;
111         char numsubst[256];
112         char tech[40];
113         int stillgoing;
114         int metric;
115         int allowredirect_in;
116         int allowredirect_out;
117         int ringbackonly;
118         int musiconhold;
119         int dataquality;
120         int allowdisconnect;
121         struct member *member;
122         struct localuser *next;
123 };
124
125 LOCAL_USER_DECL;
126
127 struct queue_ent {
128         struct ast_call_queue *parent;  /* What queue is our parent */
129         char moh[80];                           /* Name of musiconhold to be used */
130         char announce[80];              /* Announcement to play */
131         char context[80];               /* Context when user exits queue */
132         int pos;                                        /* Where we are in the queue */
133         time_t start;                           /* When we started holding */
134         struct ast_channel *chan;       /* Our channel */
135         struct queue_ent *next;         /* The next queue entry */
136 };
137
138 struct member {
139         char tech[80];                          /* Technology */
140         char loc[256];                          /* Location */
141         int penalty;                            /* Are we a last resort? */
142         int calls;
143         int dynamic;                            /* Are we dynamically added? */
144         time_t lastcall;        /* When last successful call was hungup */
145         struct member *next;            /* Next member */
146 };
147
148 struct ast_call_queue {
149         ast_mutex_t     lock;   
150         char name[80];                  /* Name of the queue */
151         char moh[80];                   /* Name of musiconhold to be used */
152         char announce[80];              /* Announcement to play */
153         char context[80];               /* Announcement to play */
154         int strategy;                   /* Queueing strategy */
155         int announcetimeout;    /* How often to announce their position */
156         int count;                              /* How many entries are in the queue */
157         int maxlen;                             /* Max number of entries in queue */
158
159         int dead;                               /* Whether this queue is dead or not */
160         int retry;                              /* Retry calling everyone after this amount of time */
161         int timeout;                    /* How long to wait for an answer */
162         
163         /* Queue strategy things */
164         
165         int rrpos;                              /* Round Robin - position */
166         int wrapped;                    /* Round Robin - wrapped around? */
167
168         struct member *members; /* Member channels to be tried */
169         struct queue_ent *head; /* Start of the actual queue */
170         struct ast_call_queue *next;    /* Next call queue */
171 };
172
173 static struct ast_call_queue *queues = NULL;
174 static ast_mutex_t qlock = AST_MUTEX_INITIALIZER;
175
176 static char *int2strat(int strategy)
177 {
178         int x;
179         for (x=0;x<sizeof(strategies) / sizeof(strategies[0]);x++) {
180                 if (strategy == strategies[x].strategy)
181                         return strategies[x].name;
182         }
183         return "<unknown>";
184 }
185
186 static int strat2int(char *strategy)
187 {
188         int x;
189         for (x=0;x<sizeof(strategies) / sizeof(strategies[0]);x++) {
190                 if (!strcasecmp(strategy, strategies[x].name))
191                         return strategies[x].strategy;
192         }
193         return -1;
194 }
195
196 static int join_queue(char *queuename, struct queue_ent *qe)
197 {
198         struct ast_call_queue *q;
199         struct queue_ent *cur, *prev = NULL;
200         int res = -1;
201         int pos = 0;
202         ast_mutex_lock(&qlock);
203         q = queues;
204         while(q) {
205                 if (!strcasecmp(q->name, queuename)) {
206                         /* This is our one */
207                         ast_mutex_lock(&q->lock);
208                         if (q->members && (!q->maxlen || (q->count < q->maxlen))) {
209                                 /* There's space for us, put us at the end */
210                                 prev = NULL;
211                                 cur = q->head;
212                                 while(cur) {
213                                         cur->pos = ++pos;
214                                         prev = cur;
215                                         cur = cur->next;
216                                 }
217                                 if (prev)
218                                         prev->next = qe;
219                                 else
220                                         q->head = qe;
221                                 /* Fix additional pointers and
222                                   information  */
223                                 qe->next = NULL;
224                                 qe->parent = q;
225                                 qe->pos = ++pos;
226                                 strncpy(qe->moh, q->moh, sizeof(qe->moh));
227                                 strncpy(qe->announce, q->announce, sizeof(qe->announce));
228                                 strncpy(qe->context, q->context, sizeof(qe->context));
229                                 q->count++;
230                                 res = 0;
231                                 manager_event(EVENT_FLAG_CALL, "Join", 
232                                                                 "Channel: %s\r\nCallerID: %s\r\nQueue: %s\r\nPosition: %d\r\nCount: %d\r\n",
233                                                                 qe->chan->name, (qe->chan->callerid ? qe->chan->callerid : "unknown"), q->name, qe->pos, q->count );
234 #if 0
235 ast_log(LOG_NOTICE, "Queue '%s' Join, Channel '%s', Position '%d'\n", q->name, qe->chan->name, qe->pos );
236 #endif
237                         }
238                         ast_mutex_unlock(&q->lock);
239                         break;
240                 }
241                 q = q->next;
242         }
243         ast_mutex_unlock(&qlock);
244         return res;
245 }
246
247 static void free_members(struct ast_call_queue *q, int all)
248 {
249         /* Free non-dynamic members */
250         struct member *curm, *next, *prev;
251         curm = q->members;
252         prev = NULL;
253         while(curm) {
254                 next = curm->next;
255                 if (all || !curm->dynamic) {
256                         if (prev)
257                                 prev->next = next;
258                         else
259                                 q->members = next;
260                         free(curm);
261                 } else 
262                         prev = curm;
263                 curm = next;
264         }
265 }
266
267 static void destroy_queue(struct ast_call_queue *q)
268 {
269         struct ast_call_queue *cur, *prev = NULL;
270         ast_mutex_lock(&qlock);
271         cur = queues;
272         while(cur) {
273                 if (cur == q) {
274                         if (prev)
275                                 prev->next = cur->next;
276                         else
277                                 queues = cur->next;
278                 } else {
279                         prev = cur;
280                 }
281                 cur = cur->next;
282         }
283         ast_mutex_unlock(&qlock);
284         free_members(q, 1);
285         free(q);
286 }
287
288 static void leave_queue(struct queue_ent *qe)
289 {
290         struct ast_call_queue *q;
291         struct queue_ent *cur, *prev = NULL;
292         int pos = 0;
293         q = qe->parent;
294         if (!q)
295                 return;
296         ast_mutex_lock(&q->lock);
297
298         prev = NULL;
299         cur = q->head;
300         while(cur) {
301                 if (cur == qe) {
302                         q->count--;
303
304                         /* Take us out of the queue */
305                         manager_event(EVENT_FLAG_CALL, "Leave",
306                                  "Channel: %s\r\nQueue: %s\r\nCount: %d\r\n",
307                                  qe->chan->name, q->name,  q->count);
308 #if 0
309 ast_log(LOG_NOTICE, "Queue '%s' Leave, Channel '%s'\n", q->name, qe->chan->name );
310 #endif
311                         /* Take us out of the queue */
312                         if (prev)
313                                 prev->next = cur->next;
314                         else
315                                 q->head = cur->next;
316                 } else {
317                         cur->pos = ++pos;
318                         prev = cur;
319                 }
320                 cur = cur->next;
321         }
322         ast_mutex_unlock(&q->lock);
323         if (q->dead && !q->count) {     
324                 /* It's dead and nobody is in it, so kill it */
325                 destroy_queue(q);
326         }
327 }
328
329 static void hanguptree(struct localuser *outgoing, struct ast_channel *exception)
330 {
331         /* Hang up a tree of stuff */
332         struct localuser *oo;
333         while(outgoing) {
334                 /* Hangup any existing lines we have open */
335                 if (outgoing->chan && (outgoing->chan != exception))
336                         ast_hangup(outgoing->chan);
337                 oo = outgoing;
338                 outgoing=outgoing->next;
339                 free(oo);
340         }
341 }
342
343 static int ring_entry(struct queue_ent *qe, struct localuser *tmp)
344 {
345         int res;
346         /* Request the peer */
347         tmp->chan = ast_request(tmp->tech, qe->chan->nativeformats, tmp->numsubst);
348         if (!tmp->chan) {                       /* If we can't, just go on to the next call */
349 #if 0
350                 ast_log(LOG_NOTICE, "Unable to create channel of type '%s'\n", cur->tech);
351 #endif                  
352                 if (qe->chan->cdr)
353                         ast_cdr_busy(qe->chan->cdr);
354                 tmp->stillgoing = 0;
355                 return 0;
356         }
357         tmp->chan->appl = "AppQueue";
358         tmp->chan->data = "(Outgoing Line)";
359         tmp->chan->whentohangup = 0;
360         if (tmp->chan->callerid)
361                 free(tmp->chan->callerid);
362         if (tmp->chan->ani)
363                 free(tmp->chan->ani);
364         if (qe->chan->callerid)
365                 tmp->chan->callerid = strdup(qe->chan->callerid);
366         else
367                 tmp->chan->callerid = NULL;
368         if (qe->chan->ani)
369                 tmp->chan->ani = strdup(qe->chan->ani);
370         else
371                 tmp->chan->ani = NULL;
372         /* Presense of ADSI CPE on outgoing channel follows ours */
373         tmp->chan->adsicpe = qe->chan->adsicpe;
374         /* Place the call, but don't wait on the answer */
375         res = ast_call(tmp->chan, tmp->numsubst, 0);
376         if (res) {
377                 /* Again, keep going even if there's an error */
378                 if (option_debug)
379                         ast_log(LOG_DEBUG, "ast call on peer returned %d\n", res);
380                 else if (option_verbose > 2)
381                         ast_verbose(VERBOSE_PREFIX_3 "Couldn't call %s\n", tmp->numsubst);
382                 ast_hangup(tmp->chan);
383                 tmp->chan = NULL;
384                 tmp->stillgoing = 0;
385                 return 0;
386         } else
387                 if (option_verbose > 2)
388                         ast_verbose(VERBOSE_PREFIX_3 "Called %s\n", tmp->numsubst);
389         return 0;
390 }
391
392 static int ring_one(struct queue_ent *qe, struct localuser *outgoing)
393 {
394         struct localuser *cur;
395         struct localuser *best;
396         int bestmetric=0;
397         do {
398                 best = NULL;
399                 cur = outgoing;
400                 while(cur) {
401                         if (cur->stillgoing &&                                                  /* Not already done */
402                                 !cur->chan &&                                                           /* Isn't already going */
403                                 (!best || (cur->metric < bestmetric))) {        /* We haven't found one yet, or it's better */
404                                         bestmetric = cur->metric;
405                                         best = cur;
406                         }
407                         cur = cur->next;
408                 }
409                 if (best) {
410                         if (!qe->parent->strategy) {
411                                 /* Ring everyone who shares this best metric (for ringall) */
412                                 cur = outgoing;
413                                 while(cur) {
414                                         if (cur->stillgoing && !cur->chan && (cur->metric == bestmetric)) {
415                                                 ast_log(LOG_DEBUG, "(Parallel) Trying '%s/%s' with metric %d\n", cur->tech, cur->numsubst, cur->metric);
416                                                 ring_entry(qe, cur);
417                                         }
418                                         cur = cur->next;
419                                 }
420                         } else {
421                                 /* Ring just the best channel */
422                                 ast_log(LOG_DEBUG, "Trying '%s/%s' with metric %d\n", best->tech, best->numsubst, best->metric);
423                                 ring_entry(qe, best);
424                         }
425                 }
426         } while (best && !best->chan);
427         if (!best) {
428                 ast_log(LOG_DEBUG, "Nobody left to try ringing in queue\n");
429                 return 0;
430         }
431         return 1;
432 }
433
434 static int valid_exit(struct queue_ent *qe, char digit)
435 {
436         char tmp[2];
437         if (!strlen(qe->context))
438                 return 0;
439         tmp[0] = digit;
440         tmp[1] = '\0';
441         if (ast_exists_extension(qe->chan, qe->context, tmp, 1, qe->chan->callerid)) {
442                 strncpy(qe->chan->context, qe->context, sizeof(qe->chan->context) - 1);
443                 strncpy(qe->chan->exten, tmp, sizeof(qe->chan->exten) - 1);
444                 qe->chan->priority = 0;
445                 return 1;
446         }
447         return 0;
448 }
449
450 #define MAX 256
451
452 static struct localuser *wait_for_answer(struct queue_ent *qe, struct localuser *outgoing, int *to, int *allowredir_in, int *allowredir_out, int *allowdisconnect, char *digit)
453 {
454         char *queue = qe->parent->name;
455         struct localuser *o;
456         int found;
457         int numlines;
458         int sentringing = 0;
459         int numbusies = 0;
460         int orig = *to;
461         struct ast_frame *f;
462         struct localuser *peer = NULL;
463         struct ast_channel *watchers[MAX];
464         int pos;
465         struct ast_channel *winner;
466         struct ast_channel *in = qe->chan;
467         
468         while(*to && !peer) {
469                 o = outgoing;
470                 found = -1;
471                 pos = 1;
472                 numlines = 0;
473                 watchers[0] = in;
474                 while(o) {
475                         /* Keep track of important channels */
476                         if (o->stillgoing && o->chan) {
477                                 watchers[pos++] = o->chan;
478                                 found = 1;
479                         }
480                         o = o->next;
481                         numlines++;
482                 }
483                 if (found < 0) {
484                         if (numlines == numbusies) {
485                                 ast_log(LOG_DEBUG, "Everyone is busy at this time\n");
486                         } else {
487                                 ast_log(LOG_NOTICE, "No one is answered queue %s\n", queue);
488                         }
489                         *to = 0;
490                         return NULL;
491                 }
492                 winner = ast_waitfor_n(watchers, pos, to);
493                 o = outgoing;
494                 while(o) {
495                         if (o->stillgoing && (o->chan) &&  (o->chan->_state == AST_STATE_UP)) {
496                                 if (!peer) {
497                                         if (option_verbose > 2)
498                                                 ast_verbose( VERBOSE_PREFIX_3 "%s answered %s\n", o->chan->name, in->name);
499                                         peer = o;
500                                         *allowredir_in = o->allowredirect_in;
501                                         *allowredir_out = o->allowredirect_out;
502                                         *allowdisconnect = o->allowdisconnect;
503                                 }
504                         } else if (o->chan && (o->chan == winner)) {
505                                 f = ast_read(winner);
506                                 if (f) {
507                                         if (f->frametype == AST_FRAME_CONTROL) {
508                                                 switch(f->subclass) {
509                                             case AST_CONTROL_ANSWER:
510                                                         /* This is our guy if someone answered. */
511                                                         if (!peer) {
512                                                                 if (option_verbose > 2)
513                                                                         ast_verbose( VERBOSE_PREFIX_3 "%s answered %s\n", o->chan->name, in->name);
514                                                                 peer = o;
515                                                                 *allowredir_in = o->allowredirect_in;
516                                                                 *allowredir_out = o->allowredirect_out;
517                                                                 *allowdisconnect = o->allowdisconnect;
518                                                         }
519                                                         break;
520                                                 case AST_CONTROL_BUSY:
521                                                         if (option_verbose > 2)
522                                                                 ast_verbose( VERBOSE_PREFIX_3 "%s is busy\n", o->chan->name);
523                                                         o->stillgoing = 0;
524                                                         if (in->cdr)
525                                                                 ast_cdr_busy(in->cdr);
526                                                         ast_hangup(o->chan);
527                                                         o->chan = NULL;
528                                                         if (qe->parent->strategy)
529                                                                 ring_one(qe, outgoing);
530                                                         numbusies++;
531                                                         break;
532                                                 case AST_CONTROL_CONGESTION:
533                                                         if (option_verbose > 2)
534                                                                 ast_verbose( VERBOSE_PREFIX_3 "%s is circuit-busy\n", o->chan->name);
535                                                         o->stillgoing = 0;
536                                                         if (in->cdr)
537                                                                 ast_cdr_busy(in->cdr);
538                                                         ast_hangup(o->chan);
539                                                         o->chan = NULL;
540                                                         if (qe->parent->strategy)
541                                                                 ring_one(qe, outgoing);
542                                                         numbusies++;
543                                                         break;
544                                                 case AST_CONTROL_RINGING:
545                                                         if (option_verbose > 2)
546                                                                 ast_verbose( VERBOSE_PREFIX_3 "%s is ringing\n", o->chan->name);
547                                                         if (!sentringing) {
548 #if 0
549                                                                 ast_indicate(in, AST_CONTROL_RINGING);
550 #endif                                                          
551                                                                 sentringing++;
552                                                         }
553                                                         break;
554                                                 case AST_CONTROL_OFFHOOK:
555                                                         /* Ignore going off hook */
556                                                         break;
557                                                 default:
558                                                         ast_log(LOG_DEBUG, "Dunno what to do with control type %d\n", f->subclass);
559                                                 }
560                                         }
561                                         ast_frfree(f);
562                                 } else {
563                                         o->stillgoing = 0;
564                                         ast_hangup(o->chan);
565                                         o->chan = NULL;
566                                         if (qe->parent->strategy)
567                                                 ring_one(qe, outgoing);
568                                 }
569                         }
570                         o = o->next;
571                 }
572                 if (winner == in) {
573                         f = ast_read(in);
574 #if 0
575                         if (f && (f->frametype != AST_FRAME_VOICE))
576                                         printf("Frame type: %d, %d\n", f->frametype, f->subclass);
577                         else if (!f || (f->frametype != AST_FRAME_VOICE))
578                                 printf("Hangup received on %s\n", in->name);
579 #endif
580                         if (!f || ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_HANGUP))) {
581                                 /* Got hung up */
582                                 *to=-1;
583                                 return NULL;
584                         }
585                         if (f && (f->frametype == AST_FRAME_DTMF) && allowdisconnect && (f->subclass == '*')) {
586                             if (option_verbose > 3)
587                                 ast_verbose(VERBOSE_PREFIX_3 "User hit %c to disconnect call.\n", f->subclass);
588                                 *to=0;
589                                 return NULL;
590                         }
591                         if (f && (f->frametype == AST_FRAME_DTMF) && (f->subclass != '*') && valid_exit(qe, f->subclass)) {
592                                 if (option_verbose > 3)
593                                         ast_verbose(VERBOSE_PREFIX_3 "User pressed digit: %c", f->subclass);
594                                 *to=0;
595                                 *digit=f->subclass;
596                                 return NULL;
597                         }
598                 }
599                 if (!*to && (option_verbose > 2))
600                         ast_verbose( VERBOSE_PREFIX_3 "Nobody picked up in %d ms\n", orig);
601         }
602
603         return peer;
604         
605 }
606
607 static int wait_our_turn(struct queue_ent *qe)
608 {
609         struct queue_ent *ch;
610         int res = 0;
611         for (;;) {
612                 /* Atomically read the parent head */
613                 ast_mutex_lock(&qe->parent->lock);
614                 ch = qe->parent->head;
615                 ast_mutex_unlock(&qe->parent->lock);
616                 /* If we are now at the top of the head, break out */
617                 if (qe->parent->head == qe)
618                         break;
619                 /* Wait a second before checking again */
620                 res = ast_waitfordigit(qe->chan, RECHECK * 1000);
621                 if (res)
622                         break;
623         }
624         return res;
625 }
626
627 static int update_queue(struct ast_call_queue *q, struct localuser *user)
628 {
629         struct member *cur;
630         /* Since a reload could have taken place, we have to traverse the list to
631                 be sure it's still valid */
632         ast_mutex_lock(&q->lock);
633         cur = q->members;
634         while(cur) {
635                 if (user->member == cur) {
636                         time(&cur->lastcall);
637                         cur->calls++;
638                         break;
639                 }
640                 cur = cur->next;
641         }
642         ast_mutex_unlock(&q->lock);
643         return 0;
644 }
645
646 static int calc_metric(struct ast_call_queue *q, struct member *mem, int pos, struct queue_ent *qe, struct localuser *tmp)
647 {
648         switch (q->strategy) {
649         case QUEUE_STRATEGY_RINGALL:
650                 /* Everyone equal, except for penalty */
651                 tmp->metric = mem->penalty * 1000000;
652                 break;
653         case QUEUE_STRATEGY_ROUNDROBIN:
654                 if (!pos) {
655                         if (!q->wrapped) {
656                                 /* No more channels, start over */
657                                 q->rrpos = 0;
658                         } else {
659                                 /* Prioritize next entry */
660                                 q->rrpos++;
661                         }
662                         q->wrapped = 0;
663                 }
664                 if (pos < q->rrpos) {
665                         tmp->metric = 1000 + pos;
666                 } else {
667                         if (pos > q->rrpos) {
668                                 /* Indicate there is another priority */
669                                 q->wrapped = 1;
670                         }
671                         tmp->metric = pos;
672                 }
673                 tmp->metric += mem->penalty * 1000000;
674                 break;
675         case QUEUE_STRATEGY_RANDOM:
676                 tmp->metric = rand() % 1000;
677                 tmp->metric += mem->penalty * 1000000;
678                 break;
679         case QUEUE_STRATEGY_FEWESTCALLS:
680                 tmp->metric = mem->calls;
681                 tmp->metric += mem->penalty * 1000000;
682                 break;
683         case QUEUE_STRATEGY_LEASTRECENT:
684                 if (!mem->lastcall)
685                         tmp->metric = 0;
686                 else
687                         tmp->metric = 1000000 - (time(NULL) - mem->lastcall);
688                 tmp->metric += mem->penalty * 1000000;
689                 break;
690         default:
691                 ast_log(LOG_WARNING, "Can't calculate metric for unknown strategy %d\n", q->strategy);
692                 break;
693         }
694         return 0;
695 }
696
697 static int try_calling(struct queue_ent *qe, char *options, char *announceoverride, char *url)
698 {
699         struct member *cur;
700         struct localuser *outgoing=NULL, *tmp = NULL;
701         int to;
702         int allowredir_in=0;
703         int allowredir_out=0;
704         int allowdisconnect=0;
705         char restofit[AST_MAX_EXTENSION];
706         char *newnum;
707         struct ast_channel *peer;
708         struct localuser *lpeer;
709         int res = 0, bridge = 0;
710         int zapx = 2;
711         int x=0;
712         char *announce = NULL;
713         char digit = 0;
714         /* Hold the lock while we setup the outgoing calls */
715         ast_mutex_lock(&qe->parent->lock);
716         cur = qe->parent->members;
717         if (strlen(qe->announce))
718                 announce = qe->announce;
719         if (announceoverride && strlen(announceoverride))
720                 announce = announceoverride;
721         while(cur) {
722                 /* Get a technology/[device:]number pair */
723                 tmp = malloc(sizeof(struct localuser));
724                 if (!tmp) {
725                         ast_log(LOG_WARNING, "Out of memory\n");
726                         goto out;
727                 }
728                 memset(tmp, 0, sizeof(struct localuser));
729                 tmp->stillgoing = -1;
730                 if (options) {
731                         if (strchr(options, 't'))
732                                 tmp->allowredirect_in = 1;
733                         if (strchr(options, 'T'))
734                                 tmp->allowredirect_out = 1;
735                         if (strchr(options, 'r'))
736                                 tmp->ringbackonly = 1;
737                         if (strchr(options, 'm'))
738                                 tmp->musiconhold = 1;
739                         if (strchr(options, 'd'))
740                                 tmp->dataquality = 1;
741                         if (strchr(options, 'H'))
742                                 tmp->allowdisconnect = 1;
743                 }
744                 if (url) {
745                         ast_log(LOG_DEBUG, "Queue with URL=%s_\n", url);
746                 } else 
747                         ast_log(LOG_DEBUG, "Simple queue (no URL)\n");
748
749                 tmp->member = cur;              /* Never directly dereference!  Could change on reload */
750                 strncpy(tmp->tech, cur->tech, sizeof(tmp->tech)-1);
751                 strncpy(tmp->numsubst, cur->loc, sizeof(tmp->numsubst)-1);
752                 /* If we're dialing by extension, look at the extension to know what to dial */
753                 if ((newnum = strstr(tmp->numsubst, "BYEXTENSION"))) {
754                         strncpy(restofit, newnum + strlen("BYEXTENSION"), sizeof(restofit)-1);
755                         snprintf(newnum, sizeof(tmp->numsubst) - (newnum - tmp->numsubst), "%s%s", qe->chan->exten,restofit);
756                         if (option_debug)
757                                 ast_log(LOG_DEBUG, "Dialing by extension %s\n", tmp->numsubst);
758                 }
759                 /* Special case: If we ring everyone, go ahead and ring them, otherwise
760                    just calculate their metric for the appropriate strategy */
761                 calc_metric(qe->parent, cur, x++, qe, tmp);
762                 /* Put them in the list of outgoing thingies...  We're ready now. 
763                    XXX If we're forcibly removed, these outgoing calls won't get
764                    hung up XXX */
765                 tmp->next = outgoing;
766                 outgoing = tmp;         
767                 /* If this line is up, don't try anybody else */
768                 if (outgoing->chan && (outgoing->chan->_state == AST_STATE_UP))
769                         break;
770
771                 cur = cur->next;
772         }
773         if (qe->parent->timeout)
774                 to = qe->parent->timeout * 1000;
775         else
776                 to = -1;
777         ring_one(qe, outgoing);
778         ast_mutex_unlock(&qe->parent->lock);
779         lpeer = wait_for_answer(qe, outgoing, &to, &allowredir_in, &allowredir_out, &allowdisconnect, &digit);
780         if (lpeer)
781                 peer = lpeer->chan;
782         else
783                 peer = NULL;
784         if (!peer) {
785                 if (to) {
786                         /* Musta gotten hung up */
787                         res = -1;
788                 } else {
789                         if (digit && valid_exit(qe, digit))
790                                 res=digit;
791                         else
792                                 /* Nobody answered, next please? */
793                                 res=0;
794                 }
795                 goto out;
796         }
797         if (peer) {
798                 /* Ah ha!  Someone answered within the desired timeframe.  Of course after this
799                    we will always return with -1 so that it is hung up properly after the 
800                    conversation.  */
801                 if (!strcmp(qe->chan->type,"Zap")) {
802                         if (tmp->dataquality) zapx = 0;
803                         ast_channel_setoption(qe->chan,AST_OPTION_TONE_VERIFY,&zapx,sizeof(char),0);
804                 }                       
805                 if (!strcmp(peer->type,"Zap")) {
806                         if (tmp->dataquality) zapx = 0;
807                         ast_channel_setoption(peer,AST_OPTION_TONE_VERIFY,&zapx,sizeof(char),0);
808                 }
809                 /* Update parameters for the queue */
810                 update_queue(qe->parent, lpeer);
811                 hanguptree(outgoing, peer);
812                 /* Stop music on hold */
813                 ast_moh_stop(qe->chan);
814                 outgoing = NULL;
815                 if (announce) {
816                         int res2;
817                         res2 = ast_autoservice_start(qe->chan);
818                         if (!res2)
819                                 res2 = ast_streamfile(peer, announce, peer->language);
820                         if (!res2)
821                                 res2 = ast_waitstream(peer, "");
822                         res2 |= ast_autoservice_stop(qe->chan);
823                         if (res2) {
824                                 /* Agent must have hung up */
825                                 ast_log(LOG_WARNING, "Agent on %s hungup on the customer.  They're going to be pissed.\n", peer->name);
826                                 ast_hangup(peer);
827                                 return -1;
828                         }
829                 }
830                 /* If appropriate, log that we have a destination channel */
831                 if (qe->chan->cdr)
832                         ast_cdr_setdestchan(qe->chan->cdr, peer->name);
833                 /* Make sure channels are compatible */
834                 res = ast_channel_make_compatible(qe->chan, peer);
835                 if (res < 0) {
836                         ast_log(LOG_WARNING, "Had to drop call because I couldn't make %s compatible with %s\n", qe->chan->name, peer->name);
837                         ast_hangup(peer);
838                         return -1;
839                 }
840                 /* Drop out of the queue at this point, to prepare for next caller */
841                 leave_queue(qe);                        
842                 /* JDG: sendurl */
843                 if( url && strlen(url) && ast_channel_supports_html(peer) ) {
844                         ast_log(LOG_DEBUG, "app_queue: sendurl=%s.\n", url);
845                         ast_channel_sendurl( peer, url );
846                 } /* /JDG */
847                 bridge = ast_bridge_call(qe->chan, peer, allowredir_in, allowredir_out, allowdisconnect);
848
849                 if(bridge != AST_PBX_NO_HANGUP_PEER)
850                         ast_hangup(peer);
851
852                 if( bridge == 0 ) res=1; /* JDG: bridge successfull, leave app_queue */
853                 else res = bridge; /* bridge error, stay in the queue */
854         }       
855 out:
856         hanguptree(outgoing, NULL);
857         return res;
858 }
859
860 static int wait_a_bit(struct queue_ent *qe)
861 {
862         int retrywait;
863         /* Hold the lock while we setup the outgoing calls */
864         ast_mutex_lock(&qe->parent->lock);
865         retrywait = qe->parent->retry * 1000;
866         ast_mutex_unlock(&qe->parent->lock);
867         return ast_waitfordigit(qe->chan, retrywait);
868 }
869
870 // [PHM 06/26/03]
871
872 static struct member * interface_exists( struct ast_call_queue * q, char * interface )
873 {
874         struct member * ret = NULL ;
875         struct member *mem;
876         char buf[500] ;
877
878         if( q != NULL )
879         {
880                 mem = q->members ;
881
882                 while( mem != NULL ) {
883                         sprintf( buf, "%s/%s", mem->tech, mem->loc);
884
885                         if( strcmp( buf, interface ) == 0 ) {
886                                 ret = mem ;
887                                 break ;
888                         }
889                         else
890                                 mem = mem->next ;
891                 }
892         }
893
894         return( ret ) ;
895 }
896
897
898 static struct member * create_queue_node( char * interface )
899 {
900         struct member * cur ;
901         char * tmp ;
902         
903         /* Add a new member */
904
905         cur = malloc(sizeof(struct member));
906
907         if (cur) {
908                 memset(cur, 0, sizeof(struct member));
909                 strncpy(cur->tech, interface, sizeof(cur->tech) - 1);
910                 if ((tmp = strchr(cur->tech, '/')))
911                         *tmp = '\0';
912                 if ((tmp = strchr(interface, '/'))) {
913                         tmp++;
914                         strncpy(cur->loc, tmp, sizeof(cur->loc) - 1);
915                 } else
916                         ast_log(LOG_WARNING, "No location at interface '%s'\n", interface);
917         }
918
919         return( cur ) ;
920 }
921
922
923 static int rqm_exec(struct ast_channel *chan, void *data)
924 {
925         int res=-1;
926         struct localuser *u;
927         char *queuename;
928         struct member * node ;
929         struct member * look ;
930         char info[512];
931         char tmpchan[256]="";
932         char *interface=NULL;
933         struct ast_call_queue *q;
934         int found=0 ;
935
936         if (!data) {
937                 ast_log(LOG_WARNING, "RemoveQueueMember requires an argument (queuename|optional interface)\n");
938                 return -1;
939         }
940         
941         LOCAL_USER_ADD(u); // not sure if we need this, but better be safe than sorry ;-)
942         
943         /* Parse our arguments XXX Check for failure XXX */
944         strncpy(info, (char *)data, strlen((char *)data) + AST_MAX_EXTENSION-1);
945         queuename = info;
946         if (queuename) {
947                 interface = strchr(queuename, '|');
948                 if (interface) {
949                         *interface = '\0';
950                         interface++;
951                 }
952                 else {
953                         strncpy(tmpchan, chan->name, sizeof(tmpchan) - 1);
954                         interface = strrchr(tmpchan, '-');
955                         if (interface)
956                                 *interface = '\0';
957                         interface = tmpchan;
958                 }
959         }
960
961         if( ( q = queues) != NULL )
962         {
963                 while( q && ( res != 0 ) && (!found) ) 
964                 {
965                         ast_mutex_lock(&q->lock);
966                         if( strcmp( q->name, queuename) == 0 )
967                         {
968                                 // found queue, try to remove  interface
969                                 found=1 ;
970
971                                 if( ( node = interface_exists( q, interface ) ) != NULL )
972                                 {
973                                         if( ( look = q->members ) == node )
974                                         {
975                                                 // 1st
976                                                 q->members = node->next;
977                                         }
978                                         else
979                                         {
980                                                 while( look != NULL )
981                                                         if( look->next == node )
982                                                         {
983                                                                 look->next = node->next ;
984                                                                 break ;
985                                                         }
986                                                         else
987                                                                 look = look->next ;
988                                         }
989
990                                         free( node ) ;
991
992                                         ast_log(LOG_NOTICE, "Removed interface '%s' to queue '%s'\n", 
993                                                 interface, queuename);
994                                         res = 0 ;
995                                 }
996                                 else
997                                         ast_log(LOG_WARNING, "Unable to remove interface '%s' from queue '%s': "
998                                                 "Not there\n", interface, queuename);
999                         }
1000
1001                         ast_mutex_unlock(&q->lock);
1002                         q = q->next;
1003                 }
1004         }
1005
1006         if( ! found )
1007                 ast_log(LOG_WARNING, "Unable to remove interface from queue '%s': No such queue\n", queuename);
1008
1009         LOCAL_USER_REMOVE(u);
1010         return res;
1011 }
1012
1013
1014
1015 static int aqm_exec(struct ast_channel *chan, void *data)
1016 {
1017         int res=-1;
1018         struct localuser *u;
1019         char *queuename;
1020         char info[512];
1021         char tmpchan[512]="";
1022         char *interface=NULL;
1023         struct ast_call_queue *q;
1024         struct member *save;
1025         int found=0 ;
1026
1027         if (!data) {
1028                 ast_log(LOG_WARNING, "AddQueueMember requires an argument (queuename|optional interface)\n");
1029                 return -1;
1030         }
1031         
1032         LOCAL_USER_ADD(u); // not sure if we need this, but better be safe than sorry ;-)
1033         
1034         /* Parse our arguments XXX Check for failure XXX */
1035         strncpy(info, (char *)data, strlen((char *)data) + AST_MAX_EXTENSION-1);
1036         queuename = info;
1037         if (queuename) {
1038                 interface = strchr(queuename, '|');
1039                 if (interface) {
1040                         *interface = '\0';
1041                         interface++;
1042                 }
1043                 else {
1044                         strncpy(tmpchan, chan->name, sizeof(tmpchan) - 1);
1045                         interface = strrchr(tmpchan, '-');
1046                         if (interface)
1047                                 *interface = '\0';
1048                         interface = tmpchan;
1049                 }
1050         }
1051
1052         if( ( q = queues) != NULL )
1053         {
1054                 while( q && ( res != 0 ) && (!found) ) 
1055                 {
1056                         ast_mutex_lock(&q->lock);
1057                         if( strcmp( q->name, queuename) == 0 )
1058                         {
1059                                 // found queue, try to enable interface
1060                                 found=1 ;
1061
1062                                 if( interface_exists( q, interface ) == NULL )
1063                                 {
1064                                         save = q->members ;
1065                                         q->members = create_queue_node( interface ) ;
1066
1067                                         if( q->members != NULL ) {
1068                                                 q->members->dynamic = 1;
1069                                                 q->members->next = save ;
1070                                         } else
1071                                                 q->members = save ;
1072
1073                                         ast_log(LOG_NOTICE, "Added interface '%s' to queue '%s'\n", interface, queuename);
1074                                         res = 0 ;
1075                                 }
1076                                 else
1077                                         ast_log(LOG_WARNING, "Unable to add interface '%s' to queue '%s': "
1078                                                 "Already there\n", interface, queuename);
1079                         }
1080
1081                         ast_mutex_unlock(&q->lock);
1082                         q = q->next;
1083                 }
1084         }
1085
1086         if( ! found )
1087                 ast_log(LOG_WARNING, "Unable to add interface to queue '%s': No such queue\n", queuename);
1088
1089         LOCAL_USER_REMOVE(u);
1090         return res;
1091 }
1092
1093
1094 static int queue_exec(struct ast_channel *chan, void *data)
1095 {
1096         int res=-1;
1097         struct localuser *u;
1098         char *queuename;
1099         char info[512];
1100         char *options = NULL;
1101         char *url = NULL;
1102         char *announceoverride = NULL;
1103         
1104         /* Our queue entry */
1105         struct queue_ent qe;
1106         
1107         if (!data) {
1108                 ast_log(LOG_WARNING, "Queue requires an argument (queuename|optional timeout|optional URL)\n");
1109                 return -1;
1110         }
1111         
1112         LOCAL_USER_ADD(u);
1113         
1114         /* Parse our arguments XXX Check for failure XXX */
1115         strncpy(info, (char *)data, strlen((char *)data) + AST_MAX_EXTENSION-1);
1116         queuename = info;
1117         if (queuename) {
1118                 options = strchr(queuename, '|');
1119                 if (options) {
1120                         *options = '\0';
1121                         options++;
1122                         url = strchr(options, '|');
1123                         if (url) {
1124                                 *url = '\0';
1125                                 url++;
1126                                 announceoverride = strchr(url, '|');
1127                                 if (announceoverride) {
1128                                         *announceoverride = '\0';
1129                                         announceoverride++;
1130                                 }
1131                         }
1132                 }
1133         }
1134         printf("queue: %s, options: %s, url: %s, announce: %s\n",
1135                 queuename, options, url, announceoverride);
1136         /* Setup our queue entry */
1137         memset(&qe, 0, sizeof(qe));
1138         qe.chan = chan;
1139         qe.start = time(NULL);
1140         if (!join_queue(queuename, &qe)) {
1141                 /* Start music on hold */
1142                 ast_moh_start(chan, qe.moh);
1143                 for (;;) {
1144                         res = wait_our_turn(&qe);
1145                         /* If they hungup, return immediately */
1146                         if (res < 0) {
1147                                 if (option_verbose > 2) {
1148                                         ast_verbose(VERBOSE_PREFIX_3 "User disconnected while waiting their turn\n");
1149                                         res = -1;
1150                                 }
1151                                 break;
1152                         }
1153                         if (!res)
1154                                 break;
1155                         if (valid_exit(&qe, res))
1156                                 break;
1157                 }
1158                 if (!res) {
1159                         for (;;) {
1160                                 res = try_calling(&qe, options, announceoverride, url);
1161                                 if (res)
1162                                         break;
1163                                 res = wait_a_bit(&qe);
1164                                 if (res < 0) {
1165                                         if (option_verbose > 2) {
1166                                                 ast_verbose(VERBOSE_PREFIX_3 "User disconnected when they almost made it\n");
1167                                                 res = -1;
1168                                         }
1169                                         break;
1170                                 }
1171                                 if (res && valid_exit(&qe, res))
1172                                         break;
1173                         }
1174                 }
1175                 /* Don't allow return code > 0 */
1176                 if (res > 0 && res != AST_PBX_KEEPALIVE) {
1177                         res = 0;        
1178                         ast_moh_stop(chan);
1179                 }
1180                 leave_queue(&qe);
1181         } else {
1182                 ast_log(LOG_WARNING, "Unable to join queue '%s'\n", queuename);
1183                 res =  0;
1184         }
1185         LOCAL_USER_REMOVE(u);
1186         return res;
1187 }
1188
1189 static void reload_queues(void)
1190 {
1191         struct ast_call_queue *q, *ql, *qn;
1192         struct ast_config *cfg;
1193         char *cat, *tmp;
1194         struct ast_variable *var;
1195         struct member *prev, *cur;
1196         int new;
1197         cfg = ast_load("queues.conf");
1198         if (!cfg) {
1199                 ast_log(LOG_NOTICE, "No call queueing config file, so no call queues\n");
1200                 return;
1201         }
1202         ast_mutex_lock(&qlock);
1203         /* Mark all queues as dead for the moment */
1204         q = queues;
1205         while(q) {
1206                 q = q->next;
1207         }
1208         /* Chug through config file */
1209         cat = ast_category_browse(cfg, NULL);
1210         while(cat) {
1211                 if (strcasecmp(cat, "general")) {
1212                         /* Look for an existing one */
1213                         q = queues;
1214                         while(q) {
1215                                 if (!strcmp(q->name, cat))
1216                                         break;
1217                                 q = q->next;
1218                         }
1219                         if (!q) {
1220                                 /* Make one then */
1221                                 q = malloc(sizeof(struct ast_call_queue));
1222                                 if (q) {
1223                                         /* Initialize it */
1224                                         memset(q, 0, sizeof(struct ast_call_queue));
1225                                         ast_mutex_init(&q->lock);
1226                                         strncpy(q->name, cat, sizeof(q->name));
1227                                         new = 1;
1228                                 } else new = 0;
1229                         } else
1230                                         new = 0;
1231                         if (q) {
1232                                 if (!new) 
1233                                         ast_mutex_lock(&q->lock);
1234                                 /* Re-initialize the queue */
1235                                 q->dead = 0;
1236                                 q->retry = 0;
1237                                 q->timeout = -1;
1238                                 q->maxlen = 0;
1239                                 free_members(q, 0);
1240                                 strcpy(q->moh, "");
1241                                 strcpy(q->announce, "");
1242                                 strcpy(q->context, "");
1243                                 prev = q->members;
1244                                 if (prev) {
1245                                         /* find the end of any dynamic members */
1246                                         while(prev->next)
1247                                                 prev = prev->next;
1248                                 }
1249                                 var = ast_variable_browse(cfg, cat);
1250                                 while(var) {
1251                                         if (!strcasecmp(var->name, "member")) {
1252                                                 /* Add a new member */
1253                                                 cur = malloc(sizeof(struct member));
1254                                                 if (cur) {
1255                                                         memset(cur, 0, sizeof(struct member));
1256                                                         strncpy(cur->tech, var->value, sizeof(cur->tech) - 1);
1257                                                         if ((tmp = strchr(cur->tech, ','))) {
1258                                                                 *tmp = '\0';
1259                                                                 tmp++;
1260                                                                 cur->penalty = atoi(tmp);
1261                                                                 if (cur->penalty < 0)
1262                                                                         cur->penalty = 0;
1263                                                         }
1264                                                         if ((tmp = strchr(cur->tech, '/')))
1265                                                                 *tmp = '\0';
1266                                                         if ((tmp = strchr(var->value, '/'))) {
1267                                                                 tmp++;
1268                                                                 strncpy(cur->loc, tmp, sizeof(cur->loc) - 1);
1269                                                                 if ((tmp = strchr(cur->loc, ',')))
1270                                                                         *tmp = '\0';
1271                                                         } else
1272                                                                 ast_log(LOG_WARNING, "No location at line %d of queue.conf\n", var->lineno);
1273                                                         if (prev)
1274                                                                 prev->next = cur;
1275                                                         else
1276                                                                 q->members = cur;
1277                                                         prev = cur;
1278                                                 }
1279                                         } else if (!strcasecmp(var->name, "music")) {
1280                                                 strncpy(q->moh, var->value, sizeof(q->moh) - 1);
1281                                         } else if (!strcasecmp(var->name, "announce")) {
1282                                                 strncpy(q->announce, var->value, sizeof(q->announce) - 1);
1283                                         } else if (!strcasecmp(var->name, "context")) {
1284                                                 strncpy(q->context, var->value, sizeof(q->context) - 1);
1285                                         } else if (!strcasecmp(var->name, "timeout")) {
1286                                                 q->timeout = atoi(var->value);
1287                                         } else if (!strcasecmp(var->name, "retry")) {
1288                                                 q->retry = atoi(var->value);
1289                                         } else if (!strcasecmp(var->name, "maxlen")) {
1290                                                 q->maxlen = atoi(var->value);
1291                                         } else if (!strcasecmp(var->name, "strategy")) {
1292                                                 q->strategy = strat2int(var->value);
1293                                                 if (q->strategy < 0) {
1294                                                         ast_log(LOG_WARNING, "'%s' isn't a valid strategy, using ringall instead\n", var->value);
1295                                                         q->strategy = 0;
1296                                                 }
1297                                         } else {
1298                                                 ast_log(LOG_WARNING, "Unknown keyword in queue '%s': %s at line %d of queue.conf\n", cat, var->name, var->lineno);
1299                                         }
1300                                         var = var->next;
1301                                 }
1302                                 if (q->retry < 1)
1303                                         q->retry = DEFAULT_RETRY;
1304                                 if (q->timeout < 0)
1305                                         q->timeout = DEFAULT_TIMEOUT;
1306                                 if (q->maxlen < 0)
1307                                         q->maxlen = 0;
1308                                 if (!new) 
1309                                         ast_mutex_unlock(&q->lock);
1310                                 if (new) {
1311                                         q->next = queues;
1312                                         queues = q;
1313                                 }
1314                         }
1315                 }
1316                 cat = ast_category_browse(cfg, cat);
1317         }
1318         ast_destroy(cfg);
1319         q = queues;
1320         ql = NULL;
1321         while(q) {
1322                 qn = q->next;
1323                 if (q->dead) {
1324                         if (ql)
1325                                 ql->next = q->next;
1326                         else
1327                                 queues = q->next;
1328                         if (!q->count) {
1329                                 free(q);
1330                         } else
1331                                 ast_log(LOG_WARNING, "XXX Leaking a litttle memory :( XXX\n");
1332                 } else
1333                         ql = q;
1334                 q = qn;
1335         }
1336         ast_mutex_unlock(&qlock);
1337 }
1338
1339 static int queues_show(int fd, int argc, char **argv)
1340 {
1341         struct ast_call_queue *q;
1342         struct queue_ent *qe;
1343         struct member *mem;
1344         int pos;
1345         time_t now;
1346         char max[80];
1347         char calls[80];
1348         
1349         time(&now);
1350         if (argc != 2)
1351                 return RESULT_SHOWUSAGE;
1352         q = queues;
1353         if (!q) {       
1354                 ast_cli(fd, "No queues.\n");
1355                 return RESULT_SUCCESS;
1356         }
1357         while(q) {
1358                 ast_mutex_lock(&q->lock);
1359                 if (q->maxlen)
1360                         snprintf(max, sizeof(max), "%d", q->maxlen);
1361                 else
1362                         strcpy(max, "unlimited");
1363                 ast_cli(fd, "%-12.12s has %d calls (max %s) in '%s' strategy\n", q->name, q->count, max, int2strat(q->strategy));
1364                 if (q->members) {
1365                         ast_cli(fd, "   Members: \n");
1366                         for (mem = q->members; mem; mem = mem->next) {
1367                                 if (mem->penalty)
1368                                         snprintf(max, sizeof(max) - 20, " with penalty %d", mem->penalty);
1369                                 else
1370                                         strcpy(max, "");
1371                                 if (mem->dynamic)
1372                                         strcat(max, " (dynamic)");
1373                                 if (mem->calls) {
1374                                         snprintf(calls, sizeof(calls), " has taken %d calls (last was %ld secs ago)",
1375                                                         mem->calls, time(NULL) - mem->lastcall);
1376                                 } else
1377                                         strcpy(calls, " has taken no calls yet");
1378                                 ast_cli(fd, "      %s/%s%s%s\n", mem->tech, mem->loc, max, calls);
1379                         }
1380                 } else
1381                         ast_cli(fd, "   No Members\n");
1382                 if (q->head) {
1383                         pos = 1;
1384                         ast_cli(fd, "   Callers: \n");
1385                         for (qe = q->head; qe; qe = qe->next) 
1386                                 ast_cli(fd, "      %d. %s (wait: %d:%02.2d)\n", pos++, qe->chan->name,
1387                                                                 (now - qe->start) / 60, (now - qe->start) % 60);
1388                 } else
1389                         ast_cli(fd, "   No Callers\n");
1390                 ast_cli(fd, "\n");
1391                 ast_mutex_unlock(&q->lock);
1392                 q = q->next;
1393         }
1394         return RESULT_SUCCESS;
1395 }
1396
1397 /* JDG: callback to display queues status in manager */
1398 static int manager_queues_show( struct mansession *s, struct message *m )
1399 {
1400         char *a[] = { "show", "queues" };
1401         return queues_show( s->fd, 2, a );
1402 } /* /JDG */
1403
1404
1405 /* Dump queue status */
1406 static int manager_queues_status( struct mansession *s, struct message *m )
1407 {
1408         time_t now;
1409         int pos;
1410         struct ast_call_queue *q;
1411         struct queue_ent *qe;
1412         astman_send_ack(s, "Queue status will follow");
1413         time(&now);
1414         q = queues;
1415         while(q) {
1416                 ast_mutex_lock(&q->lock);
1417                 ast_cli(s->fd, "Event: QueueParams\r\n"
1418                                         "Queue: %s\r\n"
1419                                         "Max: %d\r\n"
1420                                         "Calls: %d\r\n"
1421                                         "\r\n",
1422                                                 q->name, q->maxlen, q->count);
1423 #if 0
1424                 /* Do we care about queue members? */                                   
1425                 for (mem = q->members; mem; mem = mem->next) 
1426                         ast_cli(fd, "      %s/%s\n", mem->tech, mem->loc);
1427 #endif                  
1428                 pos = 1;
1429                 for (qe = q->head; qe; qe = qe->next) 
1430                         ast_cli(s->fd, "Event: QueueMember\r\n"
1431                                 "Queue: %s\r\n"
1432                                 "Position: %d\r\n"
1433                                 "Channel: %s\r\n"
1434                                 "CallerID: %s\r\n"
1435                                 "Wait: %ld\r\n"
1436                                 "\r\n", 
1437                                         q->name, pos++, qe->chan->name, (qe->chan->callerid ? qe->chan->callerid : ""), now - qe->start);
1438                 ast_mutex_unlock(&q->lock);
1439                 q = q->next;
1440         }
1441         return RESULT_SUCCESS;
1442 }
1443
1444 static char show_queues_usage[] = 
1445 "Usage: show queues\n"
1446 "       Provides summary information on call queues.\n";
1447
1448 static struct ast_cli_entry cli_show_queues = {
1449         { "show", "queues", NULL }, queues_show, 
1450         "Show status of queues", show_queues_usage, NULL };
1451
1452 int unload_module(void)
1453 {
1454         STANDARD_HANGUP_LOCALUSERS;
1455         ast_cli_unregister(&cli_show_queues);
1456         ast_manager_unregister( "Queues" );
1457         ast_manager_unregister( "QueueStatus" );
1458         return ast_unregister_application(app);
1459 }
1460
1461 int load_module(void)
1462 {
1463         int res;
1464         res = ast_register_application(app, queue_exec, synopsis, descrip);
1465         if (!res) {
1466                 ast_cli_register(&cli_show_queues);
1467                 ast_manager_register( "Queues", 0, manager_queues_show, "Queues" );
1468                 ast_manager_register( "QueueStatus", 0, manager_queues_status, "Queue Status" );
1469
1470                 // [PHM 06/26/03]
1471                 ast_register_application(app_aqm, aqm_exec, app_aqm_synopsis, app_aqm_descrip) ;
1472                 ast_register_application(app_rqm, rqm_exec, app_rqm_synopsis, app_rqm_descrip) ;
1473         }
1474         reload_queues();
1475         return res;
1476 }
1477
1478
1479 int reload(void)
1480 {
1481         reload_queues();
1482         return 0;
1483 }
1484
1485 char *description(void)
1486 {
1487         return tdesc;
1488 }
1489
1490 int usecount(void)
1491 {
1492         int res;
1493         STANDARD_USECOUNT(res);
1494         return res;
1495 }
1496
1497 char *key()
1498 {
1499         return ASTERISK_GPL_KEY;
1500 }