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