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