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