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