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