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