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