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