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