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