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