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