add channel CLID info in manager Link event (bug #4548 with minor mod)
[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 res,ourto,c;
1629         struct ast_frame *f;
1630         
1631         ourto = timeout;
1632         for(;;)
1633            {
1634                 if (ast_check_hangup(chan)) return -1;
1635                 res = ast_waitfor(chan,ourto);
1636                 if (res <= 0) /* if timeout */
1637                    {
1638                         return 0;
1639                    }
1640                 ourto = res;
1641                 f = ast_read(chan);
1642                 if (f == NULL) return -1; /* if hangup */
1643                 if ((f->frametype == AST_FRAME_CONTROL) &&
1644                     (f->subclass == AST_CONTROL_HANGUP)) return -1; /* if hangup */
1645                 if (f->frametype == AST_FRAME_TEXT)  /* if a text frame */
1646                    {
1647                         c = *((char *)f->data);  /* get the data */
1648                         ast_frfree(f);
1649                         return(c);
1650                    }
1651                 ast_frfree(f);
1652         }
1653 }
1654
1655 char *ast_recvtext(struct ast_channel *chan, int timeout)
1656 {
1657         int res,ourto;
1658         struct ast_frame *f;
1659         char *buf;
1660         
1661         ourto = timeout;
1662         for(;;) {
1663                 if (ast_check_hangup(chan)) return NULL;
1664                 res = ast_waitfor(chan,ourto);
1665                 if (res <= 0) { 
1666                         /* if timeout */
1667                         return NULL;
1668                 }
1669                 ourto = res;
1670                 f = ast_read(chan);
1671                 if (f == NULL) return NULL; /* no frame */
1672                 if ((f->frametype == AST_FRAME_CONTROL) && 
1673                         (f->subclass == AST_CONTROL_HANGUP)) return NULL; /* if hangup */
1674                 if (f->frametype == AST_FRAME_TEXT) {
1675                         /* if a text frame */
1676                         buf = (char *)malloc(strlen((char *)f->data));
1677                         if (buf) {
1678                                 strcpy(buf, (char *)f->data);
1679                                 ast_frfree(f);
1680                                 return(buf);
1681                         } else {
1682                                 return NULL;
1683                         }
1684                 }
1685                 ast_frfree(f);
1686         }
1687 }
1688
1689 int ast_sendtext(struct ast_channel *chan, char *text)
1690 {
1691         int res = 0;
1692         /* Stop if we're a zombie or need a soft hangup */
1693         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) 
1694                 return -1;
1695         CHECK_BLOCKING(chan);
1696         if (chan->tech->send_text)
1697                 res = chan->tech->send_text(chan, text);
1698         ast_clear_flag(chan, AST_FLAG_BLOCKING);
1699         return res;
1700 }
1701
1702 static int do_senddigit(struct ast_channel *chan, char digit)
1703 {
1704         int res = -1;
1705
1706         if (chan->tech->send_digit)
1707                 res = chan->tech->send_digit(chan, digit);
1708         if (!chan->tech->send_digit || res) {
1709                 /*
1710                  * Device does not support DTMF tones, lets fake
1711                  * it by doing our own generation. (PM2002)
1712                  */
1713                 static const char* dtmf_tones[] = {
1714                         "!941+1336/100,!0/100", /* 0 */
1715                         "!697+1209/100,!0/100", /* 1 */
1716                         "!697+1336/100,!0/100", /* 2 */
1717                         "!697+1477/100,!0/100", /* 3 */
1718                         "!770+1209/100,!0/100", /* 4 */
1719                         "!770+1336/100,!0/100", /* 5 */
1720                         "!770+1477/100,!0/100", /* 6 */
1721                         "!852+1209/100,!0/100", /* 7 */
1722                         "!852+1336/100,!0/100", /* 8 */
1723                         "!852+1477/100,!0/100", /* 9 */
1724                         "!697+1633/100,!0/100", /* A */
1725                         "!770+1633/100,!0/100", /* B */
1726                         "!852+1633/100,!0/100", /* C */
1727                         "!941+1633/100,!0/100", /* D */
1728                         "!941+1209/100,!0/100", /* * */
1729                         "!941+1477/100,!0/100" };       /* # */
1730                 if (digit >= '0' && digit <='9')
1731                         ast_playtones_start(chan,0,dtmf_tones[digit-'0'], 0);
1732                 else if (digit >= 'A' && digit <= 'D')
1733                         ast_playtones_start(chan,0,dtmf_tones[digit-'A'+10], 0);
1734                 else if (digit == '*')
1735                         ast_playtones_start(chan,0,dtmf_tones[14], 0);
1736                 else if (digit == '#')
1737                         ast_playtones_start(chan,0,dtmf_tones[15], 0);
1738                 else {
1739                         /* not handled */
1740                         ast_log(LOG_DEBUG, "Unable to handle DTMF tone '%c' for '%s'\n", digit, chan->name);
1741                 }
1742         }
1743         return 0;
1744 }
1745
1746 int ast_senddigit(struct ast_channel *chan, char digit)
1747 {
1748         return do_senddigit(chan, digit);
1749 }
1750
1751 int ast_prod(struct ast_channel *chan)
1752 {
1753         struct ast_frame a = { AST_FRAME_VOICE };
1754         char nothing[128];
1755         /* Send an empty audio frame to get things moving */
1756         if (chan->_state != AST_STATE_UP) {
1757                 ast_log(LOG_DEBUG, "Prodding channel '%s'\n", chan->name);
1758                 a.subclass = chan->rawwriteformat;
1759                 a.data = nothing + AST_FRIENDLY_OFFSET;
1760                 a.src = "ast_prod";
1761                 if (ast_write(chan, &a))
1762                         ast_log(LOG_WARNING, "Prodding channel '%s' failed\n", chan->name);
1763         }
1764         return 0;
1765 }
1766
1767 int ast_write_video(struct ast_channel *chan, struct ast_frame *fr)
1768 {
1769         int res;
1770         if (!chan->tech->write_video)
1771                 return 0;
1772         res = ast_write(chan, fr);
1773         if (!res)
1774                 res = 1;
1775         return res;
1776 }
1777
1778 int ast_write(struct ast_channel *chan, struct ast_frame *fr)
1779 {
1780         int res = -1;
1781         struct ast_frame *f = NULL;
1782         /* Stop if we're a zombie or need a soft hangup */
1783         ast_mutex_lock(&chan->lock);
1784         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))  {
1785                 ast_mutex_unlock(&chan->lock);
1786                 return -1;
1787         }
1788         /* Handle any pending masquerades */
1789         if (chan->masq) {
1790                 if (ast_do_masquerade(chan)) {
1791                         ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1792                         ast_mutex_unlock(&chan->lock);
1793                         return -1;
1794                 }
1795         }
1796         if (chan->masqr) {
1797                 ast_mutex_unlock(&chan->lock);
1798                 return 0;
1799         }
1800         if (chan->generatordata) {
1801                 if (ast_test_flag(chan, AST_FLAG_WRITE_INT))
1802                         ast_deactivate_generator(chan);
1803                 else {
1804                         ast_mutex_unlock(&chan->lock);
1805                         return 0;
1806                 }
1807         }
1808         /* High bit prints debugging */
1809         if (chan->fout & 0x80000000)
1810                 ast_frame_dump(chan->name, fr, ">>");
1811         CHECK_BLOCKING(chan);
1812         switch(fr->frametype) {
1813         case AST_FRAME_CONTROL:
1814                 /* XXX Interpret control frames XXX */
1815                 ast_log(LOG_WARNING, "Don't know how to handle control frames yet\n");
1816                 break;
1817         case AST_FRAME_DTMF:
1818                 ast_clear_flag(chan, AST_FLAG_BLOCKING);
1819                 ast_mutex_unlock(&chan->lock);
1820                 res = do_senddigit(chan,fr->subclass);
1821                 ast_mutex_lock(&chan->lock);
1822                 CHECK_BLOCKING(chan);
1823                 break;
1824         case AST_FRAME_TEXT:
1825                 if (chan->tech->send_text)
1826                         res = chan->tech->send_text(chan, (char *) fr->data);
1827                 else
1828                         res = 0;
1829                 break;
1830         case AST_FRAME_HTML:
1831                 if (chan->tech->send_html)
1832                         res = chan->tech->send_html(chan, fr->subclass, (char *) fr->data, fr->datalen);
1833                 else
1834                         res = 0;
1835                 break;
1836         case AST_FRAME_VIDEO:
1837                 /* XXX Handle translation of video codecs one day XXX */
1838                 if (chan->tech->write_video)
1839                         res = chan->tech->write_video(chan, fr);
1840                 else
1841                         res = 0;
1842                 break;
1843         default:
1844                 if (chan->tech->write) {
1845                         if (chan->writetrans) {
1846                                 f = ast_translate(chan->writetrans, fr, 0);
1847                         } else
1848                                 f = fr;
1849                         if (f) {
1850                                 res = chan->tech->write(chan, f);
1851
1852                                 if (f->frametype == AST_FRAME_VOICE && chan->spiers) {
1853                                         struct ast_channel_spy *spying;
1854                                         for (spying = chan->spiers; spying; spying=spying->next) {
1855                                                 ast_queue_spy_frame(spying, f, 1);
1856                                         }
1857                                 }
1858
1859                                 if( chan->monitor &&
1860                                                 chan->monitor->write_stream &&
1861                                                 f && ( f->frametype == AST_FRAME_VOICE ) ) {
1862 #ifndef MONITOR_CONSTANT_DELAY
1863                                         int jump = chan->insmpl - chan->outsmpl - 2 * f->samples;
1864                                         if (jump >= 0) {
1865                                                 if (ast_seekstream(chan->monitor->write_stream, jump + f->samples, SEEK_FORCECUR) == -1)
1866                                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
1867                                                 chan->outsmpl += jump + 2 * f->samples;
1868                                         } else
1869                                                 chan->outsmpl += f->samples;
1870 #else
1871                                         int jump = chan->insmpl - chan->outsmpl;
1872                                         if (jump - MONITOR_DELAY >= 0) {
1873                                                 if (ast_seekstream(chan->monitor->write_stream, jump - f->samples, SEEK_FORCECUR) == -1)
1874                                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
1875                                                 chan->outsmpl += jump;
1876                                         } else
1877                                                 chan->outsmpl += f->samples;
1878 #endif
1879                                 if (ast_writestream(chan->monitor->write_stream, f) < 0)
1880                                                 ast_log(LOG_WARNING, "Failed to write data to channel monitor write stream\n");
1881                                 }
1882                         } else
1883                                 res = 0;
1884                 }
1885         }
1886         if (f && (f != fr))
1887                 ast_frfree(f);
1888         ast_clear_flag(chan, AST_FLAG_BLOCKING);
1889         /* Consider a write failure to force a soft hangup */
1890         if (res < 0)
1891                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1892         else {
1893                 if ((chan->fout & 0x7fffffff) == 0x7fffffff)
1894                         chan->fout &= 0x80000000;
1895                 else
1896                         chan->fout++;
1897         }
1898         ast_mutex_unlock(&chan->lock);
1899         return res;
1900 }
1901
1902 static int set_format(struct ast_channel *chan, int fmt, int *rawformat, int *format,
1903                       struct ast_trans_pvt **trans, const int direction)
1904 {
1905         int native;
1906         int res;
1907         
1908         native = chan->nativeformats;
1909         /* Find a translation path from the native format to one of the desired formats */
1910         if (!direction)
1911                 /* reading */
1912                 res = ast_translator_best_choice(&fmt, &native);
1913         else
1914                 /* writing */
1915                 res = ast_translator_best_choice(&native, &fmt);
1916
1917         if (res < 0) {
1918                 ast_log(LOG_NOTICE, "Unable to find a path from %s to %s\n",
1919                         ast_getformatname(native), ast_getformatname(fmt));
1920                 return -1;
1921         }
1922         
1923         /* Now we have a good choice for both. */
1924         ast_mutex_lock(&chan->lock);
1925         *rawformat = native;
1926         /* User perspective is fmt */
1927         *format = fmt;
1928         /* Free any read translation we have right now */
1929         if (*trans)
1930                 ast_translator_free_path(*trans);
1931         /* Build a translation path from the raw format to the desired format */
1932         if (!direction)
1933                 /* reading */
1934                 *trans = ast_translator_build_path(*format, *rawformat);
1935         else
1936                 /* writing */
1937                 *trans = ast_translator_build_path(*rawformat, *format);
1938         ast_mutex_unlock(&chan->lock);
1939         if (option_debug)
1940                 ast_log(LOG_DEBUG, "Set channel %s to %s format %s\n", chan->name,
1941                         direction ? "write" : "read", ast_getformatname(fmt));
1942         return 0;
1943 }
1944
1945 int ast_set_read_format(struct ast_channel *chan, int fmt)
1946 {
1947         return set_format(chan, fmt, &chan->rawreadformat, &chan->readformat,
1948                           &chan->readtrans, 0);
1949 }
1950
1951 int ast_set_write_format(struct ast_channel *chan, int fmt)
1952 {
1953         return set_format(chan, fmt, &chan->rawwriteformat, &chan->writeformat,
1954                           &chan->writetrans, 1);
1955 }
1956
1957 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)
1958 {
1959         int state = 0;
1960         int cause = 0;
1961         struct ast_channel *chan;
1962         struct ast_frame *f;
1963         int res = 0;
1964         char *variable;
1965         chan = ast_request(type, format, data, &cause);
1966         if (chan) {
1967                 if (oh) {
1968                         char *tmp, *var;
1969                         /* JDG chanvar */
1970                         if (oh->variable)
1971                                 variable = ast_strdupa(oh->variable);
1972                         else
1973                                 variable = NULL;
1974                         tmp = variable;
1975                         /* FIXME replace this call with strsep  NOT*/
1976                         while( (var = strtok_r(NULL, "|", &tmp)) ) {
1977                                 pbx_builtin_setvar( chan, var );
1978                         } /* /JDG */
1979                         ast_set_callerid(chan, oh->cid_num, oh->cid_name, oh->cid_num);
1980                         if (oh->account && *oh->account)
1981                                 ast_cdr_setaccount(chan, oh->account);
1982                 }
1983                 ast_set_callerid(chan, cid_num, cid_name, cid_num);
1984
1985                 if (!ast_call(chan, data, 0)) {
1986                         while(timeout && (chan->_state != AST_STATE_UP)) {
1987                                 res = ast_waitfor(chan, timeout);
1988                                 if (res < 0) {
1989                                         /* Something not cool, or timed out */
1990                                         break;
1991                                 }
1992                                 /* If done, break out */
1993                                 if (!res)
1994                                         break;
1995                                 if (timeout > -1)
1996                                         timeout = res;
1997                                 f = ast_read(chan);
1998                                 if (!f) {
1999                                         state = AST_CONTROL_HANGUP;
2000                                         res = 0;
2001                                         break;
2002                                 }
2003                                 if (f->frametype == AST_FRAME_CONTROL) {
2004                                         if (f->subclass == AST_CONTROL_RINGING)
2005                                                 state = AST_CONTROL_RINGING;
2006                                         else if ((f->subclass == AST_CONTROL_BUSY) || (f->subclass == AST_CONTROL_CONGESTION)) {
2007                                                 state = f->subclass;
2008                                                 ast_frfree(f);
2009                                                 break;
2010                                         } else if (f->subclass == AST_CONTROL_ANSWER) {
2011                                                 state = f->subclass;
2012                                                 ast_frfree(f);
2013                                                 break;
2014                                         } else if (f->subclass == AST_CONTROL_PROGRESS) {
2015                                                 /* Ignore */
2016                                         } else if (f->subclass == -1) {
2017                                                 /* Ignore -- just stopping indications */
2018                                         } else {
2019                                                 ast_log(LOG_NOTICE, "Don't know what to do with control frame %d\n", f->subclass);
2020                                         }
2021                                 }
2022                                 ast_frfree(f);
2023                         }
2024                 } else
2025                         ast_log(LOG_NOTICE, "Unable to call channel %s/%s\n", type, (char *)data);
2026         } else {
2027                 ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
2028                 switch(cause) {
2029                 case AST_CAUSE_BUSY:
2030                         state = AST_CONTROL_BUSY;
2031                         break;
2032                 case AST_CAUSE_CONGESTION:
2033                         state = AST_CONTROL_CONGESTION;
2034                         break;
2035                 }
2036         }
2037         if (chan) {
2038                 /* Final fixups */
2039                 if (oh) {
2040                         if (oh->context && *oh->context)
2041                                 ast_copy_string(chan->context, oh->context, sizeof(chan->context));
2042                         if (oh->exten && *oh->exten)
2043                                 ast_copy_string(chan->exten, oh->exten, sizeof(chan->exten));
2044                         chan->priority = oh->priority;
2045                 }
2046                 if (chan->_state == AST_STATE_UP) 
2047                         state = AST_CONTROL_ANSWER;
2048         }
2049         if (outstate)
2050                 *outstate = state;
2051         if (chan && res <= 0) {
2052                 if (!chan->cdr) {
2053                         chan->cdr = ast_cdr_alloc();
2054                         if (chan->cdr)
2055                                 ast_cdr_init(chan->cdr, chan);
2056                 }
2057                 if (chan->cdr) {
2058                         char tmp[256];
2059                         snprintf(tmp, 256, "%s/%s", type, (char *)data);
2060                         ast_cdr_setapp(chan->cdr,"Dial",tmp);
2061                         ast_cdr_update(chan);
2062                         ast_cdr_start(chan->cdr);
2063                         ast_cdr_end(chan->cdr);
2064                         /* If the cause wasn't handled properly */
2065                         if (ast_cdr_disposition(chan->cdr,chan->hangupcause))
2066                                 ast_cdr_failed(chan->cdr);
2067                 } else 
2068                         ast_log(LOG_WARNING, "Unable to create Call Detail Record\n");
2069                 ast_hangup(chan);
2070                 chan = NULL;
2071         }
2072         return chan;
2073 }
2074
2075 struct ast_channel *ast_request_and_dial(const char *type, int format, void *data, int timeout, int *outstate, const char *cidnum, const char *cidname)
2076 {
2077         return __ast_request_and_dial(type, format, data, timeout, outstate, cidnum, cidname, NULL);
2078 }
2079
2080 struct ast_channel *ast_request(const char *type, int format, void *data, int *cause)
2081 {
2082         struct chanlist *chan;
2083         struct ast_channel *c = NULL;
2084         int capabilities;
2085         int fmt;
2086         int res;
2087         int foo;
2088         if (!cause)
2089                 cause = &foo;
2090         *cause = AST_CAUSE_NOTDEFINED;
2091         if (ast_mutex_lock(&chlock)) {
2092                 ast_log(LOG_WARNING, "Unable to lock channel list\n");
2093                 return NULL;
2094         }
2095         chan = backends;
2096         while(chan) {
2097                 if (!strcasecmp(type, chan->tech->type)) {
2098                         capabilities = chan->tech->capabilities;
2099                         fmt = format;
2100                         res = ast_translator_best_choice(&fmt, &capabilities);
2101                         if (res < 0) {
2102                                 ast_log(LOG_WARNING, "No translator path exists for channel type %s (native %d) to %d\n", type, chan->tech->capabilities, format);
2103                                 ast_mutex_unlock(&chlock);
2104                                 return NULL;
2105                         }
2106                         ast_mutex_unlock(&chlock);
2107                         if (chan->tech->requester)
2108                                 c = chan->tech->requester(type, capabilities, data, cause);
2109                         if (c) {
2110                                 if (c->_state == AST_STATE_DOWN) {
2111                                         manager_event(EVENT_FLAG_CALL, "Newchannel",
2112                                         "Channel: %s\r\n"
2113                                         "State: %s\r\n"
2114                                         "CallerID: %s\r\n"
2115                                         "CallerIDName: %s\r\n"
2116                                         "Uniqueid: %s\r\n",
2117                                         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);
2118                                 }
2119                         }
2120                         return c;
2121                 }
2122                 chan = chan->next;
2123         }
2124         if (!chan) {
2125                 ast_log(LOG_WARNING, "No channel type registered for '%s'\n", type);
2126                 *cause = AST_CAUSE_NOSUCHDRIVER;
2127         }
2128         ast_mutex_unlock(&chlock);
2129         return c;
2130 }
2131
2132 int ast_parse_device_state(char *device)
2133 {
2134         char name[AST_CHANNEL_NAME] = "";
2135         char *cut;
2136         struct ast_channel *chan;
2137
2138         chan = ast_channel_walk_locked(NULL);
2139         while (chan) {
2140                 ast_copy_string(name, chan->name, sizeof(name));
2141                 ast_mutex_unlock(&chan->lock);
2142                 cut = strchr(name,'-');
2143                 if (cut)
2144                         *cut = 0;
2145                 if (!strcmp(name, device)) {
2146                         if (chan->_state == AST_STATE_RINGING) {
2147                                 return AST_DEVICE_RINGING;
2148                         } else {
2149                                 return AST_DEVICE_INUSE;
2150                         }
2151                 }
2152                 chan = ast_channel_walk_locked(chan);
2153         }
2154         return AST_DEVICE_UNKNOWN;
2155 }
2156
2157 int ast_device_state(char *device)
2158 {
2159         char tech[AST_MAX_EXTENSION] = "";
2160         char *number;
2161         struct chanlist *chanls;
2162         int res = 0;
2163         
2164         ast_copy_string(tech, device, sizeof(tech));
2165         number = strchr(tech, '/');
2166         if (!number) {
2167             return AST_DEVICE_INVALID;
2168         }
2169         *number = 0;
2170         number++;
2171                 
2172         if (ast_mutex_lock(&chlock)) {
2173                 ast_log(LOG_WARNING, "Unable to lock channel list\n");
2174                 return -1;
2175         }
2176         chanls = backends;
2177         while(chanls) {
2178                 if (!strcasecmp(tech, chanls->tech->type)) {
2179                         ast_mutex_unlock(&chlock);
2180                         if (!chanls->tech->devicestate) 
2181                                 return ast_parse_device_state(device);
2182                         else {
2183                                 res = chanls->tech->devicestate(number);
2184                                 if (res == AST_DEVICE_UNKNOWN)
2185                                         return ast_parse_device_state(device);
2186                                 else
2187                                         return res;
2188                         }
2189                 }
2190                 chanls = chanls->next;
2191         }
2192         ast_mutex_unlock(&chlock);
2193         return AST_DEVICE_INVALID;
2194 }
2195
2196 int ast_call(struct ast_channel *chan, char *addr, int timeout) 
2197 {
2198         /* Place an outgoing call, but don't wait any longer than timeout ms before returning. 
2199            If the remote end does not answer within the timeout, then do NOT hang up, but 
2200            return anyway.  */
2201         int res = -1;
2202         /* Stop if we're a zombie or need a soft hangup */
2203         ast_mutex_lock(&chan->lock);
2204         if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) 
2205                 if (chan->tech->call)
2206                         res = chan->tech->call(chan, addr, timeout);
2207         ast_mutex_unlock(&chan->lock);
2208         return res;
2209 }
2210
2211 int ast_transfer(struct ast_channel *chan, char *dest) 
2212 {
2213         /* Place an outgoing call, but don't wait any longer than timeout ms before returning. 
2214            If the remote end does not answer within the timeout, then do NOT hang up, but 
2215            return anyway.  */
2216         int res = -1;
2217         /* Stop if we're a zombie or need a soft hangup */
2218         ast_mutex_lock(&chan->lock);
2219         if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
2220                 if (chan->tech->transfer) {
2221                         res = chan->tech->transfer(chan, dest);
2222                         if (!res)
2223                                 res = 1;
2224                 } else
2225                         res = 0;
2226         }
2227         ast_mutex_unlock(&chan->lock);
2228         return res;
2229 }
2230
2231 int ast_readstring(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders)
2232 {
2233         int pos=0;
2234         int to = ftimeout;
2235         int d;
2236         /* XXX Merge with full version? XXX */
2237         /* Stop if we're a zombie or need a soft hangup */
2238         if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c)) 
2239                 return -1;
2240         if (!len)
2241                 return -1;
2242         do {
2243                 if (c->stream) {
2244                         d = ast_waitstream(c, AST_DIGIT_ANY);
2245                         ast_stopstream(c);
2246                         usleep(1000);
2247                         if (!d)
2248                                 d = ast_waitfordigit(c, to);
2249                 } else {
2250                         d = ast_waitfordigit(c, to);
2251                 }
2252                 if (d < 0)
2253                         return -1;
2254                 if (d == 0) {
2255                         s[pos]='\0';
2256                         return 1;
2257                 }
2258                 if (!strchr(enders, d))
2259                         s[pos++] = d;
2260                 if (strchr(enders, d) || (pos >= len)) {
2261                         s[pos]='\0';
2262                         return 0;
2263                 }
2264                 to = timeout;
2265         } while(1);
2266         /* Never reached */
2267         return 0;
2268 }
2269
2270 int ast_readstring_full(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders, int audiofd, int ctrlfd)
2271 {
2272         int pos=0;
2273         int to = ftimeout;
2274         int d;
2275         /* Stop if we're a zombie or need a soft hangup */
2276         if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c)) 
2277                 return -1;
2278         if (!len)
2279                 return -1;
2280         do {
2281                 if (c->stream) {
2282                         d = ast_waitstream_full(c, AST_DIGIT_ANY, audiofd, ctrlfd);
2283                         ast_stopstream(c);
2284                         usleep(1000);
2285                         if (!d)
2286                                 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
2287                 } else {
2288                         d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
2289                 }
2290                 if (d < 0)
2291                         return -1;
2292                 if (d == 0) {
2293                         s[pos]='\0';
2294                         return 1;
2295                 }
2296                 if (d == 1) {
2297                         s[pos]='\0';
2298                         return 2;
2299                 }
2300                 if (!strchr(enders, d))
2301                         s[pos++] = d;
2302                 if (strchr(enders, d) || (pos >= len)) {
2303                         s[pos]='\0';
2304                         return 0;
2305                 }
2306                 to = timeout;
2307         } while(1);
2308         /* Never reached */
2309         return 0;
2310 }
2311
2312 int ast_channel_supports_html(struct ast_channel *chan)
2313 {
2314         if (chan->tech->send_html)
2315                 return 1;
2316         return 0;
2317 }
2318
2319 int ast_channel_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
2320 {
2321         if (chan->tech->send_html)
2322                 return chan->tech->send_html(chan, subclass, data, datalen);
2323         return -1;
2324 }
2325
2326 int ast_channel_sendurl(struct ast_channel *chan, const char *url)
2327 {
2328         if (chan->tech->send_html)
2329                 return chan->tech->send_html(chan, AST_HTML_URL, url, strlen(url) + 1);
2330         return -1;
2331 }
2332
2333 int ast_channel_make_compatible(struct ast_channel *chan, struct ast_channel *peer)
2334 {
2335         int src;
2336         int dst;
2337
2338         /* Set up translation from the chan to the peer */
2339         src = chan->nativeformats;
2340         dst = peer->nativeformats;
2341         if (ast_translator_best_choice(&dst, &src) < 0) {
2342                 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", chan->name, src, peer->name, dst);
2343                 return -1;
2344         }
2345         /* if the best path is not 'pass through', then
2346            transcoding is needed; if desired, force transcode path
2347            to use SLINEAR between channels */
2348         if ((src != dst) && option_transcode_slin)
2349                 dst = AST_FORMAT_SLINEAR;
2350         if (ast_set_read_format(chan, dst) < 0) {
2351                 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", chan->name, dst);
2352                 return -1;
2353         }
2354         if (ast_set_write_format(peer, dst) < 0) {
2355                 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", peer->name, dst);
2356                 return -1;
2357         }
2358
2359         /* Set up translation from the peer to the chan */
2360         src = peer->nativeformats;
2361         dst = chan->nativeformats;
2362         if (ast_translator_best_choice(&dst, &src) < 0) {
2363                 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", peer->name, src, chan->name, dst);
2364                 return -1;
2365         }
2366         /* if the best path is not 'pass through', then
2367            transcoding is needed; if desired, force transcode path
2368            to use SLINEAR between channels */
2369         if ((src != dst) && option_transcode_slin)
2370                 dst = AST_FORMAT_SLINEAR;
2371         if (ast_set_read_format(peer, dst) < 0) {
2372                 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", peer->name, dst);
2373                 return -1;
2374         }
2375         if (ast_set_write_format(chan, dst) < 0) {
2376                 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", chan->name, dst);
2377                 return -1;
2378         }
2379         return 0;
2380 }
2381
2382 int ast_channel_masquerade(struct ast_channel *original, struct ast_channel *clone)
2383 {
2384         struct ast_frame null = { AST_FRAME_NULL, };
2385         int res = -1;
2386         if (original == clone) {
2387                 ast_log(LOG_WARNING, "Can't masquerade channel '%s' into itself!\n", original->name);
2388                 return -1;
2389         }
2390         ast_mutex_lock(&original->lock);
2391         while(ast_mutex_trylock(&clone->lock)) {
2392                 ast_mutex_unlock(&original->lock);
2393                 usleep(1);
2394                 ast_mutex_lock(&original->lock);
2395         }
2396         ast_log(LOG_DEBUG, "Planning to masquerade %s into the structure of %s\n",
2397                 clone->name, original->name);
2398         if (original->masq) {
2399                 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n", 
2400                         original->masq->name, original->name);
2401         } else if (clone->masqr) {
2402                 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n", 
2403                         clone->name, clone->masqr->name);
2404         } else {
2405                 original->masq = clone;
2406                 clone->masqr = original;
2407                 ast_queue_frame(original, &null);
2408                 ast_queue_frame(clone, &null);
2409                 ast_log(LOG_DEBUG, "Done planning to masquerade %s into the structure of %s\n", original->name, clone->name);
2410                 res = 0;
2411         }
2412         ast_mutex_unlock(&clone->lock);
2413         ast_mutex_unlock(&original->lock);
2414         return res;
2415 }
2416
2417 void ast_change_name(struct ast_channel *chan, char *newname)
2418 {
2419         char tmp[256];
2420         ast_copy_string(tmp, chan->name, sizeof(tmp));
2421         ast_copy_string(chan->name, newname, sizeof(chan->name));
2422         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", tmp, chan->name, chan->uniqueid);
2423 }
2424
2425 void ast_channel_inherit_variables(const struct ast_channel *parent, struct ast_channel *child)
2426 {
2427         struct ast_var_t *current, *newvar;
2428         char *varname;
2429
2430         AST_LIST_TRAVERSE(&parent->varshead, current, entries) {
2431                 int vartype = 0;
2432
2433                 varname = ast_var_full_name(current);
2434                 if (!varname)
2435                         continue;
2436
2437                 if (varname[0] == '_') {
2438                         vartype = 1;
2439                         if (varname[1] == '_')
2440                                 vartype = 2;
2441                 }
2442
2443                 switch (vartype) {
2444                 case 1:
2445                         newvar = ast_var_assign(&varname[1], ast_var_value(current));
2446                         if (newvar) {
2447                                 AST_LIST_INSERT_HEAD(&child->varshead, newvar, entries);
2448                                 if (option_debug)
2449                                         ast_log(LOG_DEBUG, "Copying soft-transferable variable %s.\n", ast_var_name(newvar));
2450                         }
2451                         break;
2452                 case 2:
2453                         newvar = ast_var_assign(ast_var_full_name(current), ast_var_value(current));
2454                         if (newvar) {
2455                                 AST_LIST_INSERT_HEAD(&child->varshead, newvar, entries);
2456                                 if (option_debug)
2457                                         ast_log(LOG_DEBUG, "Copying hard-transferable variable %s.\n", ast_var_name(newvar));
2458                         }
2459                         break;
2460                 default:
2461                         if (option_debug)
2462                                 ast_log(LOG_DEBUG, "Not copying variable %s.\n", ast_var_name(current));
2463                         break;
2464                 }
2465         }
2466 }
2467
2468 /* Clone channel variables from 'clone' channel into 'original' channel
2469    All variables except those related to app_groupcount are cloned
2470    Variables are actually _removed_ from 'clone' channel, presumably
2471    because it will subsequently be destroyed.
2472    Assumes locks will be in place on both channels when called.
2473 */
2474    
2475 static void clone_variables(struct ast_channel *original, struct ast_channel *clone)
2476 {
2477         struct ast_var_t *varptr;
2478
2479         /* we need to remove all app_groupcount related variables from the original
2480            channel before merging in the clone's variables; any groups assigned to the
2481            original channel should be released, only those assigned to the clone
2482            should remain
2483         */
2484
2485         AST_LIST_TRAVERSE_SAFE_BEGIN(&original->varshead, varptr, entries) {
2486                 if (!strncmp(ast_var_name(varptr), GROUP_CATEGORY_PREFIX, strlen(GROUP_CATEGORY_PREFIX))) {
2487                         AST_LIST_REMOVE(&original->varshead, varptr, entries);
2488                         ast_var_delete(varptr);
2489                 }
2490         }
2491         AST_LIST_TRAVERSE_SAFE_END;
2492
2493         /* Append variables from clone channel into original channel */
2494         /* XXX Is this always correct?  We have to in order to keep MACROS working XXX */
2495         if (AST_LIST_FIRST(&clone->varshead))
2496                 AST_LIST_INSERT_TAIL(&original->varshead, AST_LIST_FIRST(&clone->varshead), entries);
2497 }
2498
2499 /* Assumes channel will be locked when called */
2500 int ast_do_masquerade(struct ast_channel *original)
2501 {
2502         int x,i;
2503         int res=0;
2504         int origstate;
2505         struct ast_frame *cur, *prev;
2506         const struct ast_channel_tech *t;
2507         void *t_pvt;
2508         struct ast_callerid tmpcid;
2509         struct ast_channel *clone = original->masq;
2510         int rformat = original->readformat;
2511         int wformat = original->writeformat;
2512         char newn[100];
2513         char orig[100];
2514         char masqn[100];
2515         char zombn[100];
2516
2517 #if 1
2518         ast_log(LOG_DEBUG, "Actually Masquerading %s(%d) into the structure of %s(%d)\n",
2519                 clone->name, clone->_state, original->name, original->_state);
2520 #endif
2521         /* XXX This is a seriously wacked out operation.  We're essentially putting the guts of
2522            the clone channel into the original channel.  Start by killing off the original
2523            channel's backend.   I'm not sure we're going to keep this function, because 
2524            while the features are nice, the cost is very high in terms of pure nastiness. XXX */
2525
2526         /* We need the clone's lock, too */
2527         ast_mutex_lock(&clone->lock);
2528
2529         ast_log(LOG_DEBUG, "Got clone lock on '%s' at %p\n", clone->name, &clone->lock);
2530
2531         /* Having remembered the original read/write formats, we turn off any translation on either
2532            one */
2533         free_translation(clone);
2534         free_translation(original);
2535
2536
2537         /* Unlink the masquerade */
2538         original->masq = NULL;
2539         clone->masqr = NULL;
2540         
2541         /* Save the original name */
2542         ast_copy_string(orig, original->name, sizeof(orig));
2543         /* Save the new name */
2544         ast_copy_string(newn, clone->name, sizeof(newn));
2545         /* Create the masq name */
2546         snprintf(masqn, sizeof(masqn), "%s<MASQ>", newn);
2547                 
2548         /* Copy the name from the clone channel */
2549         ast_copy_string(original->name, newn, sizeof(original->name));
2550
2551         /* Mangle the name of the clone channel */
2552         ast_copy_string(clone->name, masqn, sizeof(clone->name));
2553         
2554         /* Notify any managers of the change, first the masq then the other */
2555         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", newn, masqn, clone->uniqueid);
2556         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", orig, newn, original->uniqueid);
2557
2558         /* Swap the technlogies */      
2559         t = original->tech;
2560         original->tech = clone->tech;
2561         clone->tech = t;
2562
2563         t_pvt = original->tech_pvt;
2564         original->tech_pvt = clone->tech_pvt;
2565         clone->tech_pvt = t_pvt;
2566
2567         /* Swap the readq's */
2568         cur = original->readq;
2569         original->readq = clone->readq;
2570         clone->readq = cur;
2571
2572         /* Swap the alertpipes */
2573         for (i = 0; i < 2; i++) {
2574                 x = original->alertpipe[i];
2575                 original->alertpipe[i] = clone->alertpipe[i];
2576                 clone->alertpipe[i] = x;
2577         }
2578
2579         /* Swap the raw formats */
2580         x = original->rawreadformat;
2581         original->rawreadformat = clone->rawreadformat;
2582         clone->rawreadformat = x;
2583         x = original->rawwriteformat;
2584         original->rawwriteformat = clone->rawwriteformat;
2585         clone->rawwriteformat = x;
2586
2587         /* Save any pending frames on both sides.  Start by counting
2588          * how many we're going to need... */
2589         prev = NULL;
2590         cur = clone->readq;
2591         x = 0;
2592         while(cur) {
2593                 x++;
2594                 prev = cur;
2595                 cur = cur->next;
2596         }
2597         /* If we had any, prepend them to the ones already in the queue, and 
2598          * load up the alertpipe */
2599         if (prev) {
2600                 prev->next = original->readq;
2601                 original->readq = clone->readq;
2602                 clone->readq = NULL;
2603                 if (original->alertpipe[1] > -1) {
2604                         for (i=0;i<x;i++)
2605                                 write(original->alertpipe[1], &x, sizeof(x));
2606                 }
2607         }
2608         clone->_softhangup = AST_SOFTHANGUP_DEV;
2609
2610
2611         /* And of course, so does our current state.  Note we need not
2612            call ast_setstate since the event manager doesn't really consider
2613            these separate.  We do this early so that the clone has the proper
2614            state of the original channel. */
2615         origstate = original->_state;
2616         original->_state = clone->_state;
2617         clone->_state = origstate;
2618
2619         if (clone->tech->fixup){
2620                 res = clone->tech->fixup(original, clone);
2621                 if (res) 
2622                         ast_log(LOG_WARNING, "Fixup failed on channel %s, strange things may happen.\n", clone->name);
2623         }
2624
2625         /* Start by disconnecting the original's physical side */
2626         if (clone->tech->hangup)
2627                 res = clone->tech->hangup(clone);
2628         if (res) {
2629                 ast_log(LOG_WARNING, "Hangup failed!  Strange things may happen!\n");
2630                 ast_mutex_unlock(&clone->lock);
2631                 return -1;
2632         }
2633         
2634         snprintf(zombn, sizeof(zombn), "%s<ZOMBIE>", orig);
2635         /* Mangle the name of the clone channel */
2636         ast_copy_string(clone->name, zombn, sizeof(clone->name));
2637         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", masqn, zombn, clone->uniqueid);
2638
2639         /* Update the type. */
2640         original->type = clone->type;
2641         
2642         /* Keep the same language.  */
2643         ast_copy_string(original->language, clone->language, sizeof(original->language));
2644         /* Copy the FD's */
2645         for (x=0;x<AST_MAX_FDS;x++) {
2646                 original->fds[x] = clone->fds[x];
2647         }
2648         clone_variables(original, clone);
2649         clone->varshead.first = NULL;
2650         /* Presense of ADSI capable CPE follows clone */
2651         original->adsicpe = clone->adsicpe;
2652         /* Bridge remains the same */
2653         /* CDR fields remain the same */
2654         /* XXX What about blocking, softhangup, blocker, and lock and blockproc? XXX */
2655         /* Application and data remain the same */
2656         /* Clone exception  becomes real one, as with fdno */
2657         ast_copy_flags(original, clone, AST_FLAG_EXCEPTION);
2658         original->fdno = clone->fdno;
2659         /* Schedule context remains the same */
2660         /* Stream stuff stays the same */
2661         /* Keep the original state.  The fixup code will need to work with it most likely */
2662
2663         /* Just swap the whole structures, nevermind the allocations, they'll work themselves
2664            out. */
2665         tmpcid = original->cid;
2666         original->cid = clone->cid;
2667         clone->cid = tmpcid;
2668         
2669         /* Restore original timing file descriptor */
2670         original->fds[AST_MAX_FDS - 2] = original->timingfd;
2671         
2672         /* Our native formats are different now */
2673         original->nativeformats = clone->nativeformats;
2674         
2675         /* Context, extension, priority, app data, jump table,  remain the same */
2676         /* pvt switches.  pbx stays the same, as does next */
2677         
2678         /* Set the write format */
2679         ast_set_write_format(original, wformat);
2680
2681         /* Set the read format */
2682         ast_set_read_format(original, rformat);
2683
2684         /* Copy the music class */
2685         ast_copy_string(original->musicclass, clone->musicclass, sizeof(original->musicclass));
2686
2687         ast_log(LOG_DEBUG, "Putting channel %s in %d/%d formats\n", original->name, wformat, rformat);
2688
2689         /* Okay.  Last thing is to let the channel driver know about all this mess, so he
2690            can fix up everything as best as possible */
2691         if (original->tech->fixup) {
2692                 res = original->tech->fixup(clone, original);
2693                 if (res) {
2694                         ast_log(LOG_WARNING, "Driver for '%s' could not fixup channel %s\n",
2695                                 original->type, original->name);
2696                         ast_mutex_unlock(&clone->lock);
2697                         return -1;
2698                 }
2699         } else
2700                 ast_log(LOG_WARNING, "Driver '%s' does not have a fixup routine (for %s)!  Bad things may happen.\n",
2701                         original->type, original->name);
2702         
2703         /* Now, at this point, the "clone" channel is totally F'd up.  We mark it as
2704            a zombie so nothing tries to touch it.  If it's already been marked as a
2705            zombie, then free it now (since it already is considered invalid). */
2706         if (ast_test_flag(clone, AST_FLAG_ZOMBIE)) {
2707                 ast_log(LOG_DEBUG, "Destroying clone '%s'\n", clone->name);
2708                 ast_mutex_unlock(&clone->lock);
2709                 ast_channel_free(clone);
2710                 manager_event(EVENT_FLAG_CALL, "Hangup", "Channel: %s\r\n", zombn);
2711         } else {
2712                 struct ast_frame null_frame = { AST_FRAME_NULL, };
2713                 ast_log(LOG_DEBUG, "Released clone lock on '%s'\n", clone->name);
2714                 ast_set_flag(clone, AST_FLAG_ZOMBIE);
2715                 ast_queue_frame(clone, &null_frame);
2716                 ast_mutex_unlock(&clone->lock);
2717         }
2718         
2719         /* Signal any blocker */
2720         if (ast_test_flag(original, AST_FLAG_BLOCKING))
2721                 pthread_kill(original->blocker, SIGURG);
2722         ast_log(LOG_DEBUG, "Done Masquerading %s (%d)\n",
2723                 original->name, original->_state);
2724         return 0;
2725 }
2726
2727 void ast_set_callerid(struct ast_channel *chan, const char *callerid, const char *calleridname, const char *ani)
2728 {
2729         if (callerid) {
2730                 if (chan->cid.cid_num)
2731                         free(chan->cid.cid_num);
2732                 if (ast_strlen_zero(callerid))
2733                         chan->cid.cid_num = NULL;
2734                 else
2735                         chan->cid.cid_num = strdup(callerid);
2736         }
2737         if (calleridname) {
2738                 if (chan->cid.cid_name)
2739                         free(chan->cid.cid_name);
2740                 if (ast_strlen_zero(calleridname))
2741                         chan->cid.cid_name = NULL;
2742                 else
2743                         chan->cid.cid_name = strdup(calleridname);
2744         }
2745         if (ani) {
2746                 if (chan->cid.cid_ani)
2747                         free(chan->cid.cid_ani);
2748                 if (ast_strlen_zero(ani))
2749                         chan->cid.cid_ani = NULL;
2750                 else
2751                         chan->cid.cid_ani = strdup(ani);
2752         }
2753         if (chan->cdr)
2754                 ast_cdr_setcid(chan->cdr, chan);
2755         manager_event(EVENT_FLAG_CALL, "Newcallerid", 
2756                                 "Channel: %s\r\n"
2757                                 "CallerID: %s\r\n"
2758                                 "CallerIDName: %s\r\n"
2759                                 "Uniqueid: %s\r\n",
2760                                 chan->name, chan->cid.cid_num ? 
2761                                 chan->cid.cid_num : "<Unknown>",
2762                                 chan->cid.cid_name ? 
2763                                 chan->cid.cid_name : "<Unknown>",
2764                                 chan->uniqueid);
2765 }
2766
2767 int ast_setstate(struct ast_channel *chan, int state)
2768 {
2769         if (chan->_state != state) {
2770                 int oldstate = chan->_state;
2771                 chan->_state = state;
2772                 if (oldstate == AST_STATE_DOWN) {
2773                         ast_device_state_changed(chan->name);
2774                         manager_event(EVENT_FLAG_CALL, "Newchannel",
2775                         "Channel: %s\r\n"
2776                         "State: %s\r\n"
2777                         "CallerID: %s\r\n"
2778                         "CallerIDName: %s\r\n"
2779                         "Uniqueid: %s\r\n",
2780                         chan->name, ast_state2str(chan->_state), 
2781                         chan->cid.cid_num ? chan->cid.cid_num : "<unknown>", 
2782                         chan->cid.cid_name ? chan->cid.cid_name : "<unknown>", 
2783                         chan->uniqueid);
2784                 } else {
2785                         manager_event(EVENT_FLAG_CALL, "Newstate", 
2786                                 "Channel: %s\r\n"
2787                                 "State: %s\r\n"
2788                                 "CallerID: %s\r\n"
2789                                 "CallerIDName: %s\r\n"
2790                                 "Uniqueid: %s\r\n",
2791                                 chan->name, ast_state2str(chan->_state), 
2792                                 chan->cid.cid_num ? chan->cid.cid_num : "<unknown>", 
2793                                 chan->cid.cid_name ? chan->cid.cid_name : "<unknown>", 
2794                                 chan->uniqueid);
2795                 }
2796         }
2797         return 0;
2798 }
2799
2800 static long tvdiff(struct timeval *now, struct timeval *then) 
2801 {
2802 #if 0
2803         return (((now->tv_sec * 1000) + now->tv_usec / 1000) - ((then->tv_sec * 1000) + then->tv_usec / 1000));
2804 #else
2805         return (now->tv_sec - then->tv_sec) * 1000 + (now->tv_usec - then->tv_usec) / 1000;     
2806 #endif
2807 }
2808
2809 /*--- Find bridged channel */
2810 struct ast_channel *ast_bridged_channel(struct ast_channel *chan)
2811 {
2812         struct ast_channel *bridged;
2813         bridged = chan->_bridge;
2814         if (bridged && bridged->tech->bridged_channel) 
2815                 bridged = bridged->tech->bridged_channel(chan, bridged);
2816         return bridged;
2817 }
2818
2819 static void bridge_playfile(struct ast_channel *chan, struct ast_channel *peer, char *sound, int remain) 
2820 {
2821         int res=0, min=0, sec=0,check=0;
2822
2823         check = ast_autoservice_start(peer);
2824         if(check) 
2825                 return;
2826
2827         if (remain > 0) {
2828                 if (remain / 60 > 1) {
2829                         min = remain / 60;
2830                         sec = remain % 60;
2831                 } else {
2832                         sec = remain;
2833                 }
2834         }
2835         
2836         if (!strcmp(sound,"timeleft")) {        /* Queue support */
2837                 res = ast_streamfile(chan, "vm-youhave", chan->language);
2838                 res = ast_waitstream(chan, "");
2839                 if (min) {
2840                         res = ast_say_number(chan, min, AST_DIGIT_ANY, chan->language, (char *) NULL);
2841                         res = ast_streamfile(chan, "queue-minutes", chan->language);
2842                         res = ast_waitstream(chan, "");
2843                 }
2844                 if (sec) {
2845                         res = ast_say_number(chan, sec, AST_DIGIT_ANY, chan->language, (char *) NULL);
2846                         res = ast_streamfile(chan, "queue-seconds", chan->language);
2847                         res = ast_waitstream(chan, "");
2848                 }
2849         } else {
2850                 res = ast_streamfile(chan, sound, chan->language);
2851                 res = ast_waitstream(chan, "");
2852         }
2853
2854         check = ast_autoservice_stop(peer);
2855 }
2856
2857 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)
2858 {
2859         /* Copy voice back and forth between the two channels.  Give the peer
2860            the ability to transfer calls with '#<extension' syntax. */
2861         struct ast_channel *cs[3];
2862         int to = -1;
2863         struct ast_frame *f;
2864         struct ast_channel *who = NULL;
2865         void *pvt0, *pvt1;
2866         int res=0;
2867         int o0nativeformats;
2868         int o1nativeformats;
2869         struct timeval precise_now;
2870         long elapsed_ms=0, time_left_ms=0;
2871         
2872         cs[0] = c0;
2873         cs[1] = c1;
2874         pvt0 = c0->pvt;
2875         pvt1 = c1->pvt;
2876         o0nativeformats = c0->nativeformats;
2877         o1nativeformats = c1->nativeformats;
2878
2879         for (;;) {
2880                 if ((c0->pvt != pvt0) || (c1->pvt != pvt1) ||
2881                     (o0nativeformats != c0->nativeformats) ||
2882                         (o1nativeformats != c1->nativeformats)) {
2883                         /* Check for Masquerade, codec changes, etc */
2884                         res = -3;
2885                         break;
2886                 }
2887                 /* timestamp */
2888                 if (config->timelimit) {
2889                         /* If there is a time limit, return now */
2890                         gettimeofday(&precise_now,NULL);
2891                         elapsed_ms = tvdiff(&precise_now,start_time);
2892                         time_left_ms = config->timelimit - elapsed_ms;
2893
2894                         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)) { 
2895                                 if (config->warning_freq == 0 || time_left_ms == config->play_warning || (time_left_ms % config->warning_freq) <= 50) {
2896                                         res = -3;
2897                                         break;
2898                                 }
2899                         }
2900                         if (time_left_ms <= 0) {
2901                                 res = -3;
2902                                 break;
2903                         }
2904                         if (time_left_ms >= 5000 && *playit) {
2905                                 res = -3;
2906                                 break;
2907                         }
2908                         
2909                 }
2910
2911                 who = ast_waitfor_n(cs, 2, &to);
2912                 if (!who) {
2913                         ast_log(LOG_DEBUG, "Nobody there, continuing...\n"); 
2914                         if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE || c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE) {
2915                                 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
2916                                         c0->_softhangup = 0;
2917                                 if (c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
2918                                         c1->_softhangup = 0;
2919                                 c0->_bridge = c1;
2920                                 c1->_bridge = c0;
2921                                 continue;
2922                         }
2923                         continue;
2924                 }
2925                 f = ast_read(who);
2926                 if (!f) {
2927                         *fo = NULL;
2928                         *rc = who;
2929                         res = 0;
2930                         ast_log(LOG_DEBUG, "Didn't get a frame from channel: %s\n",who->name);
2931                         break;
2932                 }
2933
2934                 if ((f->frametype == AST_FRAME_CONTROL) && !(config->flags & AST_BRIDGE_IGNORE_SIGS)) {
2935                         if ((f->subclass == AST_CONTROL_HOLD) || (f->subclass == AST_CONTROL_UNHOLD)) {
2936                                 ast_indicate(who == c0 ? c1 : c0, f->subclass);
2937                         } else {
2938                                 *fo = f;
2939                                 *rc = who;
2940                                 res =  0;
2941                                 ast_log(LOG_DEBUG, "Got a FRAME_CONTROL (%d) frame on channel %s\n", f->subclass, who->name);
2942                                 break;
2943                         }
2944                 }
2945                 if ((f->frametype == AST_FRAME_VOICE) ||
2946                         (f->frametype == AST_FRAME_TEXT) ||
2947                         (f->frametype == AST_FRAME_VIDEO) || 
2948                         (f->frametype == AST_FRAME_IMAGE) ||
2949                         (f->frametype == AST_FRAME_HTML) ||
2950                         (f->frametype == AST_FRAME_DTMF)) {
2951
2952                         if ((f->frametype == AST_FRAME_DTMF) && 
2953                                 (config->flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))) {
2954                                 if ((who == c0)) {
2955                                         if  ((config->flags & AST_BRIDGE_DTMF_CHANNEL_0)) {
2956                                                 *rc = c0;
2957                                                 *fo = f;
2958                                                 /* Take out of conference mode */
2959                                                 res = 0;
2960                                                 ast_log(LOG_DEBUG, "Got AST_BRIDGE_DTMF_CHANNEL_0 on c0 (%s)\n",c0->name);
2961                                                 break;
2962                                         } else 
2963                                                 goto tackygoto;
2964                                 } else
2965                                 if ((who == c1)) {
2966                                         if (config->flags & AST_BRIDGE_DTMF_CHANNEL_1) {
2967                                                 *rc = c1;
2968                                                 *fo = f;
2969                                                 res =  0;
2970                                                 ast_log(LOG_DEBUG, "Got AST_BRIDGE_DTMF_CHANNEL_1 on c1 (%s)\n",c1->name);
2971                                                 break;
2972                                         } else
2973                                                 goto tackygoto;
2974                                 }
2975                         } else {
2976 #if 0
2977                                 ast_log(LOG_DEBUG, "Read from %s\n", who->name);
2978                                 if (who == last) 
2979                                         ast_log(LOG_DEBUG, "Servicing channel %s twice in a row?\n", last->name);
2980                                 last = who;
2981 #endif
2982 tackygoto:
2983                                 /* Don't copy packets if there is a generator on either one, since they're
2984                                    not supposed to be listening anyway */
2985                                 if (who == c0) 
2986                                         ast_write(c1, f);
2987                                 else 
2988                                         ast_write(c0, f);
2989                         }
2990                 }
2991                 ast_frfree(f);
2992
2993                 /* Swap who gets priority */
2994                 cs[2] = cs[0];
2995                 cs[0] = cs[1];
2996                 cs[1] = cs[2];
2997         }
2998         return res;
2999 }
3000
3001 /*--- ast_channel_bridge: Bridge two channels together */
3002 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) 
3003 {
3004         /* Copy voice back and forth between the two channels.  Give the peer
3005            the ability to transfer calls with '#<extension' syntax. */
3006         struct ast_channel *cs[3];
3007         struct ast_channel *who = NULL;
3008         int res=0;
3009         int nativefailed=0;
3010         int firstpass;
3011         int o0nativeformats;
3012         int o1nativeformats;
3013         struct timeval start_time,precise_now;
3014         long elapsed_ms=0, time_left_ms=0;
3015         int playit=0, playitagain=1, first_time=1;
3016
3017         *fo = NULL;
3018         firstpass = config->firstpass;
3019         config->firstpass = 0;
3020
3021         /* timestamp */
3022         gettimeofday(&start_time,NULL);
3023         time_left_ms = config->timelimit;
3024
3025         if ((ast_test_flag(&(config->features_caller), AST_FEATURE_PLAY_WARNING)) && config->start_sound && firstpass)
3026                 bridge_playfile(c0,c1,config->start_sound,time_left_ms / 1000);
3027         if ((ast_test_flag(&(config->features_callee), AST_FEATURE_PLAY_WARNING)) && config->start_sound && firstpass)
3028                 bridge_playfile(c1,c0,config->start_sound,time_left_ms / 1000);
3029
3030         /* Stop if we're a zombie or need a soft hangup */
3031         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)) 
3032                 return -1;
3033         if (c0->_bridge) {
3034                 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n", 
3035                         c0->name, c0->_bridge->name);
3036                 return -1;
3037         }
3038         if (c1->_bridge) {
3039                 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n", 
3040                         c1->name, c1->_bridge->name);
3041                 return -1;
3042         }
3043         
3044         /* Keep track of bridge */
3045         c0->_bridge = c1;
3046         c1->_bridge = c0;
3047         cs[0] = c0;
3048         cs[1] = c1;
3049         
3050         manager_event(EVENT_FLAG_CALL, "Link", 
3051                         "Channel1: %s\r\n"
3052                         "Channel2: %s\r\n"
3053                         "Uniqueid1: %s\r\n"
3054                         "Uniqueid2: %s\r\n"
3055                         "CallerID1: %s\r\n"
3056                         "CallerID2: %s\r\n",
3057                         c0->name, c1->name, c0->uniqueid, c1->uniqueid, c0->cid.cid_num, c1->cid.cid_num);
3058                                                                         
3059         o1nativeformats = c1->nativeformats;
3060         o0nativeformats = c0->nativeformats;
3061         for (/* ever */;;) {
3062                 /* timestamp */
3063                 if (config->timelimit) {
3064                         gettimeofday(&precise_now,NULL);
3065                         elapsed_ms = tvdiff(&precise_now,&start_time);
3066                         time_left_ms = config->timelimit - elapsed_ms;
3067
3068                         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)) { 
3069                                 /* narrowing down to the end */
3070                                 if (config->warning_freq == 0) {
3071                                         playit = 1;
3072                                         first_time=0;
3073                                         playitagain=0;
3074                                 } else if (first_time) {
3075                                         playit = 1;
3076                                         first_time=0;
3077                                 } else {
3078                                         if ((time_left_ms % config->warning_freq) <= 50) {
3079                                                 playit = 1;
3080                                         }
3081                                 }
3082                         }
3083                         if (time_left_ms <= 0) {
3084                                 if ((ast_test_flag(&(config->features_caller), AST_FEATURE_PLAY_WARNING)) && config->end_sound)
3085                                         bridge_playfile(c0,c1,config->end_sound,0);
3086                                 if ((ast_test_flag(&(config->features_callee), AST_FEATURE_PLAY_WARNING)) && config->end_sound)
3087                                         bridge_playfile(c1,c0,config->end_sound,0);
3088                                 *fo = NULL;
3089                                 if (who) 
3090                                         *rc = who;
3091                                 res = 0;
3092                                 break;
3093                         }
3094                         if (time_left_ms >= 5000 && playit) {
3095                                 if ((ast_test_flag(&(config->features_caller), AST_FEATURE_PLAY_WARNING)) && config->warning_sound && config->play_warning)
3096                                         bridge_playfile(c0,c1,config->warning_sound,time_left_ms / 1000);
3097                                 if ((ast_test_flag(&(config->features_callee), AST_FEATURE_PLAY_WARNING)) && config->warning_sound && config->play_warning)
3098                                         bridge_playfile(c1,c0,config->warning_sound,time_left_ms / 1000);
3099                                 playit = 0;
3100                         }
3101                         
3102                 }
3103
3104                 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE || c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE) {
3105                         if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
3106                                 c0->_softhangup = 0;
3107                         if (c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
3108                                 c1->_softhangup = 0;
3109                         c0->_bridge = c1;
3110                         c1->_bridge = c0;
3111                         ast_log(LOG_DEBUG, "Unbridge signal received. Ending native bridge.\n");
3112                         continue;
3113                 }
3114