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