Add Estonian tone zone (bug #3589)
[asterisk/asterisk.git] / channel.c
1 /*
2  * Asterisk -- A telephony toolkit for Linux.
3  *
4  * Channel Management
5  * 
6  * Copyright (C) 1999 - 2005, Digium, Inc.
7  *
8  * Mark Spencer <markster@digium.com>
9  *
10  * This program is free software, distributed under the terms of
11  * the GNU General Public License
12  */
13
14 #include <stdio.h>
15 #include <stdlib.h>
16 #include <string.h>
17 #include <sys/time.h>
18 #include <signal.h>
19 #include <errno.h>
20 #include <unistd.h>
21 #include <math.h>                       /* For PI */
22 #include <asterisk/pbx.h>
23 #include <asterisk/frame.h>
24 #include <asterisk/sched.h>
25 #include <asterisk/options.h>
26 #include <asterisk/channel.h>
27 #include <asterisk/musiconhold.h>
28 #include <asterisk/channel_pvt.h>
29 #include <asterisk/logger.h>
30 #include <asterisk/say.h>
31 #include <asterisk/file.h>
32 #include <asterisk/cli.h>
33 #include <asterisk/translate.h>
34 #include <asterisk/manager.h>
35 #include <asterisk/chanvars.h>
36 #include <asterisk/linkedlists.h>
37 #include <asterisk/indications.h>
38 #include <asterisk/monitor.h>
39 #include <asterisk/causes.h>
40 #include <asterisk/utils.h>
41 #include <asterisk/lock.h>
42 #include <asterisk/app.h>
43 #ifdef ZAPTEL_OPTIMIZATIONS
44 #include <sys/ioctl.h>
45 #ifdef __linux__
46 #include <linux/zaptel.h>
47 #else
48 #include <zaptel.h>
49 #endif /* __linux__ */
50 #ifndef ZT_TIMERPING
51 #error "You need newer zaptel!  Please cvs update zaptel"
52 #endif
53 #endif
54 #include "asterisk.h"
55
56 /* uncomment if you have problems with 'monitoring' synchronized files */
57 #if 0
58 #define MONITOR_CONSTANT_DELAY
59 #define MONITOR_DELAY   150 * 8         /* 150 ms of MONITORING DELAY */
60 #endif
61
62 static int shutting_down = 0;
63 static int uniqueint = 0;
64
65 unsigned long global_fin = 0, global_fout = 0;
66
67 /* XXX Lock appropriately in more functions XXX */
68
69 struct chanlist {
70         char type[80];
71         char description[80];
72         int capabilities;
73         struct ast_channel * (*requester)(const char *type, int format, void *data, int *cause);
74         int (*devicestate)(void *data);
75         struct chanlist *next;
76 } *backends = NULL;
77 struct ast_channel *channels = NULL;
78
79 /* Protect the channel list (highly unlikely that two things would change
80    it at the same time, but still! */
81    
82 AST_MUTEX_DEFINE_STATIC(chlock);
83
84 static int show_channeltypes(int fd, int argc, char *argv[])
85 {
86 #define FORMAT  "%-7.7s  %-50.50s\n"
87         struct chanlist *cl = backends;
88         ast_cli(fd, FORMAT, "Type", "Description");
89         ast_cli(fd, FORMAT, "------", "-----------");
90         if (ast_mutex_lock(&chlock)) {
91                 ast_log(LOG_WARNING, "Unable to lock channel list\n");
92                 return -1;
93         }
94         while (cl) {
95                 ast_cli(fd, FORMAT, cl->type, cl->description);
96                 cl = cl->next;
97         }
98         ast_mutex_unlock(&chlock);
99         return RESULT_SUCCESS;
100
101 }
102
103 static char show_channeltypes_usage[] = 
104 "Usage: show channeltypes\n"
105 "       Shows available channel types registered in your Asterisk server.\n";
106
107 static struct ast_cli_entry cli_show_channeltypes = 
108         { { "show", "channeltypes", NULL }, show_channeltypes, "Show available channel types", show_channeltypes_usage };
109
110 int ast_check_hangup(struct ast_channel *chan)
111 {
112 time_t  myt;
113
114           /* if soft hangup flag, return true */
115         if (chan->_softhangup) return 1;
116           /* if no private structure, return true */
117         if (!chan->pvt->pvt) return 1;
118           /* if no hangup scheduled, just return here */
119         if (!chan->whentohangup) return 0;
120         time(&myt); /* get current time */
121           /* return, if not yet */
122         if (chan->whentohangup > myt) return 0;
123         chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
124         return 1;
125 }
126
127 static int ast_check_hangup_locked(struct ast_channel *chan)
128 {
129         int res;
130         ast_mutex_lock(&chan->lock);
131         res = ast_check_hangup(chan);
132         ast_mutex_unlock(&chan->lock);
133         return res;
134 }
135
136 void ast_begin_shutdown(int hangup)
137 {
138         struct ast_channel *c;
139         shutting_down = 1;
140         if (hangup) {
141                 ast_mutex_lock(&chlock);
142                 c = channels;
143                 while(c) {
144                         ast_softhangup(c, AST_SOFTHANGUP_SHUTDOWN);
145                         c = c->next;
146                 }
147                 ast_mutex_unlock(&chlock);
148         }
149 }
150
151 int ast_active_channels(void)
152 {
153         struct ast_channel *c;
154         int cnt = 0;
155         ast_mutex_lock(&chlock);
156         c = channels;
157         while(c) {
158                 cnt++;
159                 c = c->next;
160         }
161         ast_mutex_unlock(&chlock);
162         return cnt;
163 }
164
165 void ast_cancel_shutdown(void)
166 {
167         shutting_down = 0;
168 }
169
170 int ast_shutting_down(void)
171 {
172         return shutting_down;
173 }
174
175 void ast_channel_setwhentohangup(struct ast_channel *chan, time_t offset)
176 {
177         time_t  myt;
178
179         time(&myt);
180         if (offset)
181                 chan->whentohangup = myt + offset;
182         else
183                 chan->whentohangup = 0;
184         return;
185 }
186
187 int ast_channel_register(const char *type, const char *description, int capabilities,
188                 struct ast_channel *(*requester)(const char *type, int format, void *data, int *cause))
189 {
190         return ast_channel_register_ex(type, description, capabilities, requester, NULL);
191 }
192
193 int ast_channel_register_ex(const char *type, const char *description, int capabilities,
194                 struct ast_channel *(*requester)(const char *type, int format, void *data, int *cause),
195                 int (*devicestate)(void *data))
196 {
197         struct chanlist *chan, *last=NULL;
198         if (ast_mutex_lock(&chlock)) {
199                 ast_log(LOG_WARNING, "Unable to lock channel list\n");
200                 return -1;
201         }
202         chan = backends;
203         while (chan) {
204                 if (!strcasecmp(type, chan->type)) {
205                         ast_log(LOG_WARNING, "Already have a handler for type '%s'\n", type);
206                         ast_mutex_unlock(&chlock);
207                         return -1;
208                 }
209                 last = chan;
210                 chan = chan->next;
211         }
212         chan = malloc(sizeof(struct chanlist));
213         if (!chan) {
214                 ast_log(LOG_WARNING, "Out of memory\n");
215                 ast_mutex_unlock(&chlock);
216                 return -1;
217         }
218         strncpy(chan->type, type, sizeof(chan->type)-1);
219         strncpy(chan->description, description, sizeof(chan->description)-1);
220         chan->capabilities = capabilities;
221         chan->requester = requester;
222         chan->devicestate = devicestate;
223         chan->next = NULL;
224         if (last)
225                 last->next = chan;
226         else
227                 backends = chan;
228         if (option_debug)
229                 ast_log(LOG_DEBUG, "Registered handler for '%s' (%s)\n", chan->type, chan->description);
230         else if (option_verbose > 1)
231                 ast_verbose( VERBOSE_PREFIX_2 "Registered channel type '%s' (%s)\n", chan->type, chan->description);
232         ast_mutex_unlock(&chlock);
233         return 0;
234 }
235
236 char *ast_state2str(int state)
237 {
238         /* XXX Not reentrant XXX */
239         static char localtmp[256];
240         switch(state) {
241         case AST_STATE_DOWN:
242                 return "Down";
243         case AST_STATE_RESERVED:
244                 return "Rsrvd";
245         case AST_STATE_OFFHOOK:
246                 return "OffHook";
247         case AST_STATE_DIALING:
248                 return "Dialing";
249         case AST_STATE_RING:
250                 return "Ring";
251         case AST_STATE_RINGING:
252                 return "Ringing";
253         case AST_STATE_UP:
254                 return "Up";
255         case AST_STATE_BUSY:
256                 return "Busy";
257         default:
258                 snprintf(localtmp, sizeof(localtmp), "Unknown (%d)\n", state);
259                 return localtmp;
260         }
261 }
262
263
264 int ast_best_codec(int fmts)
265 {
266         /* This just our opinion, expressed in code.  We are asked to choose
267            the best codec to use, given no information */
268         int x;
269         static int prefs[] = 
270         {
271                 /* Okay, ulaw is used by all telephony equipment, so start with it */
272                 AST_FORMAT_ULAW,
273                 /* Unless of course, you're a silly European, so then prefer ALAW */
274                 AST_FORMAT_ALAW,
275                 /* Okay, well, signed linear is easy to translate into other stuff */
276                 AST_FORMAT_SLINEAR,
277                 /* G.726 is standard ADPCM */
278                 AST_FORMAT_G726,
279                 /* ADPCM has great sound quality and is still pretty easy to translate */
280                 AST_FORMAT_ADPCM,
281                 /* Okay, we're down to vocoders now, so pick GSM because it's small and easier to
282                    translate and sounds pretty good */
283                 AST_FORMAT_GSM,
284                 /* iLBC is not too bad */
285                 AST_FORMAT_ILBC,
286                 /* Speex is free, but computationally more expensive than GSM */
287                 AST_FORMAT_SPEEX,
288                 /* Ick, LPC10 sounds terrible, but at least we have code for it, if you're tacky enough
289                    to use it */
290                 AST_FORMAT_LPC10,
291                 /* G.729a is faster than 723 and slightly less expensive */
292                 AST_FORMAT_G729A,
293                 /* Down to G.723.1 which is proprietary but at least designed for voice */
294                 AST_FORMAT_G723_1,
295         };
296         
297         
298         for (x=0;x<sizeof(prefs) / sizeof(prefs[0]); x++)
299                 if (fmts & prefs[x])
300                         return prefs[x];
301         ast_log(LOG_WARNING, "Don't know any of 0x%x formats\n", fmts);
302         return 0;
303 }
304
305 struct ast_channel *ast_channel_alloc(int needqueue)
306 {
307         struct ast_channel *tmp;
308         struct ast_channel_pvt *pvt;
309         int x;
310         int flags;
311         struct varshead *headp;        
312                 
313         
314         /* If shutting down, don't allocate any new channels */
315         if (shutting_down)
316                 return NULL;
317         ast_mutex_lock(&chlock);
318         tmp = malloc(sizeof(struct ast_channel));
319         if (tmp) {
320                 memset(tmp, 0, sizeof(struct ast_channel));
321                 pvt = malloc(sizeof(struct ast_channel_pvt));
322                 if (pvt) {
323                         memset(pvt, 0, sizeof(struct ast_channel_pvt));
324                         tmp->sched = sched_context_create();
325                         if (tmp->sched) {
326                                 for (x=0;x<AST_MAX_FDS - 1;x++)
327                                         tmp->fds[x] = -1;
328 #ifdef ZAPTEL_OPTIMIZATIONS
329                                 tmp->timingfd = open("/dev/zap/timer", O_RDWR);
330                                 if (tmp->timingfd > -1) {
331                                         /* Check if timing interface supports new
332                                            ping/pong scheme */
333                                         flags = 1;
334                                         if (!ioctl(tmp->timingfd, ZT_TIMERPONG, &flags))
335                                                 needqueue = 0;
336                                 }
337 #else
338                                 tmp->timingfd = -1;                                     
339 #endif                                  
340                                 if (needqueue &&  
341                                         pipe(pvt->alertpipe)) {
342                                         ast_log(LOG_WARNING, "Alert pipe creation failed!\n");
343                                         free(pvt);
344                                         free(tmp);
345                                         tmp = NULL;
346                                         pvt = NULL;
347                                 } else {
348                                         if (needqueue) {
349                                                 flags = fcntl(pvt->alertpipe[0], F_GETFL);
350                                                 fcntl(pvt->alertpipe[0], F_SETFL, flags | O_NONBLOCK);
351                                                 flags = fcntl(pvt->alertpipe[1], F_GETFL);
352                                                 fcntl(pvt->alertpipe[1], F_SETFL, flags | O_NONBLOCK);
353                                         } else 
354                                         /* Make sure we've got it done right if they don't */
355                                                 pvt->alertpipe[0] = pvt->alertpipe[1] = -1;
356                                         /* Always watch the alertpipe */
357                                         tmp->fds[AST_MAX_FDS-1] = pvt->alertpipe[0];
358                                         /* And timing pipe */
359                                         tmp->fds[AST_MAX_FDS-2] = tmp->timingfd;
360                                         strncpy(tmp->name, "**Unknown**", sizeof(tmp->name)-1);
361                                         tmp->pvt = pvt;
362                                         /* Initial state */
363                                         tmp->_state = AST_STATE_DOWN;
364                                         tmp->streamid = -1;
365                                         tmp->appl = NULL;
366                                         tmp->data = NULL;
367                                         tmp->fin = global_fin;
368                                         tmp->fout = global_fout;
369                                         snprintf(tmp->uniqueid, sizeof(tmp->uniqueid), "%li.%d", (long)time(NULL), uniqueint++);
370                                         headp=&tmp->varshead;
371                                         ast_mutex_init(&tmp->lock);
372                                         AST_LIST_HEAD_INIT(headp);
373                                         strncpy(tmp->context, "default", sizeof(tmp->context)-1);
374                                         strncpy(tmp->language, defaultlanguage, sizeof(tmp->language)-1);
375                                         strncpy(tmp->exten, "s", sizeof(tmp->exten)-1);
376                                         tmp->priority=1;
377                                         tmp->amaflags = ast_default_amaflags;
378                                         strncpy(tmp->accountcode, ast_default_accountcode, sizeof(tmp->accountcode)-1);
379                                         tmp->next = channels;
380                                         channels= tmp;
381                                 }
382                         } else {
383                                 ast_log(LOG_WARNING, "Unable to create schedule context\n");
384                                 free(tmp);
385                                 tmp = NULL;
386                         }
387                 } else {
388                         ast_log(LOG_WARNING, "Out of memory\n");
389                         free(tmp);
390                         tmp = NULL;
391                 }
392         } else 
393                 ast_log(LOG_WARNING, "Out of memory\n");
394         ast_mutex_unlock(&chlock);
395         return tmp;
396 }
397
398 int ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin)
399 {
400         struct ast_frame *f;
401         struct ast_frame *prev, *cur;
402         int blah = 1;
403         int qlen = 0;
404         /* Build us a copy and free the original one */
405         f = ast_frdup(fin);
406         if (!f) {
407                 ast_log(LOG_WARNING, "Unable to duplicate frame\n");
408                 return -1;
409         }
410         ast_mutex_lock(&chan->lock);
411         prev = NULL;
412         cur = chan->pvt->readq;
413         while(cur) {
414                 if ((cur->frametype == AST_FRAME_CONTROL) && (cur->subclass == AST_CONTROL_HANGUP)) {
415                         /* Don't bother actually queueing anything after a hangup */
416                         ast_frfree(f);
417                         ast_mutex_unlock(&chan->lock);
418                         return 0;
419                 }
420                 prev = cur;
421                 cur = cur->next;
422                 qlen++;
423         }
424         /* Allow up to 96 voice frames outstanding, and up to 128 total frames */
425         if (((fin->frametype == AST_FRAME_VOICE) && (qlen > 96)) || (qlen  > 128)) {
426                 if (fin->frametype != AST_FRAME_VOICE) {
427                         ast_log(LOG_WARNING, "Exceptionally long queue length queuing to %s\n", chan->name);
428                         CRASH;
429                 } else {
430                         ast_log(LOG_DEBUG, "Dropping voice to exceptionally long queue on %s\n", chan->name);
431                         ast_frfree(f);
432                         ast_mutex_unlock(&chan->lock);
433                         return 0;
434                 }
435         }
436         if (prev)
437                 prev->next = f;
438         else
439                 chan->pvt->readq = f;
440         if (chan->pvt->alertpipe[1] > -1) {
441                 if (write(chan->pvt->alertpipe[1], &blah, sizeof(blah)) != sizeof(blah))
442                         ast_log(LOG_WARNING, "Unable to write to alert pipe on %s, frametype/subclass %d/%d (qlen = %d): %s!\n",
443                                 chan->name, f->frametype, f->subclass, qlen, strerror(errno));
444 #ifdef ZAPTEL_OPTIMIZATIONS
445         } else if (chan->timingfd > -1) {
446                 ioctl(chan->timingfd, ZT_TIMERPING, &blah);
447 #endif                          
448         } else if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
449                 pthread_kill(chan->blocker, SIGURG);
450         }
451         ast_mutex_unlock(&chan->lock);
452         return 0;
453 }
454
455 int ast_queue_hangup(struct ast_channel *chan)
456 {
457         struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_HANGUP };
458         chan->_softhangup |= AST_SOFTHANGUP_DEV;
459         return ast_queue_frame(chan, &f);
460 }
461
462 int ast_queue_control(struct ast_channel *chan, int control)
463 {
464         struct ast_frame f = { AST_FRAME_CONTROL, };
465         f.subclass = control;
466         return ast_queue_frame(chan, &f);
467 }
468
469 int ast_channel_defer_dtmf(struct ast_channel *chan)
470 {
471         int pre = 0;
472         if (chan) {
473                 pre = ast_test_flag(chan, AST_FLAG_DEFER_DTMF);
474                 ast_set_flag(chan, AST_FLAG_DEFER_DTMF);
475         }
476         return pre;
477 }
478
479 void ast_channel_undefer_dtmf(struct ast_channel *chan)
480 {
481         if (chan)
482                 ast_clear_flag(chan, AST_FLAG_DEFER_DTMF);
483 }
484
485 struct ast_channel *ast_channel_walk_locked(struct ast_channel *prev)
486 {
487         /* Returns next channel (locked) */
488         struct ast_channel *l, *ret;
489         int retries = 0;        
490 retry:
491         ret=NULL;
492         ast_mutex_lock(&chlock);
493         l = channels;
494         if (!prev) {
495                 if (l) {
496                         if (ast_mutex_trylock(&l->lock)) {
497                                 if (retries < 10)
498                                         ast_log(LOG_DEBUG, "Avoiding initial deadlock for '%s'\n", l->name);
499                                 else
500                                         ast_log(LOG_WARNING, "Avoided initial deadlock for '%s', %d retries!\n", l->name, retries);
501                                 ast_mutex_unlock(&chlock);
502                                 if (retries < 10) {
503                                         usleep(1);
504                                         retries++;
505                                         goto retry;
506                                 } else
507                                         return NULL;
508                         }
509                 }
510                 ast_mutex_unlock(&chlock);
511                 return l;
512         }
513         while(l) {
514                 if (l == prev)
515                         ret = l->next;
516                 l = l->next;
517         }
518         if (ret) {
519                 if (ast_mutex_trylock(&ret->lock)) {
520                         if (retries < 10)
521                                 ast_log(LOG_DEBUG, "Avoiding deadlock for '%s'\n", ret->name);
522                         else
523                                 ast_log(LOG_WARNING, "Avoided deadlock for '%s', %d retries!\n", ret->name, retries);
524                         ast_mutex_unlock(&chlock);
525                         if (retries < 10) {
526                                 usleep(1);
527                                 retries++;
528                                 goto retry;
529                         } else
530                                 return NULL;
531                 }
532         }
533         ast_mutex_unlock(&chlock);
534         return ret;
535         
536 }
537
538 struct ast_channel *ast_get_channel_by_name_locked(char *channame)
539 {
540         struct ast_channel *chan;
541         chan = ast_channel_walk_locked(NULL);
542         while(chan) {
543                 if (!strcasecmp(chan->name, channame))
544                         return chan;
545                 ast_mutex_unlock(&chan->lock);
546                 chan = ast_channel_walk_locked(chan);
547         }
548         return NULL;
549 }
550
551 int ast_safe_sleep_conditional( struct ast_channel *chan, int ms,
552                                                                 int (*cond)(void*), void *data )
553 {
554         struct ast_frame *f;
555
556         while(ms > 0) {
557                 if( cond && ((*cond)(data) == 0 ) )
558                         return 0;
559                 ms = ast_waitfor(chan, ms);
560                 if (ms <0)
561                         return -1;
562                 if (ms > 0) {
563                         f = ast_read(chan);
564                         if (!f)
565                                 return -1;
566                         ast_frfree(f);
567                 }
568         }
569         return 0;
570 }
571
572 int ast_safe_sleep(struct ast_channel *chan, int ms)
573 {
574         struct ast_frame *f;
575         while(ms > 0) {
576                 ms = ast_waitfor(chan, ms);
577                 if (ms <0)
578                         return -1;
579                 if (ms > 0) {
580                         f = ast_read(chan);
581                         if (!f)
582                                 return -1;
583                         ast_frfree(f);
584                 }
585         }
586         return 0;
587 }
588
589 static void free_cid(struct ast_callerid *cid)
590 {
591         if (cid->cid_dnid)
592                 free(cid->cid_dnid);
593         if (cid->cid_num)
594                 free(cid->cid_num);     
595         if (cid->cid_name)
596                 free(cid->cid_name);    
597         if (cid->cid_ani)
598                 free(cid->cid_ani);
599         if (cid->cid_rdnis)
600                 free(cid->cid_rdnis);
601 }
602
603 void ast_channel_free(struct ast_channel *chan)
604 {
605         struct ast_channel *last=NULL, *cur;
606         int fd;
607         struct ast_var_t *vardata;
608         struct ast_frame *f, *fp;
609         struct varshead *headp;
610         char name[AST_CHANNEL_NAME];
611         
612         headp=&chan->varshead;
613         
614         ast_mutex_lock(&chlock);
615         cur = channels;
616         while(cur) {
617                 if (cur == chan) {
618                         if (last)
619                                 last->next = cur->next;
620                         else
621                                 channels = cur->next;
622                         break;
623                 }
624                 last = cur;
625                 cur = cur->next;
626         }
627         if (!cur)
628                 ast_log(LOG_WARNING, "Unable to find channel in list\n");
629         else {
630                 /* Lock and unlock the channel just to be sure nobody
631                    has it locked still */
632                 ast_mutex_lock(&cur->lock);
633                 ast_mutex_unlock(&cur->lock);
634         }
635         if (chan->pvt->pvt)
636                 ast_log(LOG_WARNING, "Channel '%s' may not have been hung up properly\n", chan->name);
637
638         strncpy(name, chan->name, sizeof(name)-1);
639         
640         /* Stop monitoring */
641         if (chan->monitor) {
642                 chan->monitor->stop( chan, 0 );
643         }
644
645         /* If there is native format music-on-hold state, free it */
646         if(chan->music_state)
647                 ast_moh_cleanup(chan);
648
649         /* Free translatosr */
650         if (chan->pvt->readtrans)
651                 ast_translator_free_path(chan->pvt->readtrans);
652         if (chan->pvt->writetrans)
653                 ast_translator_free_path(chan->pvt->writetrans);
654         if (chan->pbx) 
655                 ast_log(LOG_WARNING, "PBX may not have been terminated properly on '%s'\n", chan->name);
656         free_cid(&chan->cid);
657         ast_mutex_destroy(&chan->lock);
658         /* Close pipes if appropriate */
659         if ((fd = chan->pvt->alertpipe[0]) > -1)
660                 close(fd);
661         if ((fd = chan->pvt->alertpipe[1]) > -1)
662                 close(fd);
663         if ((fd = chan->timingfd) > -1)
664                 close(fd);
665         f = chan->pvt->readq;
666         chan->pvt->readq = NULL;
667         while(f) {
668                 fp = f;
669                 f = f->next;
670                 ast_frfree(fp);
671         }
672         
673         /* loop over the variables list, freeing all data and deleting list items */
674         /* no need to lock the list, as the channel is already locked */
675         
676         while (!AST_LIST_EMPTY(headp)) {           /* List Deletion. */
677                     vardata = AST_LIST_REMOVE_HEAD(headp, entries);
678 /*                  printf("deleting var %s=%s\n",ast_var_name(vardata),ast_var_value(vardata)); */
679                     ast_var_delete(vardata);
680         }
681                                                          
682
683         free(chan->pvt);
684         chan->pvt = NULL;
685         free(chan);
686         ast_mutex_unlock(&chlock);
687
688         ast_device_state_changed(name);
689 }
690
691 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
692 {
693         int res = 0;
694         struct ast_frame f = { AST_FRAME_NULL };
695         if (option_debug)
696                 ast_log(LOG_DEBUG, "Soft-Hanging up channel '%s'\n", chan->name);
697         /* Inform channel driver that we need to be hung up, if it cares */
698         chan->_softhangup |= cause;
699         ast_queue_frame(chan, &f);
700         /* Interrupt any poll call or such */
701         if (ast_test_flag(chan, AST_FLAG_BLOCKING))
702                 pthread_kill(chan->blocker, SIGURG);
703         return res;
704 }
705
706 int ast_softhangup(struct ast_channel *chan, int cause)
707 {
708         int res;
709         ast_mutex_lock(&chan->lock);
710         res = ast_softhangup_nolock(chan, cause);
711         ast_mutex_unlock(&chan->lock);
712         return res;
713 }
714
715 static void free_translation(struct ast_channel *clone)
716 {
717         if (clone->pvt->writetrans)
718                 ast_translator_free_path(clone->pvt->writetrans);
719         if (clone->pvt->readtrans)
720                 ast_translator_free_path(clone->pvt->readtrans);
721         clone->pvt->writetrans = NULL;
722         clone->pvt->readtrans = NULL;
723         clone->pvt->rawwriteformat = clone->nativeformats;
724         clone->pvt->rawreadformat = clone->nativeformats;
725 }
726
727 int ast_hangup(struct ast_channel *chan)
728 {
729         int res = 0;
730         /* Don't actually hang up a channel that will masquerade as someone else, or
731            if someone is going to masquerade as us */
732         ast_mutex_lock(&chan->lock);
733         if (chan->masq) {
734                 if (ast_do_masquerade(chan)) 
735                         ast_log(LOG_WARNING, "Failed to perform masquerade\n");
736         }
737
738         if (chan->masq) {
739                 ast_log(LOG_WARNING, "%s getting hung up, but someone is trying to masq into us?!?\n", chan->name);
740                 ast_mutex_unlock(&chan->lock);
741                 return 0;
742         }
743         /* If this channel is one which will be masqueraded into something, 
744            mark it as a zombie already, so we know to free it later */
745         if (chan->masqr) {
746                 ast_set_flag(chan, AST_FLAG_ZOMBIE);
747                 ast_mutex_unlock(&chan->lock);
748                 return 0;
749         }
750         free_translation(chan);
751         if (chan->stream) 
752                 ast_closestream(chan->stream);
753         if (chan->vstream)
754                 ast_closestream(chan->vstream);
755         if (chan->sched)
756                 sched_context_destroy(chan->sched);
757         /* Clear any tone stuff remaining */
758         if (chan->generatordata)
759                 chan->generator->release(chan, chan->generatordata);
760         chan->generatordata = NULL;
761         chan->generator = NULL;
762         if (chan->cdr) {
763                 /* End the CDR if it hasn't already */
764                 ast_cdr_end(chan->cdr);
765                 /* Post and Free the CDR */
766                 ast_cdr_post(chan->cdr);
767                 ast_cdr_free(chan->cdr);
768         }
769         if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
770                 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
771                                         "is blocked by thread %ld in procedure %s!  Expect a failure\n",
772                                         (long)pthread_self(), chan->name, (long)chan->blocker, chan->blockproc);
773                 CRASH;
774         }
775         if (!ast_test_flag(chan, AST_FLAG_ZOMBIE)) {
776                 if (option_debug)
777                         ast_log(LOG_DEBUG, "Hanging up channel '%s'\n", chan->name);
778                 if (chan->pvt->hangup)
779                         res = chan->pvt->hangup(chan);
780         } else
781                 if (option_debug)
782                         ast_log(LOG_DEBUG, "Hanging up zombie '%s'\n", chan->name);
783                         
784         ast_mutex_unlock(&chan->lock);
785         manager_event(EVENT_FLAG_CALL, "Hangup", 
786                         "Channel: %s\r\n"
787                         "Uniqueid: %s\r\n"
788                         "Cause: %i\r\n",
789                         chan->name, chan->uniqueid, chan->hangupcause);
790         ast_channel_free(chan);
791         return res;
792 }
793
794 void ast_channel_unregister(const char *type)
795 {
796         struct chanlist *chan, *last=NULL;
797         if (option_debug)
798                 ast_log(LOG_DEBUG, "Unregistering channel type '%s'\n", type);
799         if (ast_mutex_lock(&chlock)) {
800                 ast_log(LOG_WARNING, "Unable to lock channel list\n");
801                 return;
802         }
803         if (option_verbose > 1)
804                 ast_verbose( VERBOSE_PREFIX_2 "Unregistered channel type '%s'\n", type);
805
806         chan = backends;
807         while(chan) {
808                 if (!strcasecmp(chan->type, type)) {
809                         if (last)
810                                 last->next = chan->next;
811                         else
812                                 backends = backends->next;
813                         free(chan);
814                         ast_mutex_unlock(&chlock);
815                         return;
816                 }
817                 last = chan;
818                 chan = chan->next;
819         }
820         ast_mutex_unlock(&chlock);
821 }
822
823 int ast_answer(struct ast_channel *chan)
824 {
825         int res = 0;
826         ast_mutex_lock(&chan->lock);
827         /* Stop if we're a zombie or need a soft hangup */
828         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
829                 ast_mutex_unlock(&chan->lock);
830                 return -1;
831         }
832         switch(chan->_state) {
833         case AST_STATE_RINGING:
834         case AST_STATE_RING:
835                 if (chan->pvt->answer)
836                         res = chan->pvt->answer(chan);
837                 ast_setstate(chan, AST_STATE_UP);
838                 if (chan->cdr)
839                         ast_cdr_answer(chan->cdr);
840                 ast_mutex_unlock(&chan->lock);
841                 return res;
842                 break;
843         case AST_STATE_UP:
844                 if (chan->cdr)
845                         ast_cdr_answer(chan->cdr);
846                 break;
847         }
848         ast_mutex_unlock(&chan->lock);
849         return 0;
850 }
851
852
853
854 void ast_deactivate_generator(struct ast_channel *chan)
855 {
856         ast_mutex_lock(&chan->lock);
857         if (chan->generatordata) {
858                 if (chan->generator && chan->generator->release) 
859                         chan->generator->release(chan, chan->generatordata);
860                 chan->generatordata = NULL;
861                 chan->generator = NULL;
862                 ast_clear_flag(chan, AST_FLAG_WRITE_INT);
863                 ast_settimeout(chan, 0, NULL, NULL);
864         }
865         ast_mutex_unlock(&chan->lock);
866 }
867
868 static int generator_force(void *data)
869 {
870         /* Called if generator doesn't have data */
871         void *tmp;
872         int res;
873         int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples);
874         struct ast_channel *chan = data;
875         tmp = chan->generatordata;
876         chan->generatordata = NULL;
877         generate = chan->generator->generate;
878         res = generate(chan, tmp, 0, 160);
879         chan->generatordata = tmp;
880         if (res) {
881                 ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
882                 ast_deactivate_generator(chan);
883         }
884         return 0;
885 }
886
887 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
888 {
889         int res = 0;
890         ast_mutex_lock(&chan->lock);
891         if (chan->generatordata) {
892                 if (chan->generator && chan->generator->release)
893                         chan->generator->release(chan, chan->generatordata);
894                 chan->generatordata = NULL;
895         }
896         ast_prod(chan);
897         if ((chan->generatordata = gen->alloc(chan, params))) {
898                 ast_settimeout(chan, 160, generator_force, chan);
899                 chan->generator = gen;
900         } else {
901                 res = -1;
902         }
903         ast_mutex_unlock(&chan->lock);
904         return res;
905 }
906
907 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
908 {
909         /* Wait for x amount of time on a file descriptor to have input.  */
910         struct timeval start, now;
911         int res;
912         int x, y;
913         int winner = -1;
914         int spoint;
915         struct pollfd *pfds;
916         
917         pfds = alloca(sizeof(struct pollfd) * n);
918         if (!pfds) {
919                 ast_log(LOG_ERROR, "Out of memory\n");
920                 return -1;
921         }
922         if (*ms > 0)
923                 gettimeofday(&start, NULL);
924         y = 0;
925         for (x=0;x<n;x++) {
926                 if (fds[x] > -1) {
927                         pfds[y].fd = fds[x];
928                         pfds[y].events = POLLIN | POLLPRI;
929                         y++;
930                 }
931         }
932         res = poll(pfds, y, *ms);
933         if (res < 0) {
934                 /* Simulate a timeout if we were interrupted */
935                 if (errno != EINTR)
936                         *ms = -1;
937                 else
938                         *ms = 0;
939                 return -1;
940         }
941         spoint = 0;
942         for (x=0;x<n;x++) {
943                 if (fds[x] > -1) {
944                         if ((res = ast_fdisset(pfds, fds[x], y, &spoint))) {
945                                 winner = fds[x];
946                                 if (exception) {
947                                         if (res & POLLPRI)
948                                                 *exception = -1;
949                                         else
950                                                 *exception = 0;
951                                 }
952                         }
953                 }
954         }
955         if (*ms > 0) {
956                 long passed;
957                 gettimeofday(&now, NULL);
958                 passed = (now.tv_sec - start.tv_sec) * 1000;
959                 passed += (now.tv_usec - start.tv_usec) / 1000;
960                 if (passed <= *ms)
961                         *ms -= passed;
962                 else
963                         *ms = 0;
964         }
965         return winner;
966 }
967
968 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds, 
969         int *exception, int *outfd, int *ms)
970 {
971         /* Wait for x amount of time on a file descriptor to have input.  */
972         struct timeval start, end;
973         struct pollfd *pfds;
974         int res;
975         long rms;
976         int x, y, max;
977         int spoint;
978         time_t now = 0;
979         long whentohangup = 0, havewhen = 0, diff;
980         struct ast_channel *winner = NULL;
981
982         pfds = alloca(sizeof(struct pollfd) * (n * AST_MAX_FDS + nfds));
983         if (!pfds) {
984                 ast_log(LOG_ERROR, "Out of memory\n");
985                 *outfd = -1;
986                 return NULL;
987         }
988
989         if (outfd)
990                 *outfd = -99999;
991         if (exception)
992                 *exception = 0;
993         
994         /* Perform any pending masquerades */
995         for (x=0;x<n;x++) {
996                 ast_mutex_lock(&c[x]->lock);
997                 if (c[x]->whentohangup) {
998                         if (!havewhen)
999                                 time(&now);
1000                         diff = c[x]->whentohangup - now;
1001                         if (!havewhen || (diff < whentohangup)) {
1002                                 havewhen++;
1003                                 whentohangup = diff;
1004                         }
1005                 }
1006                 if (c[x]->masq) {
1007                         if (ast_do_masquerade(c[x])) {
1008                                 ast_log(LOG_WARNING, "Masquerade failed\n");
1009                                 *ms = -1;
1010                                 ast_mutex_unlock(&c[x]->lock);
1011                                 return NULL;
1012                         }
1013                 }
1014                 ast_mutex_unlock(&c[x]->lock);
1015         }
1016
1017         rms = *ms;
1018         
1019         if (havewhen) {
1020                 if ((*ms < 0) || (whentohangup * 1000 < *ms)) {
1021                         rms =  whentohangup * 1000;
1022                 }
1023         }
1024         max = 0;
1025         for (x=0;x<n;x++) {
1026                 for (y=0;y<AST_MAX_FDS;y++) {
1027                         if (c[x]->fds[y] > -1) {
1028                                 pfds[max].fd = c[x]->fds[y];
1029                                 pfds[max].events = POLLIN | POLLPRI;
1030                                 max++;
1031                         }
1032                 }
1033                 CHECK_BLOCKING(c[x]);
1034         }
1035         for (x=0;x<nfds; x++) {
1036                 if (fds[x] > -1) {
1037                         pfds[max].fd = fds[x];
1038                         pfds[max].events = POLLIN | POLLPRI;
1039                         max++;
1040                 }
1041         }
1042         if (*ms > 0) 
1043                 gettimeofday(&start, NULL);
1044         res = poll(pfds, max, rms);
1045         if (res < 0) {
1046                 for (x=0;x<n;x++) 
1047                         ast_clear_flag(c[x], AST_FLAG_BLOCKING);
1048                 /* Simulate a timeout if we were interrupted */
1049                 if (errno != EINTR)
1050                         *ms = -1;
1051                 else {
1052                         /* Just an interrupt */
1053 #if 0
1054                         *ms = 0;
1055 #endif                  
1056                 }
1057                 return NULL;
1058         }
1059
1060         if (havewhen)
1061                 time(&now);
1062         spoint = 0;
1063         for (x=0;x<n;x++) {
1064                 ast_clear_flag(c[x], AST_FLAG_BLOCKING);
1065                 if (havewhen && c[x]->whentohangup && (now > c[x]->whentohangup)) {
1066                         c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1067                         if (!winner)
1068                                 winner = c[x];
1069                 }
1070                 for (y=0;y<AST_MAX_FDS;y++) {
1071                         if (c[x]->fds[y] > -1) {
1072                                 if ((res = ast_fdisset(pfds, c[x]->fds[y], max, &spoint))) {
1073                                         if (res & POLLPRI)
1074                                                 ast_set_flag(c[x], AST_FLAG_EXCEPTION);
1075                                         else
1076                                                 ast_clear_flag(c[x], AST_FLAG_EXCEPTION);
1077                                         c[x]->fdno = y;
1078                                         winner = c[x];
1079                                 }
1080                         }
1081                 }
1082         }
1083         for (x=0;x<nfds;x++) {
1084                 if (fds[x] > -1) {
1085                         if ((res = ast_fdisset(pfds, fds[x], max, &spoint))) {
1086                                 if (outfd)
1087                                         *outfd = fds[x];
1088                                 if (exception) {        
1089                                         if (res & POLLPRI) 
1090                                                 *exception = -1;
1091                                         else
1092                                                 *exception = 0;
1093                                 }
1094                                 winner = NULL;
1095                         }
1096                 }       
1097         }
1098         if (*ms > 0) {
1099                 long diff;
1100                 gettimeofday(&end, NULL);
1101                 diff = (end.tv_sec - start.tv_sec) * 1000;
1102                 diff += (end.tv_usec - start.tv_usec) / 1000;
1103                 if (diff < *ms)
1104                         *ms -= diff;
1105                 else
1106                         *ms = 0;
1107         }
1108         return winner;
1109 }
1110
1111 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
1112 {
1113         return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
1114 }
1115
1116 int ast_waitfor(struct ast_channel *c, int ms)
1117 {
1118         struct ast_channel *chan;
1119         int oldms = ms;
1120         chan = ast_waitfor_n(&c, 1, &ms);
1121         if (ms < 0) {
1122                 if (oldms < 0)
1123                         return 0;
1124                 else
1125                         return -1;
1126         }
1127         return ms;
1128 }
1129
1130 char ast_waitfordigit(struct ast_channel *c, int ms)
1131 {
1132         /* XXX Should I be merged with waitfordigit_full XXX */
1133         struct ast_frame *f;
1134         char result = 0;
1135         /* Stop if we're a zombie or need a soft hangup */
1136         if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c)) 
1137                 return -1;
1138         /* Wait for a digit, no more than ms milliseconds total. */
1139         while(ms && !result) {
1140                 ms = ast_waitfor(c, ms);
1141                 if (ms < 0) /* Error */
1142                         result = -1; 
1143                 else if (ms > 0) {
1144                         /* Read something */
1145                         f = ast_read(c);
1146                         if (f) {
1147                                 if (f->frametype == AST_FRAME_DTMF) 
1148                                         result = f->subclass;
1149                                 ast_frfree(f);
1150                         } else
1151                                 result = -1;
1152                 }
1153         }
1154         return result;
1155 }
1156
1157 int ast_settimeout(struct ast_channel *c, int samples, int (*func)(void *data), void *data)
1158 {
1159         int res = -1;
1160 #ifdef ZAPTEL_OPTIMIZATIONS
1161         if (c->timingfd > -1) {
1162                 if (!func) {
1163                         samples = 0;
1164                         data = 0;
1165                 }
1166                 ast_log(LOG_DEBUG, "Scheduling timer at %d sample intervals\n", samples);
1167                 res = ioctl(c->timingfd, ZT_TIMERCONFIG, &samples);
1168                 c->timingfunc = func;
1169                 c->timingdata = data;
1170         }
1171 #endif  
1172         return res;
1173 }
1174 char ast_waitfordigit_full(struct ast_channel *c, int ms, int audiofd, int cmdfd)
1175 {
1176         struct ast_frame *f;
1177         struct ast_channel *rchan;
1178         int outfd;
1179         int res;
1180         /* Stop if we're a zombie or need a soft hangup */
1181         if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c)) 
1182                 return -1;
1183         /* Wait for a digit, no more than ms milliseconds total. */
1184         while(ms) {
1185                 rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
1186                 if ((!rchan) && (outfd < 0) && (ms)) { 
1187                         ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
1188                         return -1;
1189                 } else if (outfd > -1) {
1190                         /* The FD we were watching has something waiting */
1191                         return 1;
1192                 } else if (rchan) {
1193                         f = ast_read(c);
1194                         if(!f) {
1195                                 return -1;
1196                         }
1197
1198                         switch(f->frametype) {
1199                         case AST_FRAME_DTMF:
1200                                 res = f->subclass;
1201                                 ast_frfree(f);
1202                                 return res;
1203                         case AST_FRAME_CONTROL:
1204                                 switch(f->subclass) {
1205                                 case AST_CONTROL_HANGUP:
1206                                         ast_frfree(f);
1207                                         return -1;
1208                                 case AST_CONTROL_RINGING:
1209                                 case AST_CONTROL_ANSWER:
1210                                         /* Unimportant */
1211                                         break;
1212                                 default:
1213                                         ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", f->subclass);
1214                                 }
1215                         case AST_FRAME_VOICE:
1216                                 /* Write audio if appropriate */
1217                                 if (audiofd > -1)
1218                                         write(audiofd, f->data, f->datalen);
1219                         }
1220                         /* Ignore */
1221                         ast_frfree(f);
1222                 }
1223         }
1224         return 0; /* Time is up */
1225 }
1226
1227 struct ast_frame *ast_read(struct ast_channel *chan)
1228 {
1229         struct ast_frame *f = NULL;
1230         int blah;
1231 #ifdef ZAPTEL_OPTIMIZATIONS
1232         int (*func)(void *);
1233         void *data;
1234         int res;
1235 #endif
1236         static struct ast_frame null_frame = 
1237         {
1238                 AST_FRAME_NULL,
1239         };
1240         
1241         ast_mutex_lock(&chan->lock);
1242         if (chan->masq) {
1243                 if (ast_do_masquerade(chan)) {
1244                         ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1245                         f = NULL;
1246                 } else
1247                         f =  &null_frame;
1248                 ast_mutex_unlock(&chan->lock);
1249                 return f;
1250         }
1251
1252         /* Stop if we're a zombie or need a soft hangup */
1253         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
1254                 if (chan->generator)
1255                         ast_deactivate_generator(chan);
1256                 ast_mutex_unlock(&chan->lock);
1257                 return NULL;
1258         }
1259
1260         if (!ast_test_flag(chan, AST_FLAG_DEFER_DTMF) && !ast_strlen_zero(chan->dtmfq)) {
1261                 /* We have DTMF that has been deferred.  Return it now */
1262                 chan->dtmff.frametype = AST_FRAME_DTMF;
1263                 chan->dtmff.subclass = chan->dtmfq[0];
1264                 /* Drop first digit */
1265                 memmove(chan->dtmfq, chan->dtmfq + 1, sizeof(chan->dtmfq) - 1);
1266                 ast_mutex_unlock(&chan->lock);
1267                 return &chan->dtmff;
1268         }
1269         
1270         /* Read and ignore anything on the alertpipe, but read only
1271            one sizeof(blah) per frame that we send from it */
1272         if (chan->pvt->alertpipe[0] > -1) {
1273                 read(chan->pvt->alertpipe[0], &blah, sizeof(blah));
1274         }
1275 #ifdef ZAPTEL_OPTIMIZATIONS
1276         if ((chan->timingfd > -1) && (chan->fdno == AST_MAX_FDS - 2) && ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
1277                 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
1278                 blah = -1;
1279                 /* IF we can't get event, assume it's an expired as-per the old interface */
1280                 res = ioctl(chan->timingfd, ZT_GETEVENT, &blah);
1281                 if (res) 
1282                         blah = ZT_EVENT_TIMER_EXPIRED;
1283
1284                 if (blah == ZT_EVENT_TIMER_PING) {
1285 #if 0
1286                         ast_log(LOG_NOTICE, "Oooh, there's a PING!\n");
1287 #endif                  
1288                         if (!chan->pvt->readq || !chan->pvt->readq->next) {
1289                                 /* Acknowledge PONG unless we need it again */
1290 #if 0
1291                                 ast_log(LOG_NOTICE, "Sending a PONG!\n");
1292 #endif                          
1293                                 if (ioctl(chan->timingfd, ZT_TIMERPONG, &blah)) {
1294                                         ast_log(LOG_WARNING, "Failed to pong timer on '%s': %s\n", chan->name, strerror(errno));
1295                                 }
1296                         }
1297                 } else if (blah == ZT_EVENT_TIMER_EXPIRED) {
1298                         ioctl(chan->timingfd, ZT_TIMERACK, &blah);
1299                         func = chan->timingfunc;
1300                         data = chan->timingdata;
1301                         ast_mutex_unlock(&chan->lock);
1302                         if (func) {
1303 #if 0
1304                                 ast_log(LOG_DEBUG, "Calling private function\n");
1305 #endif                  
1306                                 func(data);
1307                         } else {
1308                                 blah = 0;
1309                                 ast_mutex_lock(&chan->lock);
1310                                 ioctl(chan->timingfd, ZT_TIMERCONFIG, &blah);
1311                                 chan->timingdata = NULL;
1312                                 ast_mutex_unlock(&chan->lock);
1313                         }
1314                         f =  &null_frame;
1315                         return f;
1316                 } else
1317                         ast_log(LOG_NOTICE, "No/unknown event '%d' on timer for '%s'?\n", blah, chan->name);
1318         }
1319 #endif
1320         /* Check for pending read queue */
1321         if (chan->pvt->readq) {
1322                 f = chan->pvt->readq;
1323                 chan->pvt->readq = f->next;
1324                 /* Interpret hangup and return NULL */
1325                 if ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_HANGUP)) {
1326                         ast_frfree(f);
1327                         f = NULL;
1328                 }
1329         } else {
1330                 chan->blocker = pthread_self();
1331                 if (ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
1332                         if (chan->pvt->exception) 
1333                                 f = chan->pvt->exception(chan);
1334                         else {
1335                                 ast_log(LOG_WARNING, "Exception flag set on '%s', but no exception handler\n", chan->name);
1336                                 f = &null_frame;
1337                         }
1338                         /* Clear the exception flag */
1339                         ast_clear_flag(chan, AST_FLAG_EXCEPTION);
1340                 } else
1341                 if (chan->pvt->read)
1342                         f = chan->pvt->read(chan);
1343                 else
1344                         ast_log(LOG_WARNING, "No read routine on channel %s\n", chan->name);
1345         }
1346
1347
1348         if (f && (f->frametype == AST_FRAME_VOICE)) {
1349                 if (!(f->subclass & chan->nativeformats)) {
1350                         /* This frame can't be from the current native formats -- drop it on the
1351                            floor */
1352                         ast_log(LOG_NOTICE, "Dropping incompatible voice frame on %s of format %s since our native format has changed to %s\n", chan->name, ast_getformatname(f->subclass), ast_getformatname(chan->nativeformats));
1353                         ast_frfree(f);
1354                         f = &null_frame;
1355                 } else {
1356                         if (chan->monitor && chan->monitor->read_stream ) {
1357 #ifndef MONITOR_CONSTANT_DELAY
1358                                 int jump = chan->outsmpl - chan->insmpl - 2 * f->samples;
1359                                 if (jump >= 0) {
1360                                         if (ast_seekstream(chan->monitor->read_stream, jump + f->samples, SEEK_FORCECUR) == -1)
1361                                                 ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
1362                                         chan->insmpl += jump + 2 * f->samples;
1363                                 } else
1364                                         chan->insmpl+= f->samples;
1365 #else
1366                                 int jump = chan->outsmpl - chan->insmpl;
1367                                 if (jump - MONITOR_DELAY >= 0) {
1368                                         if (ast_seekstream(chan->monitor->read_stream, jump - f->samples, SEEK_FORCECUR) == -1)
1369                                                 ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
1370                                         chan->insmpl += jump;
1371                                 } else
1372                                         chan->insmpl += f->samples;
1373 #endif
1374                                 if (ast_writestream(chan->monitor->read_stream, f) < 0)
1375                                         ast_log(LOG_WARNING, "Failed to write data to channel monitor read stream\n");
1376                         }
1377                         if (chan->pvt->readtrans) {
1378                                 f = ast_translate(chan->pvt->readtrans, f, 1);
1379                                 if (!f)
1380                                         f = &null_frame;
1381                         }
1382                 }
1383         }
1384
1385         /* Make sure we always return NULL in the future */
1386         if (!f) {
1387                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1388                 if (chan->generator)
1389                         ast_deactivate_generator(chan);
1390                 /* End the CDR if appropriate */
1391                 if (chan->cdr)
1392                         ast_cdr_end(chan->cdr);
1393         } else if (ast_test_flag(chan, AST_FLAG_DEFER_DTMF) && f->frametype == AST_FRAME_DTMF) {
1394                 if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2)
1395                         chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
1396                 else
1397                         ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
1398                 f = &null_frame;
1399         } else if ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_ANSWER)) {
1400                 if (chan->_state == AST_STATE_UP) {
1401                         ast_log(LOG_DEBUG, "Dropping duplicate answer!\n");
1402                         f = &null_frame;
1403                 }
1404                 /* Answer the CDR */
1405                 ast_setstate(chan, AST_STATE_UP);
1406                 ast_cdr_answer(chan->cdr);
1407         } 
1408
1409         /* Run any generator sitting on the line */
1410         if (f && (f->frametype == AST_FRAME_VOICE) && chan->generatordata) {
1411                 /* Mask generator data temporarily and apply.  If there is a timing function, it
1412                    will be calling the generator instead */
1413                 void *tmp;
1414                 int res;
1415                 int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples);
1416                 if (chan->timingfunc) {
1417                         ast_log(LOG_DEBUG, "Generator got voice, switching to phase locked mode\n");
1418                         ast_settimeout(chan, 0, NULL, NULL);
1419                 }
1420                 tmp = chan->generatordata;
1421                 chan->generatordata = NULL;
1422                 generate = chan->generator->generate;
1423                 res = generate(chan, tmp, f->datalen, f->samples);
1424                 chan->generatordata = tmp;
1425                 if (res) {
1426                         ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
1427                         ast_deactivate_generator(chan);
1428                 }
1429         } else if (f && (f->frametype == AST_FRAME_CNG)) {
1430                 if (chan->generator && !chan->timingfunc && (chan->timingfd > -1)) {
1431                         ast_log(LOG_DEBUG, "Generator got CNG, switching to zap timed mode\n");
1432                         ast_settimeout(chan, 160, generator_force, chan);
1433                 }
1434         }
1435         if (chan->fin & 0x80000000)
1436                 ast_frame_dump(chan->name, f, "<<");
1437         if ((chan->fin & 0x7fffffff) == 0x7fffffff)
1438                 chan->fin &= 0x80000000;
1439         else
1440                 chan->fin++;
1441         ast_mutex_unlock(&chan->lock);
1442         return f;
1443 }
1444
1445 int ast_indicate(struct ast_channel *chan, int condition)
1446 {
1447         int res = -1;
1448         /* Stop if we're a zombie or need a soft hangup */
1449         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) 
1450                 return -1;
1451         ast_mutex_lock(&chan->lock);
1452         if (chan->pvt->indicate)
1453                 res = chan->pvt->indicate(chan, condition);
1454         ast_mutex_unlock(&chan->lock);
1455         if (!chan->pvt->indicate || res) {
1456                 /*
1457                  * Device does not support (that) indication, lets fake
1458                  * it by doing our own tone generation. (PM2002)
1459                  */
1460                 if (condition >= 0) {
1461                         const struct tone_zone_sound *ts = NULL;
1462                         switch (condition) {
1463                          case AST_CONTROL_RINGING:
1464                                 ts = ast_get_indication_tone(chan->zone, "ring");
1465                                 break;
1466                          case AST_CONTROL_BUSY:
1467                                 ts = ast_get_indication_tone(chan->zone, "busy");
1468                                 break;
1469                          case AST_CONTROL_CONGESTION:
1470                                 ts = ast_get_indication_tone(chan->zone, "congestion");
1471                                 break;
1472                         }
1473                         if (ts && ts->data[0]) {
1474                                 ast_log(LOG_DEBUG, "Driver for channel '%s' does not support indication %d, emulating it\n", chan->name, condition);
1475                                 ast_playtones_start(chan,0,ts->data, 1);
1476                                 res = 0;
1477                         } else if (condition == AST_CONTROL_PROGRESS) {
1478                                 /* ast_playtones_stop(chan); */
1479                         } else if (condition == AST_CONTROL_PROCEEDING) {
1480                                 /* Do nothing, really */
1481                         } else if (condition == AST_CONTROL_HOLD) {
1482                                 /* Do nothing.... */
1483                         } else if (condition == AST_CONTROL_UNHOLD) {
1484                                 /* Do nothing.... */
1485                         } else {
1486                                 /* not handled */
1487                                 ast_log(LOG_WARNING, "Unable to handle indication %d for '%s'\n", condition, chan->name);
1488                                 res = -1;
1489                         }
1490                 }
1491                 else ast_playtones_stop(chan);
1492         }
1493         return res;
1494 }
1495
1496 int ast_recvchar(struct ast_channel *chan, int timeout)
1497 {
1498         int res,ourto,c;
1499         struct ast_frame *f;
1500         
1501         ourto = timeout;
1502         for(;;)
1503            {
1504                 if (ast_check_hangup(chan)) return -1;
1505                 res = ast_waitfor(chan,ourto);
1506                 if (res <= 0) /* if timeout */
1507                    {
1508                         return 0;
1509                    }
1510                 ourto = res;
1511                 f = ast_read(chan);
1512                 if (f == NULL) return -1; /* if hangup */
1513                 if ((f->frametype == AST_FRAME_CONTROL) &&
1514                     (f->subclass == AST_CONTROL_HANGUP)) return -1; /* if hangup */
1515                 if (f->frametype == AST_FRAME_TEXT)  /* if a text frame */
1516                    {
1517                         c = *((char *)f->data);  /* get the data */
1518                         ast_frfree(f);
1519                         return(c);
1520                    }
1521                 ast_frfree(f);
1522         }
1523 }
1524
1525 int ast_sendtext(struct ast_channel *chan, char *text)
1526 {
1527         int res = 0;
1528         /* Stop if we're a zombie or need a soft hangup */
1529         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) 
1530                 return -1;
1531         CHECK_BLOCKING(chan);
1532         if (chan->pvt->send_text)
1533                 res = chan->pvt->send_text(chan, text);
1534         ast_clear_flag(chan, AST_FLAG_BLOCKING);
1535         return res;
1536 }
1537
1538 static int do_senddigit(struct ast_channel *chan, char digit)
1539 {
1540         int res = -1;
1541
1542         if (chan->pvt->send_digit)
1543                 res = chan->pvt->send_digit(chan, digit);
1544         if (!chan->pvt->send_digit || res) {
1545                 /*
1546                  * Device does not support DTMF tones, lets fake
1547                  * it by doing our own generation. (PM2002)
1548                  */
1549                 static const char* dtmf_tones[] = {
1550                         "!941+1336/100,!0/100", /* 0 */
1551                         "!697+1209/100,!0/100", /* 1 */
1552                         "!697+1336/100,!0/100", /* 2 */
1553                         "!697+1477/100,!0/100", /* 3 */
1554                         "!770+1209/100,!0/100", /* 4 */
1555                         "!770+1336/100,!0/100", /* 5 */
1556                         "!770+1477/100,!0/100", /* 6 */
1557                         "!852+1209/100,!0/100", /* 7 */
1558                         "!852+1336/100,!0/100", /* 8 */
1559                         "!852+1477/100,!0/100", /* 9 */
1560                         "!697+1633/100,!0/100", /* A */
1561                         "!770+1633/100,!0/100", /* B */
1562                         "!852+1633/100,!0/100", /* C */
1563                         "!941+1633/100,!0/100", /* D */
1564                         "!941+1209/100,!0/100", /* * */
1565                         "!941+1477/100,!0/100" };       /* # */
1566                 if (digit >= '0' && digit <='9')
1567                         ast_playtones_start(chan,0,dtmf_tones[digit-'0'], 0);
1568                 else if (digit >= 'A' && digit <= 'D')
1569                         ast_playtones_start(chan,0,dtmf_tones[digit-'A'+10], 0);
1570                 else if (digit == '*')
1571                         ast_playtones_start(chan,0,dtmf_tones[14], 0);
1572                 else if (digit == '#')
1573                         ast_playtones_start(chan,0,dtmf_tones[15], 0);
1574                 else {
1575                         /* not handled */
1576                         ast_log(LOG_DEBUG, "Unable to handle DTMF tone '%c' for '%s'\n", digit, chan->name);
1577                 }
1578         }
1579         return 0;
1580 }
1581
1582 int ast_senddigit(struct ast_channel *chan, char digit)
1583 {
1584         return do_senddigit(chan, digit);
1585 }
1586
1587 int ast_prod(struct ast_channel *chan)
1588 {
1589         struct ast_frame a = { AST_FRAME_VOICE };
1590         char nothing[128];
1591         /* Send an empty audio frame to get things moving */
1592         if (chan->_state != AST_STATE_UP) {
1593                 ast_log(LOG_DEBUG, "Prodding channel '%s'\n", chan->name);
1594                 a.subclass = chan->pvt->rawwriteformat;
1595                 a.data = nothing + AST_FRIENDLY_OFFSET;
1596                 a.src = "ast_prod";
1597                 if (ast_write(chan, &a))
1598                         ast_log(LOG_WARNING, "Prodding channel '%s' failed\n", chan->name);
1599         }
1600         return 0;
1601 }
1602
1603 int ast_write_video(struct ast_channel *chan, struct ast_frame *fr)
1604 {
1605         int res;
1606         if (!chan->pvt->write_video)
1607                 return 0;
1608         res = ast_write(chan, fr);
1609         if (!res)
1610                 res = 1;
1611         return res;
1612 }
1613
1614 int ast_write(struct ast_channel *chan, struct ast_frame *fr)
1615 {
1616         int res = -1;
1617         struct ast_frame *f = NULL;
1618         /* Stop if we're a zombie or need a soft hangup */
1619         ast_mutex_lock(&chan->lock);
1620         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))  {
1621                 ast_mutex_unlock(&chan->lock);
1622                 return -1;
1623         }
1624         /* Handle any pending masquerades */
1625         if (chan->masq) {
1626                 if (ast_do_masquerade(chan)) {
1627                         ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1628                         ast_mutex_unlock(&chan->lock);
1629                         return -1;
1630                 }
1631         }
1632         if (chan->masqr) {
1633                 ast_mutex_unlock(&chan->lock);
1634                 return 0;
1635         }
1636         if (chan->generatordata) {
1637                 if (ast_test_flag(chan, AST_FLAG_WRITE_INT))
1638                         ast_deactivate_generator(chan);
1639                 else {
1640                         ast_mutex_unlock(&chan->lock);
1641                         return 0;
1642                 }
1643         }
1644         if (chan->fout & 0x80000000)
1645                 ast_frame_dump(chan->name, fr, ">>");
1646         CHECK_BLOCKING(chan);
1647         switch(fr->frametype) {
1648         case AST_FRAME_CONTROL:
1649                 /* XXX Interpret control frames XXX */
1650                 ast_log(LOG_WARNING, "Don't know how to handle control frames yet\n");
1651                 break;
1652         case AST_FRAME_DTMF:
1653                 ast_clear_flag(chan, AST_FLAG_BLOCKING);
1654                 ast_mutex_unlock(&chan->lock);
1655                 res = do_senddigit(chan,fr->subclass);
1656                 ast_mutex_lock(&chan->lock);
1657                 CHECK_BLOCKING(chan);
1658                 break;
1659         case AST_FRAME_TEXT:
1660                 if (chan->pvt->send_text)
1661                         res = chan->pvt->send_text(chan, (char *) fr->data);
1662                 else
1663                         res = 0;
1664                 break;
1665         case AST_FRAME_HTML:
1666                 if (chan->pvt->send_html)
1667                         res = chan->pvt->send_html(chan, fr->subclass, (char *) fr->data, fr->datalen);
1668                 else
1669                         res = 0;
1670                 break;
1671         case AST_FRAME_VIDEO:
1672                 /* XXX Handle translation of video codecs one day XXX */
1673                 if (chan->pvt->write_video)
1674                         res = chan->pvt->write_video(chan, fr);
1675                 else
1676                         res = 0;
1677                 break;
1678         default:
1679                 if (chan->pvt->write) {
1680                         if (chan->pvt->writetrans) {
1681                                 f = ast_translate(chan->pvt->writetrans, fr, 0);
1682                         } else
1683                                 f = fr;
1684                         if (f) {
1685                                 res = chan->pvt->write(chan, f);
1686                                 if( chan->monitor &&
1687                                                 chan->monitor->write_stream &&
1688                                                 f && ( f->frametype == AST_FRAME_VOICE ) ) {
1689 #ifndef MONITOR_CONSTANT_DELAY
1690                                         int jump = chan->insmpl - chan->outsmpl - 2 * f->samples;
1691                                         if (jump >= 0) {
1692                                                 if (ast_seekstream(chan->monitor->write_stream, jump + f->samples, SEEK_FORCECUR) == -1)
1693                                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
1694                                                 chan->outsmpl += jump + 2 * f->samples;
1695                                         } else
1696                                                 chan->outsmpl += f->samples;
1697 #else
1698                                         int jump = chan->insmpl - chan->outsmpl;
1699                                         if (jump - MONITOR_DELAY >= 0) {
1700                                                 if (ast_seekstream(chan->monitor->write_stream, jump - f->samples, SEEK_FORCECUR) == -1)
1701                                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
1702                                                 chan->outsmpl += jump;
1703                                         } else
1704                                                 chan->outsmpl += f->samples;
1705 #endif
1706                                 if (ast_writestream(chan->monitor->write_stream, f) < 0)
1707                                                 ast_log(LOG_WARNING, "Failed to write data to channel monitor write stream\n");
1708                                 }
1709                         } else
1710                                 res = 0;
1711                 }
1712         }
1713         if (f && (f != fr))
1714                 ast_frfree(f);
1715         ast_clear_flag(chan, AST_FLAG_BLOCKING);
1716         /* Consider a write failure to force a soft hangup */
1717         if (res < 0)
1718                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1719         else {
1720                 if ((chan->fout & 0x7fffffff) == 0x7fffffff)
1721                         chan->fout &= 0x80000000;
1722                 else
1723                         chan->fout++;
1724                 chan->fout++;
1725         }
1726         ast_mutex_unlock(&chan->lock);
1727         return res;
1728 }
1729
1730 int ast_set_write_format(struct ast_channel *chan, int fmts)
1731 {
1732         int fmt;
1733         int native;
1734         int res;
1735         
1736         ast_mutex_lock(&chan->lock);
1737         native = chan->nativeformats;
1738         fmt = fmts;
1739         
1740         res = ast_translator_best_choice(&native, &fmt);
1741         if (res < 0) {
1742                 ast_log(LOG_NOTICE, "Unable to find a path from %s to %s\n",
1743                         ast_getformatname(fmts), ast_getformatname(chan->nativeformats));
1744                 ast_mutex_unlock(&chan->lock);
1745                 return -1;
1746         }
1747         
1748         /* Now we have a good choice for both.  We'll write using our native format. */
1749         chan->pvt->rawwriteformat = native;
1750         /* User perspective is fmt */
1751         chan->writeformat = fmt;
1752         /* Free any write translation we have right now */
1753         if (chan->pvt->writetrans)
1754                 ast_translator_free_path(chan->pvt->writetrans);
1755         /* Build a translation path from the user write format to the raw writing format */
1756         chan->pvt->writetrans = ast_translator_build_path(chan->pvt->rawwriteformat, chan->writeformat);
1757         if (option_debug)
1758                 ast_log(LOG_DEBUG, "Set channel %s to write format %s\n", chan->name, ast_getformatname(chan->writeformat));
1759         ast_mutex_unlock(&chan->lock);
1760         return 0;
1761 }
1762
1763 int ast_set_read_format(struct ast_channel *chan, int fmts)
1764 {
1765         int fmt;
1766         int native;
1767         int res;
1768         
1769         ast_mutex_lock(&chan->lock);
1770         native = chan->nativeformats;
1771         fmt = fmts;
1772         /* Find a translation path from the native read format to one of the user's read formats */
1773         res = ast_translator_best_choice(&fmt, &native);
1774         if (res < 0) {
1775                 ast_log(LOG_NOTICE, "Unable to find a path from %s to %s\n",
1776                         ast_getformatname(chan->nativeformats), ast_getformatname(fmts));
1777                 ast_mutex_unlock(&chan->lock);
1778                 return -1;
1779         }
1780         
1781         /* Now we have a good choice for both.  We'll write using our native format. */
1782         chan->pvt->rawreadformat = native;
1783         /* User perspective is fmt */
1784         chan->readformat = fmt;
1785         /* Free any read translation we have right now */
1786         if (chan->pvt->readtrans)
1787                 ast_translator_free_path(chan->pvt->readtrans);
1788         /* Build a translation path from the raw read format to the user reading format */
1789         chan->pvt->readtrans = ast_translator_build_path(chan->readformat, chan->pvt->rawreadformat);
1790         if (option_debug)
1791                 ast_log(LOG_DEBUG, "Set channel %s to read format %s\n", 
1792                         chan->name, ast_getformatname(chan->readformat));
1793         ast_mutex_unlock(&chan->lock);
1794         return 0;
1795 }
1796
1797 struct ast_channel *__ast_request_and_dial(const char *type, int format, void *data, int timeout, int *outstate, const char *cid_num, const char *cid_name, struct outgoing_helper *oh)
1798 {
1799         int state = 0;
1800         int cause = 0;
1801         struct ast_channel *chan;
1802         struct ast_frame *f;
1803         int res = 0;
1804         char *variable;
1805         chan = ast_request(type, format, data, &cause);
1806         if (chan) {
1807                 if (oh) {
1808                         char *tmp, *var;
1809                         /* JDG chanvar */
1810                         if (oh->variable)
1811                                 variable = ast_strdupa(oh->variable);
1812                         else
1813                                 variable = NULL;
1814                         tmp = variable;
1815                         /* FIXME replace this call with strsep  NOT*/
1816                         while( (var = strtok_r(NULL, "|", &tmp)) ) {
1817                                 pbx_builtin_setvar( chan, var );
1818                         } /* /JDG */
1819                         ast_set_callerid(chan, oh->cid_num, oh->cid_name, oh->cid_num);
1820                         if (oh->account && *oh->account)
1821                                 ast_cdr_setaccount(chan, oh->account);
1822                 }
1823                 ast_set_callerid(chan, cid_num, cid_name, cid_num);
1824
1825                 if (!ast_call(chan, data, 0)) {
1826                         while(timeout && (chan->_state != AST_STATE_UP)) {
1827                                 res = ast_waitfor(chan, timeout);
1828                                 if (res < 0) {
1829                                         /* Something not cool, or timed out */
1830                                         break;
1831                                 }
1832                                 /* If done, break out */
1833                                 if (!res)
1834                                         break;
1835                                 if (timeout > -1)
1836                                         timeout = res;
1837                                 f = ast_read(chan);
1838                                 if (!f) {
1839                                         state = AST_CONTROL_HANGUP;
1840                                         res = 0;
1841                                         break;
1842                                 }
1843                                 if (f->frametype == AST_FRAME_CONTROL) {
1844                                         if (f->subclass == AST_CONTROL_RINGING)
1845                                                 state = AST_CONTROL_RINGING;
1846                                         else if ((f->subclass == AST_CONTROL_BUSY) || (f->subclass == AST_CONTROL_CONGESTION)) {
1847                                                 state = f->subclass;
1848                                                 ast_frfree(f);
1849                                                 break;
1850                                         } else if (f->subclass == AST_CONTROL_ANSWER) {
1851                                                 state = f->subclass;
1852                                                 ast_frfree(f);
1853                                                 break;
1854                                         } else if (f->subclass == AST_CONTROL_PROGRESS) {
1855                                                 /* Ignore */
1856                                         } else if (f->subclass == -1) {
1857                                                 /* Ignore -- just stopping indications */
1858                                         } else {
1859                                                 ast_log(LOG_NOTICE, "Don't know what to do with control frame %d\n", f->subclass);
1860                                         }
1861                                 }
1862                                 ast_frfree(f);
1863                         }
1864                 } else
1865                         ast_log(LOG_NOTICE, "Unable to call channel %s/%s\n", type, (char *)data);
1866         } else {
1867                 ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
1868                 switch(cause) {
1869                 case AST_CAUSE_BUSY:
1870                         state = AST_CONTROL_BUSY;
1871                         break;
1872                 case AST_CAUSE_CONGESTION:
1873                         state = AST_CONTROL_CONGESTION;
1874                         break;
1875                 }
1876         }
1877         if (chan) {
1878                 /* Final fixups */
1879                 if (oh) {
1880                         if (oh->context && *oh->context)
1881                                 strncpy(chan->context, oh->context, sizeof(chan->context) - 1);
1882                         if (oh->exten && *oh->exten)
1883                                 strncpy(chan->exten, oh->exten, sizeof(chan->exten) - 1);
1884                         chan->priority = oh->priority;
1885                 }
1886                 if (chan->_state == AST_STATE_UP) 
1887                         state = AST_CONTROL_ANSWER;
1888         }
1889         if (outstate)
1890                 *outstate = state;
1891         if (chan && res <= 0) {
1892                 if (!chan->cdr) {
1893                         chan->cdr = ast_cdr_alloc();
1894                         if (chan->cdr)
1895                                 ast_cdr_init(chan->cdr, chan);
1896                 }
1897                 if (chan->cdr) {
1898                         char tmp[256];
1899                         snprintf(tmp, 256, "%s/%s", type, (char *)data);
1900                         ast_cdr_setapp(chan->cdr,"Dial",tmp);
1901                         ast_cdr_update(chan);
1902                         ast_cdr_start(chan->cdr);
1903                         ast_cdr_end(chan->cdr);
1904                         /* If the cause wasn't handled properly */
1905                         if (ast_cdr_disposition(chan->cdr,chan->hangupcause))
1906                                 ast_cdr_failed(chan->cdr);
1907                 } else 
1908                         ast_log(LOG_WARNING, "Unable to create Call Detail Record\n");
1909                 ast_hangup(chan);
1910                 chan = NULL;
1911         }
1912         return chan;
1913 }
1914
1915 struct ast_channel *ast_request_and_dial(const char *type, int format, void *data, int timeout, int *outstate, const char *cidnum, const char *cidname)
1916 {
1917         return __ast_request_and_dial(type, format, data, timeout, outstate, cidnum, cidname, NULL);
1918 }
1919
1920 struct ast_channel *ast_request(const char *type, int format, void *data, int *cause)
1921 {
1922         struct chanlist *chan;
1923         struct ast_channel *c = NULL;
1924         int capabilities;
1925         int fmt;
1926         int res;
1927         int foo;
1928         if (!cause)
1929                 cause = &foo;
1930         *cause = AST_CAUSE_NOTDEFINED;
1931         if (ast_mutex_lock(&chlock)) {
1932                 ast_log(LOG_WARNING, "Unable to lock channel list\n");
1933                 return NULL;
1934         }
1935         chan = backends;
1936         while(chan) {
1937                 if (!strcasecmp(type, chan->type)) {
1938                         capabilities = chan->capabilities;
1939                         fmt = format;
1940                         res = ast_translator_best_choice(&fmt, &capabilities);
1941                         if (res < 0) {
1942                                 ast_log(LOG_WARNING, "No translator path exists for channel type %s (native %d) to %d\n", type, chan->capabilities, format);
1943                                 ast_mutex_unlock(&chlock);
1944                                 return NULL;
1945                         }
1946                         ast_mutex_unlock(&chlock);
1947                         if (chan->requester)
1948                                 c = chan->requester(type, capabilities, data, cause);
1949                         if (c) {
1950                                 if (c->_state == AST_STATE_DOWN) {
1951                                         manager_event(EVENT_FLAG_CALL, "Newchannel",
1952                                         "Channel: %s\r\n"
1953                                         "State: %s\r\n"
1954                                         "CallerID: %s\r\n"
1955                                         "CallerIDName: %s\r\n"
1956                                         "Uniqueid: %s\r\n",
1957                                         c->name, ast_state2str(c->_state), c->cid.cid_num ? c->cid.cid_num : "<unknown>", c->cid.cid_name ? c->cid.cid_name : "<unknown>",c->uniqueid);
1958                                 }
1959                         }
1960                         return c;
1961                 }
1962                 chan = chan->next;
1963         }
1964         if (!chan) {
1965                 ast_log(LOG_WARNING, "No channel type registered for '%s'\n", type);
1966                 *cause = AST_CAUSE_NOSUCHDRIVER;
1967         }
1968         ast_mutex_unlock(&chlock);
1969         return c;
1970 }
1971
1972 int ast_parse_device_state(char *device)
1973 {
1974         char name[AST_CHANNEL_NAME] = "";
1975         char *cut;
1976         struct ast_channel *chan;
1977
1978         chan = ast_channel_walk_locked(NULL);
1979         while (chan) {
1980                 strncpy(name, chan->name, sizeof(name)-1);
1981                 ast_mutex_unlock(&chan->lock);
1982                 cut = strchr(name,'-');
1983                 if (cut)
1984                         *cut = 0;
1985                 if (!strcmp(name, device))
1986                         return AST_DEVICE_INUSE;
1987                 chan = ast_channel_walk_locked(chan);
1988         }
1989         return AST_DEVICE_UNKNOWN;
1990 }
1991
1992 int ast_device_state(char *device)
1993 {
1994         char tech[AST_MAX_EXTENSION] = "";
1995         char *number;
1996         struct chanlist *chanls;
1997         int res = 0;
1998         
1999         strncpy(tech, device, sizeof(tech)-1);
2000         number = strchr(tech, '/');
2001         if (!number) {
2002             return AST_DEVICE_INVALID;
2003         }
2004         *number = 0;
2005         number++;
2006                 
2007         if (ast_mutex_lock(&chlock)) {
2008                 ast_log(LOG_WARNING, "Unable to lock channel list\n");
2009                 return -1;
2010         }
2011         chanls = backends;
2012         while(chanls) {
2013                 if (!strcasecmp(tech, chanls->type)) {
2014                         ast_mutex_unlock(&chlock);
2015                         if (!chanls->devicestate) 
2016                                 return ast_parse_device_state(device);
2017                         else {
2018                                 res = chanls->devicestate(number);
2019                                 if (res == AST_DEVICE_UNKNOWN)
2020                                         return ast_parse_device_state(device);
2021                                 else
2022                                         return res;
2023                         }
2024                 }
2025                 chanls = chanls->next;
2026         }
2027         ast_mutex_unlock(&chlock);
2028         return AST_DEVICE_INVALID;
2029 }
2030
2031 int ast_call(struct ast_channel *chan, char *addr, int timeout) 
2032 {
2033         /* Place an outgoing call, but don't wait any longer than timeout ms before returning. 
2034            If the remote end does not answer within the timeout, then do NOT hang up, but 
2035            return anyway.  */
2036         int res = -1;
2037         /* Stop if we're a zombie or need a soft hangup */
2038         ast_mutex_lock(&chan->lock);
2039         if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) 
2040                 if (chan->pvt->call)
2041                         res = chan->pvt->call(chan, addr, timeout);
2042         ast_mutex_unlock(&chan->lock);
2043         return res;
2044 }
2045
2046 int ast_transfer(struct ast_channel *chan, char *dest) 
2047 {
2048         /* Place an outgoing call, but don't wait any longer than timeout ms before returning. 
2049            If the remote end does not answer within the timeout, then do NOT hang up, but 
2050            return anyway.  */
2051         int res = -1;
2052         /* Stop if we're a zombie or need a soft hangup */
2053         ast_mutex_lock(&chan->lock);
2054         if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
2055                 if (chan->pvt->transfer) {
2056                         res = chan->pvt->transfer(chan, dest);
2057                         if (!res)
2058                                 res = 1;
2059                 } else
2060                         res = 0;
2061         }
2062         ast_mutex_unlock(&chan->lock);
2063         return res;
2064 }
2065
2066 int ast_readstring(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders)
2067 {
2068         int pos=0;
2069         int to = ftimeout;
2070         char d;
2071         /* XXX Merge with full version? XXX */
2072         /* Stop if we're a zombie or need a soft hangup */
2073         if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c)) 
2074                 return -1;
2075         if (!len)
2076                 return -1;
2077         do {
2078                 if (c->stream) {
2079                         d = ast_waitstream(c, AST_DIGIT_ANY);
2080                         ast_stopstream(c);
2081                         usleep(1000);
2082                         if (!d)
2083                                 d = ast_waitfordigit(c, to);
2084                 } else {
2085                         d = ast_waitfordigit(c, to);
2086                 }
2087                 if (d < 0)
2088                         return -1;
2089                 if (d == 0) {
2090                         s[pos]='\0';
2091                         return 1;
2092                 }
2093                 if (!strchr(enders, d))
2094                         s[pos++] = d;
2095                 if (strchr(enders, d) || (pos >= len)) {
2096                         s[pos]='\0';
2097                         return 0;
2098                 }
2099                 to = timeout;
2100         } while(1);
2101         /* Never reached */
2102         return 0;
2103 }
2104
2105 int ast_readstring_full(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders, int audiofd, int ctrlfd)
2106 {
2107         int pos=0;
2108         int to = ftimeout;
2109         char d;
2110         /* Stop if we're a zombie or need a soft hangup */
2111         if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c)) 
2112                 return -1;
2113         if (!len)
2114                 return -1;
2115         do {
2116                 if (c->stream) {
2117                         d = ast_waitstream_full(c, AST_DIGIT_ANY, audiofd, ctrlfd);
2118                         ast_stopstream(c);
2119                         usleep(1000);
2120                         if (!d)
2121                                 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
2122                 } else {
2123                         d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
2124                 }
2125                 if (d < 0)
2126                         return -1;
2127                 if (d == 0) {
2128                         s[pos]='\0';
2129                         return 1;
2130                 }
2131                 if (d == 1) {
2132                         s[pos]='\0';
2133                         return 2;
2134                 }
2135                 if (!strchr(enders, d))
2136                         s[pos++] = d;
2137                 if (strchr(enders, d) || (pos >= len)) {
2138                         s[pos]='\0';
2139                         return 0;
2140                 }
2141                 to = timeout;
2142         } while(1);
2143         /* Never reached */
2144         return 0;
2145 }
2146
2147 int ast_channel_supports_html(struct ast_channel *chan)
2148 {
2149         if (chan->pvt->send_html)
2150                 return 1;
2151         return 0;
2152 }
2153
2154 int ast_channel_sendhtml(struct ast_channel *chan, int subclass, char *data, int datalen)
2155 {
2156         if (chan->pvt->send_html)
2157                 return chan->pvt->send_html(chan, subclass, data, datalen);
2158         return -1;
2159 }
2160
2161 int ast_channel_sendurl(struct ast_channel *chan, char *url)
2162 {
2163         if (chan->pvt->send_html)
2164                 return chan->pvt->send_html(chan, AST_HTML_URL, url, strlen(url) + 1);
2165         return -1;
2166 }
2167
2168 int ast_channel_make_compatible(struct ast_channel *chan, struct ast_channel *peer)
2169 {
2170         int peerf;
2171         int chanf;
2172         int res;
2173         ast_mutex_lock(&peer->lock);
2174         peerf = peer->nativeformats;
2175         ast_mutex_unlock(&peer->lock);
2176         ast_mutex_lock(&chan->lock);
2177         chanf = chan->nativeformats;
2178         ast_mutex_unlock(&chan->lock);
2179         res = ast_translator_best_choice(&peerf, &chanf);
2180         if (res < 0) {
2181                 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", chan->name, chan->nativeformats, peer->name, peer->nativeformats);
2182                 return -1;
2183         }
2184         /* Set read format on channel */
2185         res = ast_set_read_format(chan, peerf);
2186         if (res < 0) {
2187                 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", chan->name, chanf);
2188                 return -1;
2189         }
2190         /* Set write format on peer channel */
2191         res = ast_set_write_format(peer, peerf);
2192         if (res < 0) {
2193                 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", peer->name, peerf);
2194                 return -1;
2195         }
2196         /* Now we go the other way */
2197         peerf = peer->nativeformats;
2198         chanf = chan->nativeformats;
2199         res = ast_translator_best_choice(&chanf, &peerf);
2200         if (res < 0) {
2201                 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", peer->name, peer->nativeformats, chan->name, chan->nativeformats);
2202                 return -1;
2203         }
2204         /* Set writeformat on channel */
2205         res = ast_set_write_format(chan, chanf);
2206         if (res < 0) {
2207                 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", chan->name, chanf);
2208                 return -1;
2209         }
2210         /* Set read format on peer channel */
2211         res = ast_set_read_format(peer, chanf);
2212         if (res < 0) {
2213                 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", peer->name, peerf);
2214                 return -1;
2215         }
2216         return 0;
2217 }
2218
2219 int ast_channel_masquerade(struct ast_channel *original, struct ast_channel *clone)
2220 {
2221         struct ast_frame null = { AST_FRAME_NULL, };
2222         int res = -1;
2223         if (original == clone) {
2224                 ast_log(LOG_WARNING, "Can't masquerade channel '%s' into itself!\n", original->name);
2225                 return -1;
2226         }
2227         ast_mutex_lock(&original->lock);
2228         while(ast_mutex_trylock(&clone->lock)) {
2229                 ast_mutex_unlock(&original->lock);
2230                 usleep(1);
2231                 ast_mutex_lock(&original->lock);
2232         }
2233         ast_log(LOG_DEBUG, "Planning to masquerade %s into the structure of %s\n",
2234                 clone->name, original->name);
2235         if (original->masq) {
2236                 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n", 
2237                         original->masq->name, original->name);
2238         } else if (clone->masqr) {
2239                 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n", 
2240                         clone->name, clone->masqr->name);
2241         } else {
2242                 original->masq = clone;
2243                 clone->masqr = original;
2244                 ast_queue_frame(original, &null);
2245                 ast_queue_frame(clone, &null);
2246                 ast_log(LOG_DEBUG, "Done planning to masquerade %s into the structure of %s\n", original->name, clone->name);
2247                 res = 0;
2248         }
2249         ast_mutex_unlock(&clone->lock);
2250         ast_mutex_unlock(&original->lock);
2251         return res;
2252 }
2253
2254 void ast_change_name(struct ast_channel *chan, char *newname)
2255 {
2256         char tmp[256];
2257         strncpy(tmp, chan->name, sizeof(tmp) - 1);
2258         strncpy(chan->name, newname, sizeof(chan->name) - 1);
2259         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", tmp, chan->name, chan->uniqueid);
2260 }
2261
2262 void ast_channel_inherit_variables(const struct ast_channel *parent, struct ast_channel *child)
2263 {
2264         struct ast_var_t *current, *newvar;
2265         char *varname;
2266
2267         AST_LIST_TRAVERSE(&parent->varshead, current, entries) {
2268                 int vartype = 0;
2269
2270                 varname = ast_var_full_name(current);
2271                 if (!varname)
2272                         continue;
2273
2274                 if (varname[0] == '_') {
2275                         vartype = 1;
2276                         if (varname[1] == '_')
2277                                 vartype = 2;
2278                 }
2279
2280                 switch (vartype) {
2281                 case 1:
2282                         newvar = ast_var_assign(&varname[1], ast_var_value(current));
2283                         if (newvar) {
2284                                 AST_LIST_INSERT_HEAD(&child->varshead, newvar, entries);
2285                                 if (option_debug)
2286                                         ast_log(LOG_DEBUG, "Copying soft-transferable variable %s.\n", ast_var_name(newvar));
2287                         }
2288                         break;
2289                 case 2:
2290                         newvar = ast_var_assign(ast_var_full_name(current), ast_var_value(current));
2291                         if (newvar) {
2292                                 AST_LIST_INSERT_HEAD(&child->varshead, newvar, entries);
2293                                 if (option_debug)
2294                                         ast_log(LOG_DEBUG, "Copying hard-transferable variable %s.\n", ast_var_name(newvar));
2295                         }
2296                         break;
2297                 default:
2298                         if (option_debug)
2299                                 ast_log(LOG_DEBUG, "Not copying variable %s.\n", ast_var_name(current));
2300                         break;
2301                 }
2302         }
2303 }
2304
2305 /* Clone channel variables from 'clone' channel into 'original' channel
2306    All variables except those related to app_groupcount are cloned
2307    Variables are actually _removed_ from 'clone' channel, presumably
2308    because it will subsequently be destroyed.
2309    Assumes locks will be in place on both channels when called.
2310 */
2311    
2312 static void clone_variables(struct ast_channel *original, struct ast_channel *clone)
2313 {
2314         struct ast_var_t *varptr;
2315
2316         /* we need to remove all app_groupcount related variables from the original
2317            channel before merging in the clone's variables; any groups assigned to the
2318            original channel should be released, only those assigned to the clone
2319            should remain
2320         */
2321
2322         AST_LIST_TRAVERSE_SAFE_BEGIN(&original->varshead, varptr, entries) {
2323                 if (!strncmp(ast_var_name(varptr), GROUP_CATEGORY_PREFIX, strlen(GROUP_CATEGORY_PREFIX))) {
2324                         AST_LIST_REMOVE(&original->varshead, varptr, entries);
2325                         ast_var_delete(varptr);
2326                 }
2327         }
2328         AST_LIST_TRAVERSE_SAFE_END;
2329
2330         /* Append variables from clone channel into original channel */
2331         /* XXX Is this always correct?  We have to in order to keep MACROS working XXX */
2332         if (AST_LIST_FIRST(&clone->varshead))
2333                 AST_LIST_INSERT_TAIL(&original->varshead, AST_LIST_FIRST(&clone->varshead), entries);
2334 }
2335
2336 /* Assumes channel will be locked when called */
2337 int ast_do_masquerade(struct ast_channel *original)
2338 {
2339         int x,i;
2340         int res=0;
2341         int origstate;
2342         struct ast_frame *cur, *prev;
2343         struct ast_channel_pvt *p;
2344         struct ast_callerid tmpcid;
2345         struct ast_channel *clone = original->masq;
2346         int rformat = original->readformat;
2347         int wformat = original->writeformat;
2348         char newn[100];
2349         char orig[100];
2350         char masqn[100];
2351         char zombn[100];
2352
2353 #if 1
2354         ast_log(LOG_DEBUG, "Actually Masquerading %s(%d) into the structure of %s(%d)\n",
2355                 clone->name, clone->_state, original->name, original->_state);
2356 #endif
2357         /* XXX This is a seriously wacked out operation.  We're essentially putting the guts of
2358            the clone channel into the original channel.  Start by killing off the original
2359            channel's backend.   I'm not sure we're going to keep this function, because 
2360            while the features are nice, the cost is very high in terms of pure nastiness. XXX */
2361
2362         /* We need the clone's lock, too */
2363         ast_mutex_lock(&clone->lock);
2364
2365         ast_log(LOG_DEBUG, "Got clone lock on '%s' at %p\n", clone->name, &clone->lock);
2366
2367         /* Having remembered the original read/write formats, we turn off any translation on either
2368            one */
2369         free_translation(clone);
2370         free_translation(original);
2371
2372
2373         /* Unlink the masquerade */
2374         original->masq = NULL;
2375         clone->masqr = NULL;
2376         
2377         /* Save the original name */
2378         strncpy(orig, original->name, sizeof(orig) - 1);
2379         /* Save the new name */
2380         strncpy(newn, clone->name, sizeof(newn) - 1);
2381         /* Create the masq name */
2382         snprintf(masqn, sizeof(masqn), "%s<MASQ>", newn);
2383                 
2384         /* Copy the name from the clone channel */
2385         strncpy(original->name, newn, sizeof(original->name)-1);
2386
2387         /* Mangle the name of the clone channel */
2388         strncpy(clone->name, masqn, sizeof(clone->name) - 1);
2389         
2390         /* Notify any managers of the change, first the masq then the other */
2391         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", newn, masqn, clone->uniqueid);
2392         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", orig, newn, original->uniqueid);
2393
2394         /* Swap the guts */     
2395         p = original->pvt;
2396         original->pvt = clone->pvt;
2397         clone->pvt = p;
2398
2399         /* Save any pending frames on both sides.  Start by counting
2400          * how many we're going to need... */
2401         prev = NULL;
2402         cur = clone->pvt->readq;
2403         x = 0;
2404         while(cur) {
2405                 x++;
2406                 prev = cur;
2407                 cur = cur->next;
2408         }
2409         /* If we had any, prepend them to the ones already in the queue, and 
2410          * load up the alertpipe */
2411         if (prev) {
2412                 prev->next = original->pvt->readq;
2413                 original->pvt->readq = clone->pvt->readq;
2414                 clone->pvt->readq = NULL;
2415                 if (original->pvt->alertpipe[1] > -1) {
2416                         for (i=0;i<x;i++)
2417                                 write(original->pvt->alertpipe[1], &x, sizeof(x));
2418                 }
2419         }
2420         clone->_softhangup = AST_SOFTHANGUP_DEV;
2421
2422
2423         /* And of course, so does our current state.  Note we need not
2424            call ast_setstate since the event manager doesn't really consider
2425            these separate.  We do this early so that the clone has the proper
2426            state of the original channel. */
2427         origstate = original->_state;
2428         original->_state = clone->_state;
2429         clone->_state = origstate;
2430
2431         if (clone->pvt->fixup){
2432                 res = clone->pvt->fixup(original, clone);
2433                 if (res) 
2434                         ast_log(LOG_WARNING, "Fixup failed on channel %s, strange things may happen.\n", clone->name);
2435         }
2436
2437         /* Start by disconnecting the original's physical side */
2438         if (clone->pvt->hangup)
2439                 res = clone->pvt->hangup(clone);
2440         if (res) {
2441                 ast_log(LOG_WARNING, "Hangup failed!  Strange things may happen!\n");
2442                 ast_mutex_unlock(&clone->lock);
2443                 return -1;
2444         }
2445         
2446         snprintf(zombn, sizeof(zombn), "%s<ZOMBIE>", orig);
2447         /* Mangle the name of the clone channel */
2448         strncpy(clone->name, zombn, sizeof(clone->name) - 1);
2449         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", masqn, zombn, clone->uniqueid);
2450
2451         /* Update the type. */
2452         original->type = clone->type;
2453         
2454         /* Keep the same language.  */
2455         strncpy(original->language, clone->language, sizeof(original->language));
2456         /* Copy the FD's */
2457         for (x=0;x<AST_MAX_FDS;x++) {
2458                 original->fds[x] = clone->fds[x];
2459         }
2460         clone_variables(original, clone);
2461         clone->varshead.first = NULL;
2462         /* Presense of ADSI capable CPE follows clone */
2463         original->adsicpe = clone->adsicpe;
2464         /* Bridge remains the same */
2465         /* CDR fields remain the same */
2466         /* XXX What about blocking, softhangup, blocker, and lock and blockproc? XXX */
2467         /* Application and data remain the same */
2468         /* Clone exception  becomes real one, as with fdno */
2469         ast_copy_flags(original, clone, AST_FLAG_EXCEPTION);
2470         original->fdno = clone->fdno;
2471         /* Schedule context remains the same */
2472         /* Stream stuff stays the same */
2473         /* Keep the original state.  The fixup code will need to work with it most likely */
2474
2475         /* Just swap the whole structures, nevermind the allocations, they'll work themselves
2476            out. */
2477         tmpcid = original->cid;
2478         original->cid = clone->cid;
2479         clone->cid = tmpcid;
2480         
2481         /* Restore original timing file descriptor */
2482         original->fds[AST_MAX_FDS - 2] = original->timingfd;
2483         
2484         /* Our native formats are different now */
2485         original->nativeformats = clone->nativeformats;
2486         
2487         /* Context, extension, priority, app data, jump table,  remain the same */
2488         /* pvt switches.  pbx stays the same, as does next */
2489         
2490         /* Set the write format */
2491         ast_set_write_format(original, wformat);
2492
2493         /* Set the read format */
2494         ast_set_read_format(original, rformat);
2495
2496         /* Copy the music class */
2497         strncpy(original->musicclass, clone->musicclass, sizeof(original->musicclass) - 1);
2498
2499         ast_log(LOG_DEBUG, "Putting channel %s in %d/%d formats\n", original->name, wformat, rformat);
2500
2501         /* Okay.  Last thing is to let the channel driver know about all this mess, so he
2502            can fix up everything as best as possible */
2503         if (original->pvt->fixup) {
2504                 res = original->pvt->fixup(clone, original);
2505                 if (res) {
2506                         ast_log(LOG_WARNING, "Driver for '%s' could not fixup channel %s\n",
2507                                 original->type, original->name);
2508                         ast_mutex_unlock(&clone->lock);
2509                         return -1;
2510                 }
2511         } else
2512                 ast_log(LOG_WARNING, "Driver '%s' does not have a fixup routine (for %s)!  Bad things may happen.\n",
2513                         original->type, original->name);
2514         
2515         /* Now, at this point, the "clone" channel is totally F'd up.  We mark it as
2516            a zombie so nothing tries to touch it.  If it's already been marked as a
2517            zombie, then free it now (since it already is considered invalid). */
2518         if (ast_test_flag(clone, AST_FLAG_ZOMBIE)) {
2519                 ast_log(LOG_DEBUG, "Destroying clone '%s'\n", clone->name);
2520                 ast_mutex_unlock(&clone->lock);
2521                 ast_channel_free(clone);
2522                 manager_event(EVENT_FLAG_CALL, "Hangup", "Channel: %s\r\n", zombn);
2523         } else {
2524                 struct ast_frame null_frame = { AST_FRAME_NULL, };
2525                 ast_log(LOG_DEBUG, "Released clone lock on '%s'\n", clone->name);
2526                 ast_set_flag(clone, AST_FLAG_ZOMBIE);
2527                 ast_queue_frame(clone, &null_frame);
2528                 ast_mutex_unlock(&clone->lock);
2529         }
2530         
2531         /* Signal any blocker */
2532         if (ast_test_flag(original, AST_FLAG_BLOCKING))
2533                 pthread_kill(original->blocker, SIGURG);
2534         ast_log(LOG_DEBUG, "Done Masquerading %s (%d)\n",
2535                 original->name, original->_state);
2536         return 0;
2537 }
2538
2539 void ast_set_callerid(struct ast_channel *chan, const char *callerid, const char *calleridname, const char *ani)
2540 {
2541         if (callerid) {
2542                 if (chan->cid.cid_num)
2543                         free(chan->cid.cid_num);
2544                 if (ast_strlen_zero(callerid))
2545                         chan->cid.cid_num = NULL;
2546                 else
2547                         chan->cid.cid_num = strdup(callerid);
2548         }
2549         if (calleridname) {
2550                 if (chan->cid.cid_name)
2551                         free(chan->cid.cid_name);
2552                 if (ast_strlen_zero(calleridname))
2553                         chan->cid.cid_name = NULL;
2554                 else
2555                         chan->cid.cid_name = strdup(calleridname);
2556         }
2557         if (ani) {
2558                 if (chan->cid.cid_ani)
2559                         free(chan->cid.cid_ani);
2560                 if (ast_strlen_zero(ani))
2561                         chan->cid.cid_ani = NULL;
2562                 else
2563                         chan->cid.cid_ani = strdup(ani);
2564         }
2565         if (chan->cdr)
2566                 ast_cdr_setcid(chan->cdr, chan);
2567         manager_event(EVENT_FLAG_CALL, "Newcallerid", 
2568                                 "Channel: %s\r\n"
2569                                 "CallerID: %s\r\n"
2570                                 "CallerIDName: %s\r\n"
2571                                 "Uniqueid: %s\r\n",
2572                                 chan->name, chan->cid.cid_num ? 
2573                                 chan->cid.cid_num : "<Unknown>",
2574                                 chan->cid.cid_name ? 
2575                                 chan->cid.cid_name : "<Unknown>",
2576                                 chan->uniqueid);
2577 }
2578
2579 int ast_setstate(struct ast_channel *chan, int state)
2580 {
2581         if (chan->_state != state) {
2582                 int oldstate = chan->_state;
2583                 chan->_state = state;
2584                 if (oldstate == AST_STATE_DOWN) {
2585                         ast_device_state_changed(chan->name);
2586                         manager_event(EVENT_FLAG_CALL, "Newchannel",
2587                         "Channel: %s\r\n"
2588                         "State: %s\r\n"
2589                         "CallerID: %s\r\n"
2590                         "CallerIDName: %s\r\n"
2591                         "Uniqueid: %s\r\n",
2592                         chan->name, ast_state2str(chan->_state), 
2593                         chan->cid.cid_num ? chan->cid.cid_num : "<unknown>", 
2594                         chan->cid.cid_name ? chan->cid.cid_name : "<unknown>", 
2595                         chan->uniqueid);
2596                 } else {
2597                         manager_event(EVENT_FLAG_CALL, "Newstate", 
2598                                 "Channel: %s\r\n"
2599                                 "State: %s\r\n"
2600                                 "CallerID: %s\r\n"
2601                                 "CallerIDName: %s\r\n"
2602                                 "Uniqueid: %s\r\n",
2603                                 chan->name, ast_state2str(chan->_state), 
2604                                 chan->cid.cid_num ? chan->cid.cid_num : "<unknown>", 
2605                                 chan->cid.cid_name ? chan->cid.cid_name : "<unknown>", 
2606                                 chan->uniqueid);
2607                 }
2608         }
2609         return 0;
2610 }
2611
2612 static long tvdiff(struct timeval *now, struct timeval *then) 
2613 {
2614 #if 0
2615         return (((now->tv_sec * 1000) + now->tv_usec / 1000) - ((then->tv_sec * 1000) + then->tv_usec / 1000));
2616 #else
2617         return (now->tv_sec - then->tv_sec) * 1000 + (now->tv_usec - then->tv_usec) / 1000;     
2618 #endif
2619 }
2620
2621 struct ast_channel *ast_bridged_channel(struct ast_channel *chan)
2622 {
2623         struct ast_channel *bridged;
2624         bridged = chan->_bridge;
2625         if (bridged && bridged->pvt->bridged_channel) 
2626                 bridged = bridged->pvt->bridged_channel(chan, bridged);
2627         return bridged;
2628 }
2629
2630 static void bridge_playfile(struct ast_channel *chan, struct ast_channel *peer, char *sound, int remain) 
2631 {
2632         int res=0, min=0, sec=0,check=0;
2633
2634         check = ast_autoservice_start(peer);
2635         if(check) 
2636                 return;
2637
2638         if (remain > 0) {
2639                 if (remain / 60 > 1) {
2640                         min = remain / 60;
2641                         sec = remain % 60;
2642                 } else {
2643                         sec = remain;
2644                 }
2645         }
2646         
2647         if (!strcmp(sound,"timeleft")) {
2648                 res = ast_streamfile(chan, "vm-youhave", chan->language);
2649                 res = ast_waitstream(chan, "");
2650                 if (min) {
2651                         res = ast_say_number(chan, min, AST_DIGIT_ANY, chan->language, (char *) NULL);
2652                         res = ast_streamfile(chan, "queue-minutes", chan->language);
2653                         res = ast_waitstream(chan, "");
2654                 }
2655                 if (sec) {
2656                         res = ast_say_number(chan, sec, AST_DIGIT_ANY, chan->language, (char *) NULL);
2657                         res = ast_streamfile(chan, "queue-seconds", chan->language);
2658                         res = ast_waitstream(chan, "");
2659                 }
2660         } else {
2661                 res = ast_streamfile(chan, sound, chan->language);
2662                 res = ast_waitstream(chan, "");
2663         }
2664
2665         check = ast_autoservice_stop(peer);
2666 }
2667
2668 int ast_channel_bridge(struct ast_channel *c0, struct ast_channel *c1, struct ast_bridge_config *config, struct ast_frame **fo, struct ast_channel **rc) 
2669 {
2670         /* Copy voice back and forth between the two channels.  Give the peer
2671            the ability to transfer calls with '#<extension' syntax. */
2672         struct ast_channel *cs[3];
2673         int to = -1;
2674         struct ast_frame *f;
2675         struct ast_channel *who = NULL;
2676         int res=0;
2677         int nativefailed=0;
2678         int firstpass;
2679         int o0nativeformats;
2680         int o1nativeformats;
2681         struct timeval start_time,precise_now;
2682         long elapsed_ms=0, time_left_ms=0;
2683         int playit=0, playitagain=1, first_time=1;
2684
2685         *fo = NULL;
2686         firstpass = config->firstpass;
2687         config->firstpass = 0;
2688
2689         /* timestamp */
2690         gettimeofday(&start_time,NULL);
2691         time_left_ms = config->timelimit;
2692
2693         if ((ast_test_flag(&(config->features_caller), AST_FEATURE_PLAY_WARNING)) && config->start_sound && firstpass)
2694                 bridge_playfile(c0,c1,config->start_sound,time_left_ms / 1000);
2695         if ((ast_test_flag(&(config->features_callee), AST_FEATURE_PLAY_WARNING)) && config->start_sound && firstpass)
2696                 bridge_playfile(c1,c0,config->start_sound,time_left_ms / 1000);
2697
2698         /* Stop if we're a zombie or need a soft hangup */
2699         if (ast_test_flag(c0, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c0) || ast_test_flag(c1, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c1)) 
2700                 return -1;
2701         if (c0->_bridge) {
2702                 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n", 
2703                         c0->name, c0->_bridge->name);
2704                 return -1;
2705         }
2706         if (c1->_bridge) {
2707                 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n", 
2708                         c1->name, c1->_bridge->name);
2709                 return -1;
2710         }
2711         
2712         /* Keep track of bridge */
2713         c0->_bridge = c1;
2714         c1->_bridge = c0;
2715         cs[0] = c0;
2716         cs[1] = c1;
2717         
2718         manager_event(EVENT_FLAG_CALL, "Link", 
2719                         "Channel1: %s\r\n"
2720                         "Channel2: %s\r\n"
2721                         "Uniqueid1: %s\r\n"
2722                         "Uniqueid2: %s\r\n",
2723                         c0->name, c1->name, c0->uniqueid, c1->uniqueid);
2724         o1nativeformats = c1->nativeformats;
2725         o0nativeformats = c0->nativeformats;
2726         for (/* ever */;;) {
2727                 /* timestamp */
2728                 if (config->timelimit) {
2729                         gettimeofday(&precise_now,NULL);
2730                         elapsed_ms = tvdiff(&precise_now,&start_time);
2731                         time_left_ms = config->timelimit - elapsed_ms;
2732
2733                         if (playitagain && ((ast_test_flag(&(config->features_caller), AST_FEATURE_PLAY_WARNING)) || (ast_test_flag(&(config->features_callee), AST_FEATURE_PLAY_WARNING))) && (config->play_warning && time_left_ms <= config->play_warning)) { 
2734                                 /* narrowing down to the end */
2735                                 if (config->warning_freq == 0) {
2736                                         playit = 1;
2737                                         first_time=0;
2738                                         playitagain=0;
2739                                 } else if (first_time) {
2740                                         playit = 1;
2741                                         first_time=0;
2742                                 } else {
2743                                         if ((time_left_ms % config->warning_freq) <= 50) {
2744                                                 playit = 1;
2745                                         }
2746                                 }
2747                         }
2748                         if (time_left_ms <= 0) {
2749                                 if ((ast_test_flag(&(config->features_caller), AST_FEATURE_PLAY_WARNING)) && config->end_sound)
2750                                         bridge_playfile(c0,c1,config->end_sound,0);
2751                                 if ((ast_test_flag(&(config->features_callee), AST_FEATURE_PLAY_WARNING)) && config->end_sound)
2752                                         bridge_playfile(c1,c0,config->end_sound,0);
2753                                 *fo = NULL;
2754                                 if (who) *rc = who;
2755                                 res = 0;
2756                                 break;
2757                         }
2758                         if (time_left_ms >= 5000 && playit) {
2759                                 if ((ast_test_flag(&(config->features_caller), AST_FEATURE_PLAY_WARNING)) && config->warning_sound && config->play_warning)
2760                                         bridge_playfile(c0,c1,config->warning_sound,time_left_ms / 1000);
2761                                 if ((ast_test_flag(&(config->features_callee), AST_FEATURE_PLAY_WARNING)) && config->warning_sound && config->play_warning)
2762                                         bridge_playfile(c1,c0,config->warning_sound,time_left_ms / 1000);
2763                                 playit = 0;
2764                         }
2765                         
2766                 }
2767                 /* Stop if we're a zombie or need a soft hangup */
2768                 if (ast_test_flag(c0, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c0) || ast_test_flag(c1, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c1)) {
2769                         *fo = NULL;
2770                         if (who) *rc = who;
2771                         res = 0;
2772                         ast_log(LOG_DEBUG, "Bridge stops because we're zombie or need a soft hangup: c0=%s, c1=%s, flags: %s,%s,%s,%s\n",c0->name,c1->name,ast_test_flag(c0, AST_FLAG_ZOMBIE)?"Yes":"No",ast_check_hangup(c0)?"Yes":"No",ast_test_flag(c1, AST_FLAG_ZOMBIE)?"Yes":"No",ast_check_hangup(c1)?"Yes":"No");
2773                         break;
2774                 }
2775                 if (c0->pvt->bridge && config->timelimit==0 &&
2776                         (c0->pvt->bridge == c1->pvt->bridge) && !nativefailed && !c0->monitor && !c1->monitor) {
2777                                 /* Looks like they share a bridge code */
2778                         if (option_verbose > 2) 
2779                                 ast_verbose(VERBOSE_PREFIX_3 "Attempting native bridge of %s and %s\n", c0->name, c1->name);
2780                         if (!(res = c0->pvt->bridge(c0, c1, config->flags, fo, rc))) {
2781                                 c0->_bridge = NULL;
2782                                 c1->_bridge = NULL;
2783                                 manager_event(EVENT_FLAG_CALL, "Unlink", 
2784                                         "Channel1: %s\r\n"
2785                                         "Channel2: %s\r\n"
2786                                         "Uniqueid1: %s\r\n"
2787                                         "Uniqueid2: %s\r\n",
2788                                         c0->name, c1->name, c0->uniqueid, c1->uniqueid);
2789                                 ast_log(LOG_DEBUG, "Returning from native bridge, channels: %s, %s\n",c0->name ,c1->name);
2790                                 return 0;
2791                         }
2792                         /* If they return non-zero then continue on normally.  Let "-2" mean don't worry about
2793                            my not wanting to bridge */
2794                         if ((res != -2) && (res != -3))
2795                                 ast_log(LOG_WARNING, "Private bridge between %s and %s failed\n", c0->name, c1->name);
2796                         if (res != -3) nativefailed++;
2797                 }
2798         
2799                 if (((c0->writeformat != c1->readformat) || (c0->readformat != c1->writeformat) || (c0->nativeformats != o0nativeformats) || (c1->nativeformats != o1nativeformats)) &&
2800                         !(c0->generator || c1->generator))  {
2801                         if (ast_channel_make_compatible(c0, c1)) {
2802                                 ast_log(LOG_WARNING, "Can't make %s and %s compatible\n", c0->name, c1->name);
2803                                 manager_event(EVENT_FLAG_CALL, "Unlink", 
2804                                         "Channel1: %s\r\n"
2805                                         "Channel2: %s\r\n"
2806                                         "Uniqueid1: %s\r\n"
2807                                         "Uniqueid2: %s\r\n",
2808                                         c0->name, c1->name, c0->uniqueid, c1->uniqueid);
2809                                 return -1;
2810                         }
2811                         o0nativeformats = c0->nativeformats;
2812                         o1nativeformats = c1->nativeformats;
2813                 }
2814                 who = ast_waitfor_n(cs, 2, &to);
2815                 if (!who) {
2816                         ast_log(LOG_DEBUG, "Nobody there, continuing...\n"); 
2817                         continue;
2818                 }
2819                 f = ast_read(who);
2820                 if (!f) {
2821                         *fo = NULL;
2822                         *rc = who;
2823                         res = 0;
2824                         ast_log(LOG_DEBUG, "Didn't get a frame from channel: %s\n",who->name);
2825                         break;
2826                 }
2827
2828                 if ((f->frametype == AST_FRAME_CONTROL) && !(config->flags & AST_BRIDGE_IGNORE_SIGS)) {
2829                         if ((f->subclass == AST_CONTROL_HOLD) || (f->subclass == AST_CONTROL_UNHOLD)) {
2830                                 ast_indicate(who == c0 ? c1 : c0, f->subclass);
2831                         } else {
2832                                 *fo = f;
2833                                 *rc = who;
2834                                 res =  0;
2835                                 ast_log(LOG_DEBUG, "Got a FRAME_CONTROL (%d) frame on channel %s\n", f->subclass, who->name);
2836                                 break;
2837                         }
2838                 }
2839                 if ((f->frametype == AST_FRAME_VOICE) ||
2840                         (f->frametype == AST_FRAME_TEXT) ||
2841                         (f->frametype == AST_FRAME_VIDEO) || 
2842                         (f->frametype == AST_FRAME_IMAGE) ||
2843                         (f->frametype == AST_FRAME_HTML) ||
2844                         (f->frametype == AST_FRAME_DTMF)) {
2845                         if ((f->frametype == AST_FRAME_DTMF) && 
2846                                 (config->flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))) {
2847                                 if ((who == c0)) {
2848                                         if  ((config->flags & AST_BRIDGE_DTMF_CHANNEL_0)) {
2849                                                 *rc = c0;
2850                                                 *fo = f;
2851                                                 /* Take out of conference mode */
2852                                                 res = 0;
2853                                                 ast_log(LOG_DEBUG, "Got AST_BRIDGE_DTMF_CHANNEL_0 on c0 (%s)\n",c0->name);
2854                                                 break;
2855                                         } else 
2856                                                 goto tackygoto;
2857                                 } else
2858                                 if ((who == c1)) {
2859                                         if (config->flags & AST_BRIDGE_DTMF_CHANNEL_1) {
2860                                                 *rc = c1;
2861                                                 *fo = f;
2862                                                 res =  0;
2863                                                 ast_log(LOG_DEBUG, "Got AST_BRIDGE_DTMF_CHANNEL_1 on c1 (%s)\n",c1->name);
2864                                                 break;
2865                                         } else
2866                                                 goto tackygoto;
2867                                 }
2868                         } else {
2869 #if 0
2870                                 ast_log(LOG_DEBUG, "Read from %s\n", who->name);
2871                                 if (who == last) 
2872                                         ast_log(LOG_DEBUG, "Servicing channel %s twice in a row?\n", last->name);
2873                                 last = who;
2874 #endif
2875 tackygoto:
2876                                 /* Don't copy packets if there is a generator on either one, since they're
2877                                    not supposed to be listening anyway */
2878                                 if (who == c0) 
2879                                         ast_write(c1, f);
2880                                 else 
2881                                         ast_write(c0, f);
2882                         }
2883                 }
2884                 ast_frfree(f);
2885
2886                 /* Swap who gets priority */
2887                 cs[2] = cs[0];
2888                 cs[0] = cs[1];
2889                 cs[1] = cs[2];
2890         }
2891         c0->_bridge = NULL;
2892         c1->_bridge = NULL;
2893         manager_event(EVENT_FLAG_CALL, "Unlink", 
2894                                         "Channel1: %s\r\n"
2895                                         "Channel2: %s\r\n"
2896                                         "Uniqueid1: %s\r\n"
2897                                         "Uniqueid2: %s\r\n",
2898                                         c0->name, c1->name, c0->uniqueid, c1->uniqueid);
2899         ast_log(LOG_DEBUG, "Bridge stops bridging channels %s and %s\n",c0->name,c1->name);
2900         return res;
2901 }
2902
2903 int ast_channel_setoption(struct ast_channel *chan, int option, void *data, int datalen, int block)
2904 {
2905         int res;
2906         if (chan->pvt->setoption) {
2907                 res = chan->pvt->setoption(chan, option, data, datalen);
2908                 if (res < 0)
2909                         return res;
2910         } else {
2911                 errno = ENOSYS;
2912                 return -1;
2913         }
2914         if (block) {
2915                 /* XXX Implement blocking -- just wait for our option frame reply, discarding
2916                    intermediate packets. XXX */
2917                 ast_log(LOG_ERROR, "XXX Blocking not implemented yet XXX\n");
2918                 return -1;
2919         }
2920         return 0;
2921 }
2922
2923 struct tonepair_def {
2924         int freq1;
2925         int freq2;
2926         int duration;
2927         int vol;
2928 };
2929
2930 struct tonepair_state {
2931         float freq1;
2932         float freq2;
2933         float vol;
2934         int duration;
2935         int pos;
2936         int origwfmt;
2937         struct ast_frame f;
2938         unsigned char offset[AST_FRIENDLY_OFFSET];
2939         short data[4000];
2940 };
2941
2942 static void tonepair_release(struct ast_channel *chan, void *params)
2943 {
2944         struct tonepair_state *ts = params;
2945         if (chan) {
2946                 ast_set_write_format(chan, ts->origwfmt);
2947         }
2948         free(ts);
2949 }
2950
2951 static void * tonepair_alloc(struct ast_channel *chan, void *params)
2952 {
2953         struct tonepair_state *ts;
2954         struct tonepair_def *td = params;
2955         ts = malloc(sizeof(struct tonepair_state));
2956         if (!ts)
2957                 return NULL;
2958         memset(ts, 0, sizeof(struct tonepair_state));
2959         ts->origwfmt = chan->writeformat;
2960         if (ast_set_write_format(chan, AST_FORMAT_SLINEAR)) {
2961                 ast_log(LOG_WARNING, "Unable to set '%s' to signed linear format (write)\n", chan->name);
2962                 tonepair_release(NULL, ts);
2963                 ts = NULL;
2964         } else {
2965                 ts->freq1 = td->freq1;
2966                 ts->freq2 = td->freq2;
2967                 ts->duration = td->duration;
2968                 ts->vol = td->vol;
2969         }
2970         /* Let interrupts interrupt :) */
2971         ast_set_flag(chan, AST_FLAG_WRITE_INT);
2972         return ts;
2973 }
2974
2975 static int tonepair_generator(struct ast_channel *chan, void *data, int len, int samples)
2976 {
2977         struct tonepair_state *ts = data;
2978         int x;
2979
2980         /* we need to prepare a frame with 16 * timelen samples as we're 
2981          * generating SLIN audio
2982          */
2983         len = samples * 2;
2984
2985         if (len > sizeof(ts->data) / 2 - 1) {
2986                 ast_log(LOG_WARNING, "Can't generate that much data!\n");
2987                 return -1;
2988         }
2989         memset(&ts->f, 0, sizeof(ts->f));
2990         for (x=0;x<len/2;x++) {
2991                 ts->data[x] = ts->vol * (
2992                                 sin((ts->freq1 * 2.0 * M_PI / 8000.0) * (ts->pos + x)) +
2993                                 sin((ts->freq2 * 2.0 * M_PI / 8000.0) * (ts->pos + x))
2994                         );
2995         }
2996         ts->f.frametype = AST_FRAME_VOICE;
2997         ts->f.subclass = AST_FORMAT_SLINEAR;
2998         ts->f.datalen = len;
2999         ts->f.samples = samples;
3000         ts->f.offset = AST_FRIENDLY_OFFSET;
3001         ts->f.data = ts->data;
3002         ast_write(chan, &ts->f);
3003         ts->pos += x;
3004         if (ts->duration > 0) {
3005                 if (ts->pos >= ts->duration * 8)
3006                         return -1;
3007         }
3008         return 0;
3009 }
3010
3011 static struct ast_generator tonepair = {
3012         alloc: tonepair_alloc,
3013         release: tonepair_release,
3014         generate: tonepair_generator,
3015 };
3016
3017 int ast_tonepair_start(struct ast_channel *chan, int freq1, int freq2, int duration, int vol)
3018 {
3019         struct tonepair_def d = { 0, };
3020         d.freq1 = freq1;
3021         d.freq2 = freq2;
3022         d.duration = duration;
3023         if (vol < 1)
3024                 d.vol = 8192;
3025         else
3026                 d.vol = vol;
3027         if (ast_activate_generator(chan, &tonepair, &d))
3028                 return -1;
3029         return 0;
3030 }
3031
3032 void ast_tonepair_stop(struct ast_channel *chan)
3033 {
3034         ast_deactivate_generator(chan);
3035 }
3036
3037 int ast_tonepair(struct ast_channel *chan, int freq1, int freq2, int duration, int vol)
3038 {
3039         struct ast_frame *f;
3040         int res;
3041         if ((res = ast_tonepair_start(chan, freq1, freq2, duration, vol)))
3042                 return res;
3043
3044         /* Give us some wiggle room */
3045         while(chan->generatordata && (ast_waitfor(chan, 100) >= 0)) {
3046                 f = ast_read(chan);
3047                 if (f)
3048                         ast_frfree(f);
3049                 else
3050                         return -1;
3051         }
3052         return 0;
3053 }
3054
3055 ast_group_t ast_get_group(char *s)
3056 {
3057         char *copy;
3058         char *piece;
3059         char *c=NULL;
3060         int start=0, finish=0,x;
3061         ast_group_t group = 0;
3062         copy = ast_strdupa(s);
3063         if (!copy) {
3064                 ast_log(LOG_ERROR, "Out of memory\n");
3065                 return 0;
3066         }
3067         c = copy;
3068         
3069         while((piece = strsep(&c, ","))) {
3070                 if (sscanf(piece, "%d-%d", &start, &finish) == 2) {
3071                         /* Range */
3072                 } else if (sscanf(piece, "%d", &start)) {
3073                         /* Just one */
3074                         finish = start;
3075                 } else {
3076