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