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