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