4174613ec4e7bf2fa27ea86e4fa44205d9e9923a
[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 Wait, look for hangups and condition arg */
1230 int ast_safe_sleep_conditional(struct ast_channel *chan, int ms, int (*cond)(void*), void *data)
1231 {
1232         struct ast_frame *f;
1233
1234         while (ms > 0) {
1235                 if (cond && ((*cond)(data) == 0))
1236                         return 0;
1237                 ms = ast_waitfor(chan, ms);
1238                 if (ms < 0)
1239                         return -1;
1240                 if (ms > 0) {
1241                         f = ast_read(chan);
1242                         if (!f)
1243                                 return -1;
1244                         ast_frfree(f);
1245                 }
1246         }
1247         return 0;
1248 }
1249
1250 /*! \brief Wait, look for hangups */
1251 int ast_safe_sleep(struct ast_channel *chan, int ms)
1252 {
1253         return ast_safe_sleep_conditional(chan, ms, NULL, NULL);
1254 }
1255
1256 static void free_cid(struct ast_callerid *cid)
1257 {
1258         if (cid->cid_dnid)
1259                 ast_free(cid->cid_dnid);
1260         if (cid->cid_num)
1261                 ast_free(cid->cid_num); 
1262         if (cid->cid_name)
1263                 ast_free(cid->cid_name);        
1264         if (cid->cid_ani)
1265                 ast_free(cid->cid_ani);
1266         if (cid->cid_rdnis)
1267                 ast_free(cid->cid_rdnis);
1268         cid->cid_dnid = cid->cid_num = cid->cid_name = cid->cid_ani = cid->cid_rdnis = NULL;
1269 }
1270
1271 /*! \brief Free a channel structure */
1272 void ast_channel_free(struct ast_channel *chan)
1273 {
1274         int fd;
1275 #ifdef HAVE_EPOLL
1276         int i;
1277 #endif
1278         struct ast_var_t *vardata;
1279         struct ast_frame *f;
1280         struct varshead *headp;
1281         struct ast_datastore *datastore = NULL;
1282         char name[AST_CHANNEL_NAME], *dashptr;
1283         
1284         headp=&chan->varshead;
1285         
1286         AST_RWLIST_WRLOCK(&channels);
1287         if (!AST_RWLIST_REMOVE(&channels, chan, chan_list)) {
1288                 AST_RWLIST_UNLOCK(&channels);
1289                 ast_log(LOG_ERROR, "Unable to find channel in list to free. Assuming it has already been done.\n");
1290         }
1291         /* Lock and unlock the channel just to be sure nobody has it locked still
1292            due to a reference retrieved from the channel list. */
1293         ast_channel_lock(chan);
1294         ast_channel_unlock(chan);
1295
1296         /* Get rid of each of the data stores on the channel */
1297         while ((datastore = AST_LIST_REMOVE_HEAD(&chan->datastores, entry)))
1298                 /* Free the data store */
1299                 ast_datastore_free(datastore);
1300
1301         /* Lock and unlock the channel just to be sure nobody has it locked still
1302            due to a reference that was stored in a datastore. (i.e. app_chanspy) */
1303         ast_channel_lock(chan);
1304         ast_channel_unlock(chan);
1305
1306         if (chan->tech_pvt) {
1307                 ast_log(LOG_WARNING, "Channel '%s' may not have been hung up properly\n", chan->name);
1308                 ast_free(chan->tech_pvt);
1309         }
1310
1311         if (chan->sched)
1312                 sched_context_destroy(chan->sched);
1313
1314         ast_copy_string(name, chan->name, sizeof(name));
1315         if ((dashptr = strrchr(name, '-'))) {
1316                 *dashptr = '\0';
1317         }
1318
1319         /* Stop monitoring */
1320         if (chan->monitor)
1321                 chan->monitor->stop( chan, 0 );
1322
1323         /* If there is native format music-on-hold state, free it */
1324         if (chan->music_state)
1325                 ast_moh_cleanup(chan);
1326
1327         /* Free translators */
1328         if (chan->readtrans)
1329                 ast_translator_free_path(chan->readtrans);
1330         if (chan->writetrans)
1331                 ast_translator_free_path(chan->writetrans);
1332         if (chan->pbx)
1333                 ast_log(LOG_WARNING, "PBX may not have been terminated properly on '%s'\n", chan->name);
1334         free_cid(&chan->cid);
1335         /* Close pipes if appropriate */
1336         if ((fd = chan->alertpipe[0]) > -1)
1337                 close(fd);
1338         if ((fd = chan->alertpipe[1]) > -1)
1339                 close(fd);
1340         if ((fd = chan->timingfd) > -1)
1341                 ast_timer_close(fd);
1342 #ifdef HAVE_EPOLL
1343         for (i = 0; i < AST_MAX_FDS; i++) {
1344                 if (chan->epfd_data[i])
1345                         free(chan->epfd_data[i]);
1346         }
1347         close(chan->epfd);
1348 #endif
1349         while ((f = AST_LIST_REMOVE_HEAD(&chan->readq, frame_list)))
1350                 ast_frfree(f);
1351         
1352         /* loop over the variables list, freeing all data and deleting list items */
1353         /* no need to lock the list, as the channel is already locked */
1354         
1355         while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
1356                 ast_var_delete(vardata);
1357
1358         ast_app_group_discard(chan);
1359
1360         /* Destroy the jitterbuffer */
1361         ast_jb_destroy(chan);
1362
1363         if (chan->cdr) {
1364                 ast_cdr_discard(chan->cdr);
1365                 chan->cdr = NULL;
1366         }
1367         
1368         ast_mutex_destroy(&chan->lock_dont_use);
1369
1370         ast_string_field_free_memory(chan);
1371         ast_free(chan);
1372         AST_RWLIST_UNLOCK(&channels);
1373
1374         ast_devstate_changed_literal(AST_DEVICE_NOT_INUSE, name);
1375 }
1376
1377 struct ast_datastore *ast_channel_datastore_alloc(const struct ast_datastore_info *info, const char *uid)
1378 {
1379         return ast_datastore_alloc(info, uid);
1380 }
1381
1382 int ast_channel_datastore_free(struct ast_datastore *datastore)
1383 {
1384         return ast_datastore_free(datastore);
1385 }
1386
1387 int ast_channel_datastore_inherit(struct ast_channel *from, struct ast_channel *to)
1388 {
1389         struct ast_datastore *datastore = NULL, *datastore2;
1390
1391         AST_LIST_TRAVERSE(&from->datastores, datastore, entry) {
1392                 if (datastore->inheritance > 0) {
1393                         datastore2 = ast_datastore_alloc(datastore->info, datastore->uid);
1394                         if (datastore2) {
1395                                 datastore2->data = datastore->info->duplicate(datastore->data);
1396                                 datastore2->inheritance = datastore->inheritance == DATASTORE_INHERIT_FOREVER ? DATASTORE_INHERIT_FOREVER : datastore->inheritance - 1;
1397                                 AST_LIST_INSERT_TAIL(&to->datastores, datastore2, entry);
1398                         }
1399                 }
1400         }
1401         return 0;
1402 }
1403
1404 int ast_channel_datastore_add(struct ast_channel *chan, struct ast_datastore *datastore)
1405 {
1406         int res = 0;
1407
1408         AST_LIST_INSERT_HEAD(&chan->datastores, datastore, entry);
1409
1410         return res;
1411 }
1412
1413 int ast_channel_datastore_remove(struct ast_channel *chan, struct ast_datastore *datastore)
1414 {
1415         return AST_LIST_REMOVE(&chan->datastores, datastore, entry) ? 0 : -1;
1416 }
1417
1418 struct ast_datastore *ast_channel_datastore_find(struct ast_channel *chan, const struct ast_datastore_info *info, const char *uid)
1419 {
1420         struct ast_datastore *datastore = NULL;
1421         
1422         if (info == NULL)
1423                 return NULL;
1424
1425         AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->datastores, datastore, entry) {
1426                 if (datastore->info != info) {
1427                         continue;
1428                 }
1429
1430                 if (uid == NULL) {
1431                         /* matched by type only */
1432                         break;
1433                 }
1434
1435                 if ((datastore->uid != NULL) && !strcasecmp(uid, datastore->uid)) {
1436                         /* Matched by type AND uid */
1437                         break;
1438                 }
1439         }
1440         AST_LIST_TRAVERSE_SAFE_END;
1441
1442         return datastore;
1443 }
1444
1445 /*! Set the file descriptor on the channel */
1446 void ast_channel_set_fd(struct ast_channel *chan, int which, int fd)
1447 {
1448 #ifdef HAVE_EPOLL
1449         struct epoll_event ev;
1450         struct ast_epoll_data *aed = NULL;
1451
1452         if (chan->fds[which] > -1) {
1453                 epoll_ctl(chan->epfd, EPOLL_CTL_DEL, chan->fds[which], &ev);
1454                 aed = chan->epfd_data[which];
1455         }
1456
1457         /* If this new fd is valid, add it to the epoll */
1458         if (fd > -1) {
1459                 if (!aed && (!(aed = ast_calloc(1, sizeof(*aed)))))
1460                         return;
1461                 
1462                 chan->epfd_data[which] = aed;
1463                 aed->chan = chan;
1464                 aed->which = which;
1465                 
1466                 ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
1467                 ev.data.ptr = aed;
1468                 epoll_ctl(chan->epfd, EPOLL_CTL_ADD, fd, &ev);
1469         } else if (aed) {
1470                 /* We don't have to keep around this epoll data structure now */
1471                 free(aed);
1472                 chan->epfd_data[which] = NULL;
1473         }
1474 #endif
1475         chan->fds[which] = fd;
1476         return;
1477 }
1478
1479 /*! Add a channel to an optimized waitfor */
1480 void ast_poll_channel_add(struct ast_channel *chan0, struct ast_channel *chan1)
1481 {
1482 #ifdef HAVE_EPOLL
1483         struct epoll_event ev;
1484         int i = 0;
1485
1486         if (chan0->epfd == -1)
1487                 return;
1488
1489         /* Iterate through the file descriptors on chan1, adding them to chan0 */
1490         for (i = 0; i < AST_MAX_FDS; i++) {
1491                 if (chan1->fds[i] == -1)
1492                         continue;
1493                 ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
1494                 ev.data.ptr = chan1->epfd_data[i];
1495                 epoll_ctl(chan0->epfd, EPOLL_CTL_ADD, chan1->fds[i], &ev);
1496         }
1497
1498 #endif
1499         return;
1500 }
1501
1502 /*! Delete a channel from an optimized waitfor */
1503 void ast_poll_channel_del(struct ast_channel *chan0, struct ast_channel *chan1)
1504 {
1505 #ifdef HAVE_EPOLL
1506         struct epoll_event ev;
1507         int i = 0;
1508
1509         if (chan0->epfd == -1)
1510                 return;
1511
1512         for (i = 0; i < AST_MAX_FDS; i++) {
1513                 if (chan1->fds[i] == -1)
1514                         continue;
1515                 epoll_ctl(chan0->epfd, EPOLL_CTL_DEL, chan1->fds[i], &ev);
1516         }
1517
1518 #endif
1519         return;
1520 }
1521
1522 /*! \brief Softly hangup a channel, don't lock */
1523 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
1524 {
1525         ast_debug(1, "Soft-Hanging up channel '%s'\n", chan->name);
1526         /* Inform channel driver that we need to be hung up, if it cares */
1527         chan->_softhangup |= cause;
1528         ast_queue_frame(chan, &ast_null_frame);
1529         /* Interrupt any poll call or such */
1530         if (ast_test_flag(chan, AST_FLAG_BLOCKING))
1531                 pthread_kill(chan->blocker, SIGURG);
1532         return 0;
1533 }
1534
1535 /*! \brief Softly hangup a channel, lock */
1536 int ast_softhangup(struct ast_channel *chan, int cause)
1537 {
1538         int res;
1539
1540         ast_channel_lock(chan);
1541         res = ast_softhangup_nolock(chan, cause);
1542         ast_channel_unlock(chan);
1543
1544         return res;
1545 }
1546
1547 static void free_translation(struct ast_channel *clonechan)
1548 {
1549         if (clonechan->writetrans)
1550                 ast_translator_free_path(clonechan->writetrans);
1551         if (clonechan->readtrans)
1552                 ast_translator_free_path(clonechan->readtrans);
1553         clonechan->writetrans = NULL;
1554         clonechan->readtrans = NULL;
1555         clonechan->rawwriteformat = clonechan->nativeformats;
1556         clonechan->rawreadformat = clonechan->nativeformats;
1557 }
1558
1559 /*! \brief Hangup a channel */
1560 int ast_hangup(struct ast_channel *chan)
1561 {
1562         int res = 0;
1563
1564         /* Don't actually hang up a channel that will masquerade as someone else, or
1565            if someone is going to masquerade as us */
1566         ast_channel_lock(chan);
1567
1568         if (chan->audiohooks) {
1569                 ast_audiohook_detach_list(chan->audiohooks);
1570                 chan->audiohooks = NULL;
1571         }
1572
1573         ast_autoservice_stop(chan);
1574
1575         if (chan->masq) {
1576                 if (ast_do_masquerade(chan))
1577                         ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1578         }
1579
1580         if (chan->masq) {
1581                 ast_log(LOG_WARNING, "%s getting hung up, but someone is trying to masq into us?!?\n", chan->name);
1582                 ast_channel_unlock(chan);
1583                 return 0;
1584         }
1585         /* If this channel is one which will be masqueraded into something,
1586            mark it as a zombie already, so we know to free it later */
1587         if (chan->masqr) {
1588                 ast_set_flag(chan, AST_FLAG_ZOMBIE);
1589                 ast_channel_unlock(chan);
1590                 return 0;
1591         }
1592         free_translation(chan);
1593         /* Close audio stream */
1594         if (chan->stream) {
1595                 ast_closestream(chan->stream);
1596                 chan->stream = NULL;
1597         }
1598         /* Close video stream */
1599         if (chan->vstream) {
1600                 ast_closestream(chan->vstream);
1601                 chan->vstream = NULL;
1602         }
1603         if (chan->sched) {
1604                 sched_context_destroy(chan->sched);
1605                 chan->sched = NULL;
1606         }
1607         
1608         if (chan->generatordata)        /* Clear any tone stuff remaining */
1609                 if (chan->generator && chan->generator->release)
1610                         chan->generator->release(chan, chan->generatordata);
1611         chan->generatordata = NULL;
1612         chan->generator = NULL;
1613         if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
1614                 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
1615                                         "is blocked by thread %ld in procedure %s!  Expect a failure\n",
1616                                         (long)pthread_self(), chan->name, (long)chan->blocker, chan->blockproc);
1617                 ast_assert(ast_test_flag(chan, AST_FLAG_BLOCKING) == 0);
1618         }
1619         if (!ast_test_flag(chan, AST_FLAG_ZOMBIE)) {
1620                 ast_debug(1, "Hanging up channel '%s'\n", chan->name);
1621                 if (chan->tech->hangup)
1622                         res = chan->tech->hangup(chan);
1623         } else {
1624                 ast_debug(1, "Hanging up zombie '%s'\n", chan->name);
1625         }
1626                         
1627         ast_channel_unlock(chan);
1628         manager_event(EVENT_FLAG_CALL, "Hangup",
1629                         "Channel: %s\r\n"
1630                         "Uniqueid: %s\r\n"
1631                         "CallerIDNum: %s\r\n"
1632                         "CallerIDName: %s\r\n"
1633                         "Cause: %d\r\n"
1634                         "Cause-txt: %s\r\n",
1635                         chan->name,
1636                         chan->uniqueid,
1637                         S_OR(chan->cid.cid_num, "<unknown>"),
1638                         S_OR(chan->cid.cid_name, "<unknown>"),
1639                         chan->hangupcause,
1640                         ast_cause2str(chan->hangupcause)
1641                         );
1642
1643         if (chan->cdr && !ast_test_flag(chan->cdr, AST_CDR_FLAG_BRIDGED) && 
1644                 !ast_test_flag(chan->cdr, AST_CDR_FLAG_POST_DISABLED) && 
1645             (chan->cdr->disposition != AST_CDR_NULL || ast_test_flag(chan->cdr, AST_CDR_FLAG_DIALED))) {
1646                         
1647                 ast_cdr_end(chan->cdr);
1648                 ast_cdr_detach(chan->cdr);
1649                 chan->cdr = NULL;
1650         }
1651         
1652         ast_channel_free(chan);
1653
1654         return res;
1655 }
1656
1657 #define ANSWER_WAIT_MS 500
1658 int __ast_answer(struct ast_channel *chan, unsigned int delay)
1659 {
1660         int res = 0;
1661
1662         ast_channel_lock(chan);
1663
1664         /* You can't answer an outbound call */
1665         if (ast_test_flag(chan, AST_FLAG_OUTGOING)) {
1666                 ast_channel_unlock(chan);
1667                 return 0;
1668         }
1669
1670         /* Stop if we're a zombie or need a soft hangup */
1671         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
1672                 ast_channel_unlock(chan);
1673                 return -1;
1674         }
1675
1676         ast_channel_unlock(chan);
1677
1678         switch (chan->_state) {
1679         case AST_STATE_RINGING:
1680         case AST_STATE_RING:
1681                 ast_channel_lock(chan);
1682                 if (chan->tech->answer) {
1683                         res = chan->tech->answer(chan);
1684                 }
1685                 ast_setstate(chan, AST_STATE_UP);
1686                 ast_cdr_answer(chan->cdr);
1687                 ast_channel_unlock(chan);
1688                 if (delay) {
1689                         ast_safe_sleep(chan, delay);
1690                 } else {
1691                         struct ast_frame *f;
1692                         int ms = ANSWER_WAIT_MS;
1693                         while (1) {
1694                                 /* 500 ms was the original delay here, so now
1695                                  * we cap our waiting at 500 ms
1696                                  */
1697                                 ms = ast_waitfor(chan, ms);
1698                                 if (ms < 0) {
1699                                         ast_log(LOG_WARNING, "Error condition occurred when polling channel %s for a voice frame: %s\n", chan->name, strerror(errno));
1700                                         res = -1;
1701                                         break;
1702                                 }
1703                                 if (ms == 0) {
1704                                         ast_debug(2, "Didn't receive a voice frame from %s within %d ms of answering. Continuing anyway\n", chan->name, ANSWER_WAIT_MS);
1705                                         res = 0;
1706                                         break;
1707                                 }
1708                                 f = ast_read(chan);
1709                                 if (!f || (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP)) {
1710                                         res = -1;
1711                                         ast_debug(2, "Hangup of channel %s detected in answer routine\n", chan->name);
1712                                         break;
1713                                 }
1714                                 if (f->frametype == AST_FRAME_VOICE) {
1715                                         res = 0;
1716                                         break;
1717                                 }
1718                         }
1719                 }
1720                 break;
1721         case AST_STATE_UP:
1722                 break;
1723         default:
1724                 break;
1725         }
1726
1727         chan->visible_indication = 0;
1728
1729         return res;
1730 }
1731
1732 int ast_answer(struct ast_channel *chan)
1733 {
1734         return __ast_answer(chan, 0);
1735 }
1736
1737 void ast_deactivate_generator(struct ast_channel *chan)
1738 {
1739         ast_channel_lock(chan);
1740         if (chan->generatordata) {
1741                 if (chan->generator && chan->generator->release)
1742                         chan->generator->release(chan, chan->generatordata);
1743                 chan->generatordata = NULL;
1744                 chan->generator = NULL;
1745                 ast_channel_set_fd(chan, AST_GENERATOR_FD, -1);
1746                 ast_clear_flag(chan, AST_FLAG_WRITE_INT);
1747                 ast_settimeout(chan, 0, NULL, NULL);
1748         }
1749         ast_channel_unlock(chan);
1750 }
1751
1752 static int generator_force(const void *data)
1753 {
1754         /* Called if generator doesn't have data */
1755         void *tmp;
1756         int res;
1757         int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples) = NULL;
1758         struct ast_channel *chan = (struct ast_channel *)data;
1759
1760         ast_channel_lock(chan);
1761         tmp = chan->generatordata;
1762         chan->generatordata = NULL;
1763         if (chan->generator)
1764                 generate = chan->generator->generate;
1765         ast_channel_unlock(chan);
1766
1767         if (!tmp || !generate)
1768                 return 0;
1769
1770         res = generate(chan, tmp, 0, ast_format_rate(chan->writeformat & AST_FORMAT_AUDIO_MASK) / 50);
1771
1772         chan->generatordata = tmp;
1773
1774         if (res) {
1775                 ast_debug(1, "Auto-deactivating generator\n");
1776                 ast_deactivate_generator(chan);
1777         }
1778
1779         return 0;
1780 }
1781
1782 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
1783 {
1784         int res = 0;
1785
1786         ast_channel_lock(chan);
1787
1788         if (chan->generatordata) {
1789                 if (chan->generator && chan->generator->release)
1790                         chan->generator->release(chan, chan->generatordata);
1791                 chan->generatordata = NULL;
1792         }
1793
1794         ast_prod(chan);
1795         if (gen->alloc && !(chan->generatordata = gen->alloc(chan, params))) {
1796                 res = -1;
1797         }
1798         
1799         if (!res) {
1800                 ast_settimeout(chan, 50, generator_force, chan);
1801                 chan->generator = gen;
1802         }
1803
1804         ast_channel_unlock(chan);
1805
1806         return res;
1807 }
1808
1809 /*! \brief Wait for x amount of time on a file descriptor to have input.  */
1810 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
1811 {
1812         int winner = -1;
1813         ast_waitfor_nandfds(NULL, 0, fds, n, exception, &winner, ms);
1814         return winner;
1815 }
1816
1817 /*! \brief Wait for x amount of time on a file descriptor to have input.  */
1818 #ifdef HAVE_EPOLL
1819 static struct ast_channel *ast_waitfor_nandfds_classic(struct ast_channel **c, int n, int *fds, int nfds,
1820                                         int *exception, int *outfd, int *ms)
1821 #else
1822 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
1823                                         int *exception, int *outfd, int *ms)
1824 #endif
1825 {
1826         struct timeval start = { 0 , 0 };
1827         struct pollfd *pfds = NULL;
1828         int res;
1829         long rms;
1830         int x, y, max;
1831         int sz;
1832         struct timeval now = { 0, 0 };
1833         struct timeval whentohangup = { 0, 0 }, diff;
1834         struct ast_channel *winner = NULL;
1835         struct fdmap {
1836                 int chan;
1837                 int fdno;
1838         } *fdmap = NULL;
1839
1840         if ((sz = n * AST_MAX_FDS + nfds)) {
1841                 pfds = alloca(sizeof(*pfds) * sz);
1842                 fdmap = alloca(sizeof(*fdmap) * sz);
1843         }
1844
1845         if (outfd)
1846                 *outfd = -99999;
1847         if (exception)
1848                 *exception = 0;
1849         
1850         /* Perform any pending masquerades */
1851         for (x = 0; x < n; x++) {
1852                 ast_channel_lock(c[x]);
1853                 if (c[x]->masq && ast_do_masquerade(c[x])) {
1854                         ast_log(LOG_WARNING, "Masquerade failed\n");
1855                         *ms = -1;
1856                         ast_channel_unlock(c[x]);
1857                         return NULL;
1858                 }
1859                 if (!ast_tvzero(c[x]->whentohangup)) {
1860                         if (ast_tvzero(whentohangup))
1861                                 now = ast_tvnow();
1862                         diff = ast_tvsub(c[x]->whentohangup, now);
1863                         if (diff.tv_sec < 0 || ast_tvzero(diff)) {
1864                                 /* Should already be hungup */
1865                                 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1866                                 ast_channel_unlock(c[x]);
1867                                 return c[x];
1868                         }
1869                         if (ast_tvzero(whentohangup) || ast_tvcmp(diff, whentohangup) < 0)
1870                                 whentohangup = diff;
1871                 }
1872                 ast_channel_unlock(c[x]);
1873         }
1874         /* Wait full interval */
1875         rms = *ms;
1876         if (!ast_tvzero(whentohangup)) {
1877                 rms = whentohangup.tv_sec * 1000 + whentohangup.tv_usec / 1000;              /* timeout in milliseconds */
1878                 if (*ms >= 0 && *ms < rms)              /* original *ms still smaller */
1879                         rms =  *ms;
1880         }
1881         /*
1882          * Build the pollfd array, putting the channels' fds first,
1883          * followed by individual fds. Order is important because
1884          * individual fd's must have priority over channel fds.
1885          */
1886         max = 0;
1887         for (x = 0; x < n; x++) {
1888                 for (y = 0; y < AST_MAX_FDS; y++) {
1889                         fdmap[max].fdno = y;  /* fd y is linked to this pfds */
1890                         fdmap[max].chan = x;  /* channel x is linked to this pfds */
1891                         max += ast_add_fd(&pfds[max], c[x]->fds[y]);
1892                 }
1893                 CHECK_BLOCKING(c[x]);
1894         }
1895         /* Add the individual fds */
1896         for (x = 0; x < nfds; x++) {
1897                 fdmap[max].chan = -1;
1898                 max += ast_add_fd(&pfds[max], fds[x]);
1899         }
1900
1901         if (*ms > 0)
1902                 start = ast_tvnow();
1903         
1904         if (sizeof(int) == 4) { /* XXX fix timeout > 600000 on linux x86-32 */
1905                 do {
1906                         int kbrms = rms;
1907                         if (kbrms > 600000)
1908                                 kbrms = 600000;
1909                         res = poll(pfds, max, kbrms);
1910                         if (!res)
1911                                 rms -= kbrms;
1912                 } while (!res && (rms > 0));
1913         } else {
1914                 res = poll(pfds, max, rms);
1915         }
1916         for (x = 0; x < n; x++)
1917                 ast_clear_flag(c[x], AST_FLAG_BLOCKING);
1918         if (res < 0) { /* Simulate a timeout if we were interrupted */
1919                 if (errno != EINTR)
1920                         *ms = -1;
1921                 return NULL;
1922         }
1923         if (!ast_tvzero(whentohangup)) {   /* if we have a timeout, check who expired */
1924                 now = ast_tvnow();
1925                 for (x = 0; x < n; x++) {
1926                         if (!ast_tvzero(c[x]->whentohangup) && ast_tvcmp(c[x]->whentohangup, now) <= 0) {
1927                                 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1928                                 if (winner == NULL)
1929                                         winner = c[x];
1930                         }
1931                 }
1932         }
1933         if (res == 0) { /* no fd ready, reset timeout and done */
1934                 *ms = 0;        /* XXX use 0 since we may not have an exact timeout. */
1935                 return winner;
1936         }
1937         /*
1938          * Then check if any channel or fd has a pending event.
1939          * Remember to check channels first and fds last, as they
1940          * must have priority on setting 'winner'
1941          */
1942         for (x = 0; x < max; x++) {
1943                 res = pfds[x].revents;
1944                 if (res == 0)
1945                         continue;
1946                 if (fdmap[x].chan >= 0) {       /* this is a channel */
1947                         winner = c[fdmap[x].chan];      /* override previous winners */
1948                         if (res & POLLPRI)
1949                                 ast_set_flag(winner, AST_FLAG_EXCEPTION);
1950                         else
1951                                 ast_clear_flag(winner, AST_FLAG_EXCEPTION);
1952                         winner->fdno = fdmap[x].fdno;
1953                 } else {                        /* this is an fd */
1954                         if (outfd)
1955                                 *outfd = pfds[x].fd;
1956                         if (exception)
1957                                 *exception = (res & POLLPRI) ? -1 : 0;
1958                         winner = NULL;
1959                 }
1960         }
1961         if (*ms > 0) {
1962                 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
1963                 if (*ms < 0)
1964                         *ms = 0;
1965         }
1966         return winner;
1967 }
1968
1969 #ifdef HAVE_EPOLL
1970 static struct ast_channel *ast_waitfor_nandfds_simple(struct ast_channel *chan, int *ms)
1971 {
1972         struct timeval start = { 0 , 0 };
1973         int res = 0;
1974         struct epoll_event ev[1];
1975         long diff, rms = *ms;
1976         struct ast_channel *winner = NULL;
1977         struct ast_epoll_data *aed = NULL;
1978
1979         ast_channel_lock(chan);
1980
1981         /* See if this channel needs to be masqueraded */
1982         if (chan->masq && ast_do_masquerade(chan)) {
1983                 ast_log(LOG_WARNING, "Failed to perform masquerade on %s\n", chan->name);
1984                 *ms = -1;
1985                 ast_channel_unlock(chan);
1986                 return NULL;
1987         }
1988
1989         /* Figure out their timeout */
1990         if (!ast_tvzero(chan->whentohangup)) {
1991                 if ((diff = ast_tvdiff_ms(chan->whentohangup, ast_tvnow())) < 0) {
1992                         /* They should already be hungup! */
1993                         chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1994                         ast_channel_unlock(chan);
1995                         return NULL;
1996                 }
1997                 /* If this value is smaller then the current one... make it priority */
1998                 if (rms > diff)
1999                         rms = diff;
2000         }
2001
2002         ast_channel_unlock(chan);
2003
2004         /* Time to make this channel block... */
2005         CHECK_BLOCKING(chan);
2006
2007         if (*ms > 0)
2008                 start = ast_tvnow();
2009
2010         /* We don't have to add any file descriptors... they are already added, we just have to wait! */
2011         res = epoll_wait(chan->epfd, ev, 1, rms);
2012
2013         /* Stop blocking */
2014         ast_clear_flag(chan, AST_FLAG_BLOCKING);
2015
2016         /* Simulate a timeout if we were interrupted */
2017         if (res < 0) {
2018                 if (errno != EINTR)
2019                         *ms = -1;
2020                 return NULL;
2021         }
2022
2023         /* If this channel has a timeout see if it expired */
2024         if (!ast_tvzero(chan->whentohangup)) {
2025                 if (ast_tvdiff_ms(ast_tvnow(), chan->whentohangup) >= 0) {
2026                         chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
2027                         winner = chan;
2028                 }
2029         }
2030
2031         /* No fd ready, reset timeout and be done for now */
2032         if (!res) {
2033                 *ms = 0;
2034                 return winner;
2035         }
2036
2037         /* See what events are pending */
2038         aed = ev[0].data.ptr;
2039         chan->fdno = aed->which;
2040         if (ev[0].events & EPOLLPRI)
2041                 ast_set_flag(chan, AST_FLAG_EXCEPTION);
2042         else
2043                 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
2044
2045         if (*ms > 0) {
2046                 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
2047                 if (*ms < 0)
2048                         *ms = 0;
2049         }
2050
2051         return chan;
2052 }
2053
2054 static struct ast_channel *ast_waitfor_nandfds_complex(struct ast_channel **c, int n, int *ms)
2055 {
2056         struct timeval start = { 0 , 0 };
2057         int res = 0, i;
2058         struct epoll_event ev[25] = { { 0, } };
2059         struct timeval now = { 0, 0 };
2060         long whentohangup = 0, diff = 0, rms = *ms;
2061         struct ast_channel *winner = NULL;
2062
2063         for (i = 0; i < n; i++) {
2064                 ast_channel_lock(c[i]);
2065                 if (c[i]->masq && ast_do_masquerade(c[i])) {
2066                         ast_log(LOG_WARNING, "Masquerade failed\n");
2067                         *ms = -1;
2068                         ast_channel_unlock(c[i]);
2069                         return NULL;
2070                 }
2071                 if (!ast_tvzero(c[i]->whentohangup)) {
2072                         if (whentohangup == 0)
2073                                 now = ast_tvnow();
2074                         if ((diff = ast_tvdiff_ms(c[i]->whentohangup, now)) < 0) {
2075                                 c[i]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
2076                                 ast_channel_unlock(c[i]);
2077                                 return c[i];
2078                         }
2079                         if (!whentohangup || whentohangup > diff)
2080                                 whentohangup = diff;
2081                 }
2082                 ast_channel_unlock(c[i]);
2083                 CHECK_BLOCKING(c[i]);
2084         }
2085
2086         rms = *ms;
2087         if (whentohangup) {
2088                 rms = whentohangup;
2089                 if (*ms >= 0 && *ms < rms)
2090                         rms = *ms;
2091         }
2092
2093         if (*ms > 0)
2094                 start = ast_tvnow();
2095
2096         res = epoll_wait(c[0]->epfd, ev, 25, rms);
2097
2098         for (i = 0; i < n; i++)
2099                 ast_clear_flag(c[i], AST_FLAG_BLOCKING);
2100
2101         if (res < 0) {
2102                 if (errno != EINTR)
2103                         *ms = -1;
2104                 return NULL;
2105         }
2106
2107         if (whentohangup) {
2108                 now = ast_tvnow();
2109                 for (i = 0; i < n; i++) {
2110                         if (!ast_tvzero(c[i]->whentohangup) && ast_tvdiff_ms(now, c[i]->whentohangup) >= 0) {
2111                                 c[i]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
2112                                 if (!winner)
2113                                         winner = c[i];
2114                         }
2115                 }
2116         }
2117
2118         if (!res) {
2119                 *ms = 0;
2120                 return winner;
2121         }
2122
2123         for (i = 0; i < res; i++) {
2124                 struct ast_epoll_data *aed = ev[i].data.ptr;
2125
2126                 if (!ev[i].events || !aed)
2127                         continue;
2128
2129                 winner = aed->chan;
2130                 if (ev[i].events & EPOLLPRI)
2131                         ast_set_flag(winner, AST_FLAG_EXCEPTION);
2132                 else
2133                         ast_clear_flag(winner, AST_FLAG_EXCEPTION);
2134                 winner->fdno = aed->which;
2135         }
2136
2137         if (*ms > 0) {
2138                 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
2139                 if (*ms < 0)
2140                         *ms = 0;
2141         }
2142
2143         return winner;
2144 }
2145
2146 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
2147                                         int *exception, int *outfd, int *ms)
2148 {
2149         /* Clear all provided values in one place. */
2150         if (outfd)
2151                 *outfd = -99999;
2152         if (exception)
2153                 *exception = 0;
2154
2155         /* If no epoll file descriptor is available resort to classic nandfds */
2156         if (!n || nfds || c[0]->epfd == -1)
2157                 return ast_waitfor_nandfds_classic(c, n, fds, nfds, exception, outfd, ms);
2158         else if (!nfds && n == 1)
2159                 return ast_waitfor_nandfds_simple(c[0], ms);
2160         else
2161                 return ast_waitfor_nandfds_complex(c, n, ms);
2162 }
2163 #endif
2164
2165 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
2166 {
2167         return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
2168 }
2169
2170 int ast_waitfor(struct ast_channel *c, int ms)
2171 {
2172         int oldms = ms; /* -1 if no timeout */
2173
2174         ast_waitfor_nandfds(&c, 1, NULL, 0, NULL, NULL, &ms);
2175         if ((ms < 0) && (oldms < 0))
2176                 ms = 0;
2177         return ms;
2178 }
2179
2180 /* XXX never to be called with ms = -1 */
2181 int ast_waitfordigit(struct ast_channel *c, int ms)
2182 {
2183         return ast_waitfordigit_full(c, ms, -1, -1);
2184 }
2185
2186 int ast_settimeout(struct ast_channel *c, unsigned int rate, int (*func)(const void *data), void *data)
2187 {
2188         int res;
2189         unsigned int real_rate = rate, max_rate;
2190
2191         if (c->timingfd == -1) {
2192                 return -1;
2193         }
2194
2195         if (!func) {
2196                 rate = 0;
2197                 data = NULL;
2198         }
2199
2200         if (rate && rate > (max_rate = ast_timer_get_max_rate(c->timingfd))) {
2201                 real_rate = max_rate;
2202         }
2203
2204         ast_debug(1, "Scheduling timer at (%u requested / %u actual) timer ticks per second\n", rate, real_rate);
2205
2206         res = ast_timer_set_rate(c->timingfd, real_rate);
2207
2208         c->timingfunc = func;
2209         c->timingdata = data;
2210
2211         return res;
2212 }
2213
2214 int ast_waitfordigit_full(struct ast_channel *c, int ms, int audiofd, int cmdfd)
2215 {
2216         /* Stop if we're a zombie or need a soft hangup */
2217         if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
2218                 return -1;
2219
2220         /* Only look for the end of DTMF, don't bother with the beginning and don't emulate things */
2221         ast_set_flag(c, AST_FLAG_END_DTMF_ONLY);
2222
2223         /* Wait for a digit, no more than ms milliseconds total. */
2224         
2225         while (ms) {
2226                 struct ast_channel *rchan;
2227                 int outfd=-1;
2228
2229                 errno = 0;
2230                 rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
2231                 
2232                 if (!rchan && outfd < 0 && ms) {
2233                         if (errno == 0 || errno == EINTR)
2234                                 continue;
2235                         ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
2236                         ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2237                         return -1;
2238                 } else if (outfd > -1) {
2239                         /* The FD we were watching has something waiting */
2240                         ast_log(LOG_WARNING, "The FD we were waiting for has something waiting. Waitfordigit returning numeric 1\n");
2241                         ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2242                         return 1;
2243                 } else if (rchan) {
2244                         int res;
2245                         struct ast_frame *f = ast_read(c);
2246                         if (!f)
2247                                 return -1;
2248
2249                         switch (f->frametype) {
2250                         case AST_FRAME_DTMF_BEGIN:
2251                                 break;
2252                         case AST_FRAME_DTMF_END:
2253                                 res = f->subclass;
2254                                 ast_frfree(f);
2255                                 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2256                                 return res;
2257                         case AST_FRAME_CONTROL:
2258                                 switch (f->subclass) {
2259                                 case AST_CONTROL_HANGUP:
2260                                         ast_frfree(f);
2261                                         ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2262                                         return -1;
2263                                 case AST_CONTROL_RINGING:
2264                                 case AST_CONTROL_ANSWER:
2265                                 case AST_CONTROL_SRCUPDATE:
2266                                         /* Unimportant */
2267                                         break;
2268                                 default:
2269                                         ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", f->subclass);
2270                                         break;
2271                                 }
2272                                 break;
2273                         case AST_FRAME_VOICE:
2274                                 /* Write audio if appropriate */
2275                                 if (audiofd > -1) {
2276                                         if (write(audiofd, f->data.ptr, f->datalen) < 0) {
2277                                                 ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
2278                                         }
2279                                 }
2280                         default:
2281                                 /* Ignore */
2282                                 break;
2283                         }
2284                         ast_frfree(f);
2285                 }
2286         }
2287
2288         ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2289
2290         return 0; /* Time is up */
2291 }
2292
2293 static void send_dtmf_event(const struct ast_channel *chan, const char *direction, const char digit, const char *begin, const char *end)
2294 {
2295         manager_event(EVENT_FLAG_DTMF,
2296                         "DTMF",
2297                         "Channel: %s\r\n"
2298                         "Uniqueid: %s\r\n"
2299                         "Digit: %c\r\n"
2300                         "Direction: %s\r\n"
2301                         "Begin: %s\r\n"
2302                         "End: %s\r\n",
2303                         chan->name, chan->uniqueid, digit, direction, begin, end);
2304 }
2305
2306 static void ast_read_generator_actions(struct ast_channel *chan, struct ast_frame *f)
2307 {
2308         if (chan->generatordata &&  !ast_internal_timing_enabled(chan)) {
2309                 void *tmp = chan->generatordata;
2310                 int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples) = NULL;
2311                 int res;
2312                 int samples;
2313
2314                 if (chan->timingfunc) {
2315                         ast_debug(1, "Generator got voice, switching to phase locked mode\n");
2316                         ast_settimeout(chan, 0, NULL, NULL);
2317                 }
2318
2319                 chan->generatordata = NULL;     /* reset, to let writes go through */
2320
2321                 if (f->subclass != chan->writeformat) {
2322                         float factor;
2323                         factor = ((float) ast_format_rate(chan->writeformat)) / ((float) ast_format_rate(f->subclass));
2324                         samples = (int) ( ((float) f->samples) * factor );
2325                 } else {
2326                         samples = f->samples;
2327                 }
2328                 
2329                 if (chan->generator->generate) {
2330                         generate = chan->generator->generate;
2331                 }
2332                 /* This unlock is here based on two assumptions that hold true at this point in the
2333                  * code. 1) this function is only called from within __ast_read() and 2) all generators
2334                  * call ast_write() in their generate callback.
2335                  *
2336                  * The reason this is added is so that when ast_write is called, the lock that occurs 
2337                  * there will not recursively lock the channel. Doing this will cause intended deadlock 
2338                  * avoidance not to work in deeper functions
2339                  */
2340                 ast_channel_unlock(chan);
2341                 res = generate(chan, tmp, f->datalen, samples);
2342                 ast_channel_lock(chan);
2343                 chan->generatordata = tmp;
2344                 if (res) {
2345                         ast_debug(1, "Auto-deactivating generator\n");
2346                         ast_deactivate_generator(chan);
2347                 }
2348
2349         } else if (f->frametype == AST_FRAME_CNG) {
2350                 if (chan->generator && !chan->timingfunc && (chan->timingfd > -1)) {
2351                         ast_debug(1, "Generator got CNG, switching to timed mode\n");
2352                         ast_settimeout(chan, 50, generator_force, chan);
2353                 }
2354         }
2355 }
2356
2357 static struct ast_frame *__ast_read(struct ast_channel *chan, int dropaudio)
2358 {
2359         struct ast_frame *f = NULL;     /* the return value */
2360         int blah;
2361         int prestate;
2362         int count = 0, cause = 0;
2363
2364         /* this function is very long so make sure there is only one return
2365          * point at the end (there are only two exceptions to this).
2366          */
2367         while(ast_channel_trylock(chan)) {
2368                 if(count++ > 10) 
2369                         /*cannot goto done since the channel is not locked*/
2370                         return &ast_null_frame;
2371                 usleep(1);
2372         }
2373
2374         if (chan->masq) {
2375                 if (ast_do_masquerade(chan))
2376                         ast_log(LOG_WARNING, "Failed to perform masquerade\n");
2377                 else
2378                         f =  &ast_null_frame;
2379                 goto done;
2380         }
2381
2382         /* Stop if we're a zombie or need a soft hangup */
2383         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2384                 if (chan->generator)
2385                         ast_deactivate_generator(chan);
2386                 goto done;
2387         }
2388         prestate = chan->_state;
2389
2390         if (!ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_EMULATE_DTMF | AST_FLAG_IN_DTMF) && 
2391             !ast_strlen_zero(chan->dtmfq) && 
2392                 (ast_tvzero(chan->dtmf_tv) || ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) > AST_MIN_DTMF_GAP) ) {
2393                 /* We have DTMF that has been deferred.  Return it now */
2394                 chan->dtmff.subclass = chan->dtmfq[0];
2395                 /* Drop first digit from the buffer */
2396                 memmove(chan->dtmfq, chan->dtmfq + 1, sizeof(chan->dtmfq) - 1);
2397                 f = &chan->dtmff;
2398                 if (ast_test_flag(chan, AST_FLAG_END_DTMF_ONLY)) {
2399                         ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass, chan->name);
2400                         chan->dtmff.frametype = AST_FRAME_DTMF_END;
2401                 } else {
2402                         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);
2403                         chan->dtmff.frametype = AST_FRAME_DTMF_BEGIN;
2404                         ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
2405                         chan->emulate_dtmf_digit = f->subclass;
2406                         chan->emulate_dtmf_duration = AST_DEFAULT_EMULATE_DTMF_DURATION;
2407                 }
2408                 chan->dtmf_tv = ast_tvnow();
2409                 goto done;
2410         }
2411         
2412         /* Read and ignore anything on the alertpipe, but read only
2413            one sizeof(blah) per frame that we send from it */
2414         if (chan->alertpipe[0] > -1) {
2415                 int flags = fcntl(chan->alertpipe[0], F_GETFL);
2416                 /* For some odd reason, the alertpipe occasionally loses nonblocking status,
2417                  * which immediately causes a deadlock scenario.  Detect and prevent this. */
2418                 if ((flags & O_NONBLOCK) == 0) {
2419                         ast_log(LOG_ERROR, "Alertpipe on channel %s lost O_NONBLOCK?!!\n", chan->name);
2420                         if (fcntl(chan->alertpipe[0], F_SETFL, flags | O_NONBLOCK) < 0) {
2421                                 ast_log(LOG_WARNING, "Unable to set alertpipe nonblocking! (%d: %s)\n", errno, strerror(errno));
2422                                 f = &ast_null_frame;
2423                                 goto done;
2424                         }
2425                 }
2426                 if (read(chan->alertpipe[0], &blah, sizeof(blah)) < 0) {
2427                         ast_log(LOG_WARNING, "read() failed: %s\n", strerror(errno));
2428                 }
2429         }
2430
2431         if (chan->timingfd > -1 && chan->fdno == AST_TIMING_FD) {
2432                 enum ast_timing_event res;
2433
2434                 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
2435
2436                 res = ast_timer_get_event(chan->timingfd);
2437
2438                 switch (res) {
2439                 case AST_TIMING_EVENT_EXPIRED:
2440                         ast_timer_ack(chan->timingfd, 1);
2441
2442                         if (chan->timingfunc) {
2443                                 /* save a copy of func/data before unlocking the channel */
2444                                 int (*func)(const void *) = chan->timingfunc;
2445                                 void *data = chan->timingdata;
2446                                 ast_channel_unlock(chan);
2447                                 func(data);
2448                         } else {
2449                                 ast_timer_set_rate(chan->timingfd, 0);
2450                                 ast_channel_unlock(chan);
2451                         }
2452
2453                         /* cannot 'goto done' because the channel is already unlocked */
2454                         return &ast_null_frame;
2455
2456                 case AST_TIMING_EVENT_CONTINUOUS:
2457                         if (AST_LIST_EMPTY(&chan->readq) || 
2458                                 !AST_LIST_NEXT(AST_LIST_FIRST(&chan->readq), frame_list)) {
2459                                 ast_timer_disable_continuous(chan->timingfd);
2460                         }
2461                         break;
2462                 }
2463
2464         } else if (chan->fds[AST_GENERATOR_FD] > -1 && chan->fdno == AST_GENERATOR_FD) {
2465                 /* if the AST_GENERATOR_FD is set, call the generator with args
2466                  * set to -1 so it can do whatever it needs to.
2467                  */
2468                 void *tmp = chan->generatordata;
2469                 chan->generatordata = NULL;     /* reset to let ast_write get through */
2470                 chan->generator->generate(chan, tmp, -1, -1);
2471                 chan->generatordata = tmp;
2472                 f = &ast_null_frame;
2473                 goto done;
2474         }
2475
2476         /* Check for pending read queue */
2477         if (!AST_LIST_EMPTY(&chan->readq)) {
2478                 f = AST_LIST_REMOVE_HEAD(&chan->readq, frame_list);
2479                 /* Interpret hangup and return NULL */
2480                 /* XXX why not the same for frames from the channel ? */
2481                 if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP) {
2482                         cause = f->data.uint32;
2483                         ast_frfree(f);
2484                         f = NULL;
2485                 }
2486         } else {
2487                 chan->blocker = pthread_self();
2488                 if (ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
2489                         if (chan->tech->exception)
2490                                 f = chan->tech->exception(chan);
2491                         else {
2492                                 ast_log(LOG_WARNING, "Exception flag set on '%s', but no exception handler\n", chan->name);
2493                                 f = &ast_null_frame;
2494                         }
2495                         /* Clear the exception flag */
2496                         ast_clear_flag(chan, AST_FLAG_EXCEPTION);
2497                 } else if (chan->tech->read)
2498                         f = chan->tech->read(chan);
2499                 else
2500                         ast_log(LOG_WARNING, "No read routine on channel %s\n", chan->name);
2501         }
2502
2503         if (f) {
2504                 /* if the channel driver returned more than one frame, stuff the excess
2505                    into the readq for the next ast_read call (note that we can safely assume
2506                    that the readq is empty, because otherwise we would not have called into
2507                    the channel driver and f would be only a single frame)
2508                 */
2509                 if (AST_LIST_NEXT(f, frame_list)) {
2510                         AST_LIST_HEAD_SET_NOLOCK(&chan->readq, AST_LIST_NEXT(f, frame_list));
2511                         AST_LIST_NEXT(f, frame_list) = NULL;
2512                 }
2513
2514                 switch (f->frametype) {
2515                 case AST_FRAME_CONTROL:
2516                         if (f->subclass == AST_CONTROL_ANSWER) {
2517                                 if (!ast_test_flag(chan, AST_FLAG_OUTGOING)) {
2518                                         ast_debug(1, "Ignoring answer on an inbound call!\n");
2519                                         ast_frfree(f);
2520                                         f = &ast_null_frame;
2521                                 } else if (prestate == AST_STATE_UP) {
2522                                         ast_debug(1, "Dropping duplicate answer!\n");
2523                                         ast_frfree(f);
2524                                         f = &ast_null_frame;
2525                                 } else {
2526                                         /* Answer the CDR */
2527                                         ast_setstate(chan, AST_STATE_UP);
2528                                         /* removed a call to ast_cdr_answer(chan->cdr) from here. */
2529                                 }
2530                         }
2531                         break;
2532                 case AST_FRAME_DTMF_END:
2533                         send_dtmf_event(chan, "Received", f->subclass, "No", "Yes");
2534                         ast_log(LOG_DTMF, "DTMF end '%c' received on %s, duration %ld ms\n", f->subclass, chan->name, f->len);
2535                         /* Queue it up if DTMF is deffered, or if DTMF emulation is forced.
2536                          * However, only let emulation be forced if the other end cares about BEGIN frames */
2537                         if ( ast_test_flag(chan, AST_FLAG_DEFER_DTMF) ||
2538                                 (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !ast_test_flag(chan, AST_FLAG_END_DTMF_ONLY)) ) {
2539                                 if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2) {
2540                                         ast_log(LOG_DTMF, "DTMF end '%c' put into dtmf queue on %s\n", f->subclass, chan->name);
2541                                         chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
2542                                 } else
2543                                         ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
2544                                 ast_frfree(f);
2545                                 f = &ast_null_frame;
2546                         } else if (!ast_test_flag(chan, AST_FLAG_IN_DTMF | AST_FLAG_END_DTMF_ONLY)) {
2547                                 if (!ast_tvzero(chan->dtmf_tv) && 
2548                                     ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) < AST_MIN_DTMF_GAP) {
2549                                         /* If it hasn't been long enough, defer this digit */
2550                                         if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2) {
2551                                                 ast_log(LOG_DTMF, "DTMF end '%c' put into dtmf queue on %s\n", f->subclass, chan->name);
2552                                                 chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
2553                                         } else
2554                                                 ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
2555                                         ast_frfree(f);
2556                                         f = &ast_null_frame;
2557                                 } else {
2558                                         /* There was no begin, turn this into a begin and send the end later */
2559                                         f->frametype = AST_FRAME_DTMF_BEGIN;
2560                                         ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
2561                                         chan->emulate_dtmf_digit = f->subclass;
2562                                         chan->dtmf_tv = ast_tvnow();
2563                                         if (f->len) {
2564                                                 if (f->len > AST_MIN_DTMF_DURATION)
2565                                                         chan->emulate_dtmf_duration = f->len;
2566                                                 else 
2567                                                         chan->emulate_dtmf_duration = AST_MIN_DTMF_DURATION;
2568                                         } else
2569                                                 chan->emulate_dtmf_duration = AST_DEFAULT_EMULATE_DTMF_DURATION;
2570                                         ast_log(LOG_DTMF, "DTMF begin emulation of '%c' with duration %u queued on %s\n", f->subclass, chan->emulate_dtmf_duration, chan->name);
2571                                 }
2572                                 if (chan->audiohooks) {
2573                                         struct ast_frame *old_frame = f;
2574                                         /*!
2575                                          * \todo XXX It is possible to write a digit to the audiohook twice
2576                                          * if the digit was originally read while the channel was in autoservice. */
2577                                         f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
2578                                         if (old_frame != f)
2579                                                 ast_frfree(old_frame);
2580                                 }
2581                         } else {
2582                                 struct timeval now = ast_tvnow();
2583                                 if (ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
2584                                         ast_log(LOG_DTMF, "DTMF end accepted with begin '%c' on %s\n", f->subclass, chan->name);
2585                                         ast_clear_flag(chan, AST_FLAG_IN_DTMF);
2586                                         if (!f->len)
2587                                                 f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
2588                                 } else if (!f->len) {
2589                                         ast_log(LOG_DTMF, "DTMF end accepted without begin '%c' on %s\n", f->subclass, chan->name);
2590                                         f->len = AST_MIN_DTMF_DURATION;
2591                                 }
2592                                 if (f->len < AST_MIN_DTMF_DURATION && !ast_test_flag(chan, AST_FLAG_END_DTMF_ONLY)) {
2593                                         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);
2594                                         ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
2595                                         chan->emulate_dtmf_digit = f->subclass;
2596                                         chan->emulate_dtmf_duration = AST_MIN_DTMF_DURATION - f->len;
2597                                         ast_frfree(f);
2598                                         f = &ast_null_frame;
2599                                 } else {
2600                                         ast_log(LOG_DTMF, "DTMF end passthrough '%c' on %s\n", f->subclass, chan->name);
2601                                         if (f->len < AST_MIN_DTMF_DURATION) {
2602                                                 f->len = AST_MIN_DTMF_DURATION;
2603                                         }
2604                                         chan->dtmf_tv = now;
2605                                 }
2606                                 if (chan->audiohooks) {
2607                                         struct ast_frame *old_frame = f;
2608                                         f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
2609                                         if (old_frame != f)
2610                                                 ast_frfree(old_frame);
2611                                 }
2612                         }
2613                         break;
2614                 case AST_FRAME_DTMF_BEGIN:
2615                         send_dtmf_event(chan, "Received", f->subclass, "Yes", "No");
2616                         ast_log(LOG_DTMF, "DTMF begin '%c' received on %s\n", f->subclass, chan->name);
2617                         if ( ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_END_DTMF_ONLY | AST_FLAG_EMULATE_DTMF) || 
2618                             (!ast_tvzero(chan->dtmf_tv) && 
2619                               ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) < AST_MIN_DTMF_GAP) ) {
2620                                 ast_log(LOG_DTMF, "DTMF begin ignored '%c' on %s\n", f->subclass, chan->name);
2621                                 ast_frfree(f);
2622                                 f = &ast_null_frame;
2623                         } else {
2624                                 ast_set_flag(chan, AST_FLAG_IN_DTMF);
2625                                 chan->dtmf_tv = ast_tvnow();
2626                                 ast_log(LOG_DTMF, "DTMF begin passthrough '%c' on %s\n", f->subclass, chan->name);
2627                         }
2628                         break;
2629                 case AST_FRAME_NULL:
2630                         /* The EMULATE_DTMF flag must be cleared here as opposed to when the duration
2631                          * is reached , because we want to make sure we pass at least one
2632                          * voice frame through before starting the next digit, to ensure a gap
2633                          * between DTMF digits. */
2634                         if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF)) {
2635                                 struct timeval now = ast_tvnow();
2636                                 if (!chan->emulate_dtmf_duration) {
2637                                         ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
2638                                         chan->emulate_dtmf_digit = 0;
2639                                 } else if (ast_tvdiff_ms(now, chan->dtmf_tv) >= chan->emulate_dtmf_duration) {
2640                                         chan->emulate_dtmf_duration = 0;
2641                                         ast_frfree(f);
2642                                         f = &chan->dtmff;
2643                                         f->frametype = AST_FRAME_DTMF_END;
2644                                         f->subclass = chan->emulate_dtmf_digit;
2645                                         f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
2646                                         chan->dtmf_tv = now;
2647                                         ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
2648                                         chan->emulate_dtmf_digit = 0;
2649                                         ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass, chan->name);
2650                                 }
2651                         }
2652                         break;
2653                 case AST_FRAME_VOICE:
2654                         /* The EMULATE_DTMF flag must be cleared here as opposed to when the duration
2655                          * is reached , because we want to make sure we pass at least one
2656                          * voice frame through before starting the next digit, to ensure a gap
2657                          * between DTMF digits. */
2658                         if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !chan->emulate_dtmf_duration) {
2659                                 ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
2660                                 chan->emulate_dtmf_digit = 0;
2661                         }
2662
2663                         if (dropaudio || ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
2664                                 if (dropaudio)
2665                                         ast_read_generator_actions(chan, f);
2666                                 ast_frfree(f);
2667                                 f = &ast_null_frame;
2668                         }
2669
2670                         if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
2671                                 struct timeval now = ast_tvnow();
2672                                 if (ast_tvdiff_ms(now, chan->dtmf_tv) >= chan->emulate_dtmf_duration) {
2673                                         chan->emulate_dtmf_duration = 0;
2674                                         ast_frfree(f);
2675                                         f = &chan->dtmff;
2676                                         f->frametype = AST_FRAME_DTMF_END;
2677                                         f->subclass = chan->emulate_dtmf_digit;
2678                                         f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
2679                                         chan->dtmf_tv = now;
2680                                         if (chan->audiohooks) {
2681                                                 struct ast_frame *old_frame = f;
2682                                                 f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
2683                                                 if (old_frame != f)
2684                                                         ast_frfree(old_frame);
2685                                         }
2686                                         ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass, chan->name);
2687                                 } else {
2688                                         /* Drop voice frames while we're still in the middle of the digit */
2689                                         ast_frfree(f);
2690                                         f = &ast_null_frame;
2691                                 }
2692                         } else if ((f->frametype == AST_FRAME_VOICE) && !(f->subclass & chan->nativeformats)) {
2693                                 /* This frame is not one of the current native formats -- drop it on the floor */
2694                                 char to[200];
2695                                 ast_log(LOG_NOTICE, "Dropping incompatible voice frame on %s of format %s since our native format has changed to %s\n",
2696                                         chan->name, ast_getformatname(f->subclass), ast_getformatname_multiple(to, sizeof(to), chan->nativeformats));
2697                                 ast_frfree(f);
2698                                 f = &ast_null_frame;
2699                         } else if ((f->frametype == AST_FRAME_VOICE)) {
2700                                 /* Send frame to audiohooks if present */
2701                                 if (chan->audiohooks) {
2702                                         struct ast_frame *old_frame = f;
2703                                         f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
2704                                         if (old_frame != f)
2705                                                 ast_frfree(old_frame);
2706                                 }
2707                                 if (chan->monitor && chan->monitor->read_stream ) {
2708                                         /* XXX what does this do ? */
2709 #ifndef MONITOR_CONSTANT_DELAY
2710                                         int jump = chan->outsmpl - chan->insmpl - 4 * f->samples;
2711                                         if (jump >= 0) {
2712                                                 jump = chan->outsmpl - chan->insmpl;
2713                                                 if (ast_seekstream(chan->monitor->read_stream, jump, SEEK_FORCECUR) == -1)
2714                                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
2715                                                 chan->insmpl += jump + f->samples;
2716                                         } else
2717                                                 chan->insmpl+= f->samples;
2718 #else
2719                                         int jump = chan->outsmpl - chan->insmpl;
2720                                         if (jump - MONITOR_DELAY >= 0) {
2721                                                 if (ast_seekstream(chan->monitor->read_stream, jump - f->samples, SEEK_FORCECUR) == -1)
2722                                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
2723                                                 chan->insmpl += jump;
2724                                         } else
2725                                                 chan->insmpl += f->samples;
2726 #endif
2727                                         if (chan->monitor->state == AST_MONITOR_RUNNING) {
2728                                                 if (ast_writestream(chan->monitor->read_stream, f) < 0)
2729                                                         ast_log(LOG_WARNING, "Failed to write data to channel monitor read stream\n");
2730                                         }
2731                                 }
2732
2733                                 if (chan->readtrans && (f = ast_translate(chan->readtrans, f, 1)) == NULL)
2734                                         f = &ast_null_frame;
2735                                 else
2736                                         /* Run generator sitting on the line if timing device not available
2737                                          * and synchronous generation of outgoing frames is necessary       */
2738                                         ast_read_generator_actions(chan, f);
2739                         }
2740                 default:
2741                         /* Just pass it on! */
2742                         break;
2743                 }
2744         } else {
2745                 /* Make sure we always return NULL in the future */
2746                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
2747                 if (cause)
2748                         chan->hangupcause = cause;
2749                 if (chan->generator)
2750                         ast_deactivate_generator(chan);
2751                 /* We no longer End the CDR here */
2752         }
2753
2754         /* High bit prints debugging */
2755         if (chan->fin & DEBUGCHAN_FLAG)
2756                 ast_frame_dump(chan->name, f, "<<");
2757         chan->fin = FRAMECOUNT_INC(chan->fin);
2758
2759 done:
2760         if (chan->music_state && chan->generator && chan->generator->digit && f && f->frametype == AST_FRAME_DTMF_END)
2761                 chan->generator->digit(chan, f->subclass);
2762
2763         ast_channel_unlock(chan);
2764         return f;
2765 }
2766
2767 int ast_internal_timing_enabled(struct ast_channel *chan)
2768 {
2769         int ret = ast_opt_internal_timing && chan->timingfd > -1;
2770         ast_debug(5, "Internal timing is %s (option_internal_timing=%d chan->timingfd=%d)\n", ret? "enabled": "disabled", ast_opt_internal_timing, chan->timingfd);
2771         return ret;
2772 }
2773
2774 struct ast_frame *ast_read(struct ast_channel *chan)
2775 {
2776         return __ast_read(chan, 0);
2777 }
2778
2779 struct ast_frame *ast_read_noaudio(struct ast_channel *chan)
2780 {
2781         return __ast_read(chan, 1);
2782 }
2783
2784 int ast_indicate(struct ast_channel *chan, int condition)
2785 {
2786         return ast_indicate_data(chan, condition, NULL, 0);
2787 }
2788
2789 int ast_indicate_data(struct ast_channel *chan, int condition, const void *data, size_t datalen)
2790 {
2791         int res = -1;
2792
2793         ast_channel_lock(chan);
2794         /* Stop if we're a zombie or need a soft hangup */
2795         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2796                 ast_channel_unlock(chan);
2797                 return -1;
2798         }
2799         if (chan->tech->indicate)
2800                 res = chan->tech->indicate(chan, condition, data, datalen);
2801         ast_channel_unlock(chan);
2802         if (!chan->tech->indicate || res) {
2803                 /*
2804                  * Device does not support (that) indication, lets fake
2805                  * it by doing our own tone generation. (PM2002)
2806                  */
2807                 if (condition < 0)
2808                         ast_playtones_stop(chan);
2809                 else {
2810                         const struct ind_tone_zone_sound *ts = NULL;
2811                         switch (condition) {
2812                         case AST_CONTROL_RINGING:
2813                                 ts = ast_get_indication_tone(chan->zone, "ring");
2814                                 break;
2815                         case AST_CONTROL_BUSY:
2816                                 ts = ast_get_indication_tone(chan->zone, "busy");
2817                                 break;
2818                         case AST_CONTROL_CONGESTION:
2819                                 ts = ast_get_indication_tone(chan->zone, "congestion");
2820                                 break;
2821                         }
2822                         if (ts && ts->data[0]) {
2823                                 ast_debug(1, "Driver for channel '%s' does not support indication %d, emulating it\n", chan->name, condition);
2824                                 ast_playtones_start(chan,0,ts->data, 1);
2825                                 res = 0;
2826                                 chan->visible_indication = condition;
2827                         } else if (condition == AST_CONTROL_PROGRESS) {
2828                                 /* ast_playtones_stop(chan); */
2829                         } else if (condition == AST_CONTROL_PROCEEDING) {
2830                                 /* Do nothing, really */
2831                         } else if (condition == AST_CONTROL_HOLD) {
2832                                 /* Do nothing.... */
2833                         } else if (condition == AST_CONTROL_UNHOLD) {
2834                                 /* Do nothing.... */
2835                         } else if (condition == AST_CONTROL_VIDUPDATE) {
2836                                 /* Do nothing.... */
2837                         } else if (condition == AST_CONTROL_SRCUPDATE) {
2838                                 /* Do nothing... */
2839                         } else {
2840                                 /* not handled */
2841                                 ast_log(LOG_WARNING, "Unable to handle indication %d for '%s'\n", condition, chan->name);
2842                                 res = -1;
2843                         }
2844                 }
2845         } else
2846                 chan->visible_indication = condition;
2847
2848         return res;
2849 }
2850
2851 int ast_recvchar(struct ast_channel *chan, int timeout)
2852 {
2853         int c;
2854         char *buf = ast_recvtext(chan, timeout);
2855         if (buf == NULL)
2856                 return -1;      /* error or timeout */
2857         c = *(unsigned char *)buf;
2858         ast_free(buf);
2859         return c;
2860 }
2861
2862 char *ast_recvtext(struct ast_channel *chan, int timeout)
2863 {
2864         int res, done = 0;
2865         char *buf = NULL;
2866         
2867         while (!done) {
2868                 struct ast_frame *f;
2869                 if (ast_check_hangup(chan))
2870                         break;
2871                 res = ast_waitfor(chan, timeout);
2872                 if (res <= 0) /* timeout or error */
2873                         break;
2874                 timeout = res;  /* update timeout */
2875                 f = ast_read(chan);
2876                 if (f == NULL)
2877                         break; /* no frame */
2878                 if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP)
2879                         done = 1;       /* force a break */
2880                 else if (f->frametype == AST_FRAME_TEXT) {              /* what we want */
2881                         buf = ast_strndup((char *) f->data.ptr, f->datalen);    /* dup and break */
2882                         done = 1;
2883                 }
2884                 ast_frfree(f);
2885         }
2886         return buf;
2887 }
2888
2889 int ast_sendtext(struct ast_channel *chan, const char *text)
2890 {
2891         int res = 0;
2892         /* Stop if we're a zombie or need a soft hangup */
2893         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
2894                 return -1;
2895         CHECK_BLOCKING(chan);
2896         if (chan->tech->send_text)
2897                 res = chan->tech->send_text(chan, text);
2898         ast_clear_flag(chan, AST_FLAG_BLOCKING);
2899         return res;
2900 }
2901
2902 int ast_senddigit_begin(struct ast_channel *chan, char digit)
2903 {
2904         /* Device does not support DTMF tones, lets fake
2905          * it by doing our own generation. */
2906         static const char* dtmf_tones[] = {
2907                 "941+1336", /* 0 */
2908                 "697+1209", /* 1 */
2909                 "697+1336", /* 2 */
2910                 "697+1477", /* 3 */
2911                 "770+1209", /* 4 */
2912                 "770+1336", /* 5 */
2913                 "770+1477", /* 6 */
2914                 "852+1209", /* 7 */
2915                 "852+1336", /* 8 */
2916                 "852+1477", /* 9 */
2917                 "697+1633", /* A */
2918                 "770+1633", /* B */
2919                 "852+1633", /* C */
2920                 "941+1633", /* D */
2921                 "941+1209", /* * */
2922                 "941+1477"  /* # */
2923         };
2924
2925         if (!chan->tech->send_digit_begin)
2926                 return 0;
2927
2928         if (!chan->tech->send_digit_begin(chan, digit))
2929                 return 0;
2930
2931         if (digit >= '0' && digit <='9')
2932                 ast_playtones_start(chan, 0, dtmf_tones[digit-'0'], 0);
2933         else if (digit >= 'A' && digit <= 'D')
2934                 ast_playtones_start(chan, 0, dtmf_tones[digit-'A'+10], 0);
2935         else if (digit == '*')
2936                 ast_playtones_start(chan, 0, dtmf_tones[14], 0);
2937         else if (digit == '#')
2938                 ast_playtones_start(chan, 0, dtmf_tones[15], 0);
2939         else {
2940                 /* not handled */
2941                 ast_debug(1, "Unable to generate DTMF tone '%c' for '%s'\n", digit, chan->name);
2942         }
2943
2944         return 0;
2945 }
2946
2947 int ast_senddigit_end(struct ast_channel *chan, char digit, unsigned int duration)
2948 {
2949         int res = -1;
2950
2951         if (chan->tech->send_digit_end)
2952                 res = chan->tech->send_digit_end(chan, digit, duration);
2953
2954         if (res && chan->generator)
2955                 ast_playtones_stop(chan);
2956         
2957         return 0;
2958 }
2959
2960 int ast_senddigit(struct ast_channel *chan, char digit, unsigned int duration)
2961 {
2962         if (chan->tech->send_digit_begin) {
2963                 ast_senddigit_begin(chan, digit);
2964                 ast_safe_sleep(chan, (duration >= AST_DEFAULT_EMULATE_DTMF_DURATION ? duration : AST_DEFAULT_EMULATE_DTMF_DURATION));
2965         }
2966         
2967         return ast_senddigit_end(chan, digit, (duration >= AST_DEFAULT_EMULATE_DTMF_DURATION ? duration : AST_DEFAULT_EMULATE_DTMF_DURATION));
2968 }
2969
2970 int ast_prod(struct ast_channel *chan)
2971 {
2972         struct ast_frame a = { AST_FRAME_VOICE };
2973         char nothing[128];
2974
2975         /* Send an empty audio frame to get things moving */
2976         if (chan->_state != AST_STATE_UP) {
2977                 ast_debug(1, "Prodding channel '%s'\n", chan->name);
2978                 a.subclass = chan->rawwriteformat;
2979                 a.data.ptr = nothing + AST_FRIENDLY_OFFSET;
2980                 a.src = "ast_prod";
2981                 if (ast_write(chan, &a))
2982                         ast_log(LOG_WARNING, "Prodding channel '%s' failed\n", chan->name);
2983         }
2984         return 0;
2985 }
2986
2987 int ast_write_video(struct ast_channel *chan, struct ast_frame *fr)
2988 {
2989         int res;
2990         if (!chan->tech->write_video)
2991                 return 0;
2992         res = ast_write(chan, fr);
2993         if (!res)
2994                 res = 1;
2995         return res;
2996 }
2997
2998 int ast_write(struct ast_channel *chan, struct ast_frame *fr)
2999 {
3000         int res = -1;
3001         struct ast_frame *f = NULL, *f2 = NULL;
3002         int count = 0;
3003
3004         /*Deadlock avoidance*/
3005         while(ast_channel_trylock(chan)) {
3006                 /*cannot goto done since the channel is not locked*/
3007                 if(count++ > 10) {
3008                         ast_debug(1, "Deadlock avoided for write to channel '%s'\n", chan->name);
3009                         return 0;
3010                 }
3011                 usleep(1);
3012         }
3013         /* Stop if we're a zombie or need a soft hangup */
3014         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
3015                 goto done;
3016
3017         /* Handle any pending masquerades */
3018         if (chan->masq && ast_do_masquerade(chan)) {
3019                 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
3020                 goto done;
3021         }
3022         if (chan->masqr) {
3023                 res = 0;        /* XXX explain, why 0 ? */
3024                 goto done;
3025         }
3026         if (chan->generatordata) {
3027                 if (ast_test_flag(chan, AST_FLAG_WRITE_INT))
3028                         ast_deactivate_generator(chan);
3029                 else {
3030                         if (fr->frametype == AST_FRAME_DTMF_END) {
3031                                 /* There is a generator running while we're in the middle of a digit.
3032                                  * It's probably inband DTMF, so go ahead and pass it so it can
3033                                  * stop the generator */
3034                                 ast_clear_flag(chan, AST_FLAG_BLOCKING);
3035                                 ast_channel_unlock(chan);
3036                                 res = ast_senddigit_end(chan, fr->subclass, fr->len);
3037                                 ast_channel_lock(chan);
3038                                 CHECK_BLOCKING(chan);
3039                         } else if (fr->frametype == AST_FRAME_CONTROL && fr->subclass == AST_CONTROL_UNHOLD) {
3040                                 /* This is a side case where Echo is basically being called and the person put themselves on hold and took themselves off hold */
3041                                 res = (chan->tech->indicate == NULL) ? 0 :
3042                                         chan->tech->indicate(chan, fr->subclass, fr->data.ptr, fr->datalen);
3043                         }
3044                         res = 0;        /* XXX explain, why 0 ? */
3045                         goto done;
3046                 }
3047         }
3048         /* High bit prints debugging */
3049         if (chan->fout & DEBUGCHAN_FLAG)
3050                 ast_frame_dump(chan->name, fr, ">>");
3051         CHECK_BLOCKING(chan);
3052         switch (fr->frametype) {
3053         case AST_FRAME_CONTROL:
3054                 res = (chan->tech->indicate == NULL) ? 0 :
3055                         chan->tech->indicate(chan, fr->subclass, fr->data.ptr, fr->datalen);
3056                 break;
3057         case AST_FRAME_DTMF_BEGIN:
3058                 if (chan->audiohooks) {
3059                         struct ast_frame *old_frame = fr;
3060                         fr = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_WRITE, fr);
3061                         if (old_frame != fr)
3062                                 f = fr;
3063                 }
3064                 send_dtmf_event(chan, "Sent", fr->subclass, "Yes", "No");
3065                 ast_clear_flag(chan, AST_FLAG_BLOCKING);
3066                 ast_channel_unlock(chan);
3067                 res = ast_senddigit_begin(chan, fr->subclass);
3068                 ast_channel_lock(chan);
3069                 CHECK_BLOCKING(chan);
3070                 break;
3071         case AST_FRAME_DTMF_END:
3072                 if (chan->audiohooks) {
3073                         struct ast_frame *old_frame = fr;
3074                         fr = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_WRITE, fr);
3075                         if (old_frame != fr)
3076                                 f = fr;
3077                 }
3078                 send_dtmf_event(chan, "Sent", fr->subclass, "No", "Yes");
3079                 ast_clear_flag(chan, AST_FLAG_BLOCKING);
3080                 ast_channel_unlock(chan);
3081                 res = ast_senddigit_end(chan, fr->subclass, fr->len);
3082                 ast_channel_lock(chan);
3083                 CHECK_BLOCKING(chan);
3084                 break;
3085         case AST_FRAME_TEXT:
3086                 if (fr->subclass == AST_FORMAT_T140) {
3087                         res = (chan->tech->write_text == NULL) ? 0 :
3088                                 chan->tech->write_text(chan, fr);
3089                 } else {
3090                         res = (chan->tech->send_text == NULL) ? 0 :
3091                                 chan->tech->send_text(chan, (char *) fr->data.ptr);
3092                 }
3093                 break;
3094         case AST_FRAME_HTML:
3095                 res = (chan->tech->send_html == NULL) ? 0 :
3096                         chan->tech->send_html(chan, fr->subclass, (char *) fr->data.ptr, fr->datalen);
3097                 break;
3098         case AST_FRAME_VIDEO:
3099                 /* XXX Handle translation of video codecs one day XXX */
3100                 res = (chan->tech->write_video == NULL) ? 0 :
3101                         chan->tech->write_video(chan, fr);
3102                 break;
3103         case AST_FRAME_MODEM:
3104                 res = (chan->tech->write == NULL) ? 0 :
3105                         chan->tech->write(chan, fr);
3106                 break;
3107         case AST_FRAME_VOICE:
3108                 if (chan->tech->write == NULL)
3109                         break;  /*! \todo XXX should return 0 maybe ? */
3110
3111                 /* If audiohooks are present, write the frame out */
3112                 if (chan->audiohooks) {
3113                         struct ast_frame *old_frame = fr;
3114                         fr = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_WRITE, fr);
3115                         if (old_frame != fr)
3116                                 f2 = fr;
3117                 }
3118
3119                 /* If the frame is in the raw write format, then it's easy... just use the frame - otherwise we will have to translate */
3120                 if (fr->subclass == chan->rawwriteformat)
3121                         f = fr;
3122                 else
3123                         f = (chan->writetrans) ? ast_translate(chan->writetrans, fr, 0) : fr;
3124
3125                 if (!f) {
3126                         res = 0;
3127                         break;
3128                 }
3129
3130                 /* If Monitor is running on this channel, then we have to write frames out there too */
3131                 if (chan->monitor && chan->monitor->write_stream) {
3132                         /* XXX must explain this code */
3133 #ifndef MONITOR_CONSTANT_DELAY
3134                         int jump = chan->insmpl - chan->outsmpl - 4 * f->samples;
3135                         if (jump >= 0) {
3136                                 jump = chan->insmpl - chan->outsmpl;
3137                                 if (ast_seekstream(chan->monitor->write_stream, jump, SEEK_FORCECUR) == -1)
3138                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
3139                                 chan->outsmpl += jump + f->samples;
3140                         } else
3141                                 chan->outsmpl += f->samples;
3142 #else
3143                         int jump = chan->insmpl - chan->outsmpl;
3144                         if (jump - MONITOR_DELAY >= 0) {
3145                                 if (ast_seekstream(chan->monitor->write_stream, jump - f->samples, SEEK_FORCECUR) == -1)
3146                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
3147                                 chan->outsmpl += jump;
3148                         } else
3149                                 chan->outsmpl += f->samples;
3150 #endif
3151                         if (chan->monitor->state == AST_MONITOR_RUNNING) {
3152                                 if (ast_writestream(chan->monitor->write_stream, f) < 0)
3153                                         ast_log(LOG_WARNING, "Failed to write data to channel monitor write stream\n");
3154                         }
3155                 }
3156
3157                 if (f) 
3158                         res = chan->tech->write(chan,f);
3159                 else
3160                         res = 0;
3161                 break;
3162         case AST_FRAME_NULL:
3163         case AST_FRAME_IAX:
3164                 /* Ignore these */
3165                 res = 0;
3166                 break;
3167         default:
3168                 /* At this point, fr is the incoming frame and f is NULL.  Channels do
3169                  * not expect to get NULL as a frame pointer and will segfault.  Hence,
3170                  * we output the original frame passed in. */
3171                 res = chan->tech->write(chan, fr);
3172                 break;
3173         }
3174
3175         if (f && f != fr)
3176                 ast_frfree(f);
3177         if (f2)
3178                 ast_frfree(f2);
3179         ast_clear_flag(chan, AST_FLAG_BLOCKING);
3180         /* Consider a write failure to force a soft hangup */
3181         if (res < 0)
3182                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
3183         else {
3184                 chan->fout = FRAMECOUNT_INC(chan->fout);
3185         }
3186 done:
3187         ast_channel_unlock(chan);
3188         return res;
3189 }
3190
3191 static int set_format(struct ast_channel *chan, int fmt, int *rawformat, int *format,
3192                       struct ast_trans_pvt **trans, const int direction)
3193 {
3194         int native;
3195         int res;
3196         char from[200], to[200];
3197         
3198         /* Make sure we only consider audio */
3199         fmt &= AST_FORMAT_AUDIO_MASK;
3200         
3201         native = chan->nativeformats;
3202
3203         if (!fmt || !native)    /* No audio requested */
3204                 return 0;       /* Let's try a call without any sounds (video, text) */
3205         
3206         /* Find a translation path from the native format to one of the desired formats */
3207         if (!direction)
3208                 /* reading */
3209                 res = ast_translator_best_choice(&fmt, &native);
3210         else
3211                 /* writing */
3212                 res = ast_translator_best_choice(&native, &fmt);
3213
3214         if (res < 0) {
3215                 ast_log(LOG_WARNING, "Unable to find a codec translation path from %s to %s\n",
3216                         ast_getformatname_multiple(from, sizeof(from), native),
3217                         ast_getformatname_multiple(to, sizeof(to), fmt));
3218                 return -1;
3219         }
3220         
3221         /* Now we have a good choice for both. */
3222         ast_channel_lock(chan);
3223
3224         if ((*rawformat == native) && (*format == fmt) && ((*rawformat == *format) || (*trans))) {
3225                 /* the channel is already in these formats, so nothing to do */
3226                 ast_channel_unlock(chan);
3227                 return 0;
3228         }
3229
3230         *rawformat = native;
3231         /* User perspective is fmt */
3232         *format = fmt;
3233         /* Free any read translation we have right now */
3234         if (*trans)
3235                 ast_translator_free_path(*trans);
3236         /* Build a translation path from the raw format to the desired format */
3237         if (!direction)
3238                 /* reading */
3239                 *trans = ast_translator_build_path(*format, *rawformat);
3240         else
3241                 /* writing */
3242                 *trans = ast_translator_build_path(*rawformat, *format);
3243         ast_channel_unlock(chan);
3244         ast_debug(1, "Set channel %s to %s format %s\n", chan->name,
3245                 direction ? "write" : "read", ast_getformatname(fmt));
3246         return 0;
3247 }
3248
3249 int ast_set_read_format(struct ast_channel *chan, int fmt)
3250 {
3251         return set_format(chan, fmt, &chan->rawreadformat, &chan->readformat,
3252                           &chan->readtrans, 0);
3253 }
3254
3255 int ast_set_write_format(struct ast_channel *chan, int fmt)
3256 {
3257         return set_format(chan, fmt, &chan->rawwriteformat, &chan->writeformat,
3258                           &chan->writetrans, 1);
3259 }
3260
3261 const char *ast_channel_reason2str(int reason)
3262 {
3263         switch (reason) /* the following appear to be the only ones actually returned by request_and_dial */
3264         {
3265         case 0:
3266                 return "Call Failure (not BUSY, and not NO_ANSWER, maybe Circuit busy or down?)";
3267         case AST_CONTROL_HANGUP:
3268                 return "Hangup";
3269         case AST_CONTROL_RING:
3270                 return "Local Ring";
3271         case AST_CONTROL_RINGING:
3272                 return "Remote end Ringing";
3273         case AST_CONTROL_ANSWER:
3274                 return "Remote end has Answered";
3275         case AST_CONTROL_BUSY:
3276                 return "Remote end is Busy";
3277         case AST_CONTROL_CONGESTION:
3278                 return "Congestion (circuits busy)";
3279         default:
3280                 return "Unknown Reason!!";
3281         }
3282 }
3283
3284 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)
3285 {
3286         int dummy_outstate;
3287         int cause = 0;
3288         struct ast_channel *chan;
3289         int res = 0;
3290         int last_subclass = 0;
3291         
3292         if (outstate)
3293                 *outstate = 0;
3294         else
3295                 outstate = &dummy_outstate;     /* make outstate always a valid pointer */
3296
3297         chan = ast_request(type, format, data, &cause);
3298         if (!chan) {
3299                 ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
3300                 /* compute error and return */
3301                 if (cause == AST_CAUSE_BUSY)
3302                         *outstate = AST_CONTROL_BUSY;
3303                 else if (cause == AST_CAUSE_CONGESTION)
3304                         *outstate = AST_CONTROL_CONGESTION;
3305                 return NULL;
3306         }
3307
3308         if (oh) {
3309                 if (oh->vars)   
3310                         ast_set_variables(chan, oh->vars);
3311                 /* XXX why is this necessary, for the parent_channel perhaps ? */
3312                 if (!ast_strlen_zero(oh->cid_num) && !ast_strlen_zero(oh->cid_name))
3313                         ast_set_callerid(chan, oh->cid_num, oh->cid_name, oh->cid_num);
3314                 if (oh->parent_channel) {
3315                         ast_channel_inherit_variables(oh->parent_channel, chan);
3316                         ast_channel_datastore_inherit(oh->parent_channel, chan);
3317                 }
3318                 if (oh->account)
3319                         ast_cdr_setaccount(chan, oh->account);  
3320         }
3321         ast_set_callerid(chan, cid_num, cid_name, cid_num);
3322
3323         if (ast_call(chan, data, 0)) {  /* ast_call failed... */
3324                 ast_log(LOG_NOTICE, "Unable to call channel %s/%s\n", type, (char *)data);
3325         } else {
3326                 res = 1;        /* mark success in case chan->_state is already AST_STATE_UP */
3327                 while (timeout && chan->_state != AST_STATE_UP) {
3328                         struct ast_frame *f;
3329                         res = ast_waitfor(chan, timeout);
3330                         if (res <= 0) /* error, timeout, or done */
3331                                 break;
3332                         if (timeout > -1)
3333                                 timeout = res;
3334                         f = ast_read(chan);
3335                         if (!f) {
3336                                 *outstate = AST_CONTROL_HANGUP;
3337                                 res = 0;
3338                                 break;
3339                         }
3340                         if (f->frametype == AST_FRAME_CONTROL) {
3341                                 switch (f->subclass) {
3342                                 case AST_CONTROL_RINGING:       /* record but keep going */
3343                                         *outstate = f->subclass;
3344                                         break;
3345
3346                                 case AST_CONTROL_BUSY:
3347                                 case AST_CONTROL_CONGESTION:
3348                                 case AST_CONTROL_ANSWER:
3349                                         *outstate = f->subclass;
3350                                         timeout = 0;            /* trick to force exit from the while() */
3351                                         break;
3352
3353                                 /* Ignore these */
3354                                 case AST_CONTROL_PROGRESS:
3355                                 case AST_CONTROL_PROCEEDING:
3356                                 case AST_CONTROL_HOLD:
3357                                 case AST_CONTROL_UNHOLD:
3358                                 case AST_CONTROL_VIDUPDATE:
3359                                 case AST_CONTROL_SRCUPDATE:
3360                                 case -1:                        /* Ignore -- just stopping indications */
3361                                         break;
3362
3363                                 default:
3364                                         ast_log(LOG_NOTICE, "Don't know what to do with control frame %d\n", f->subclass);
3365                                 }
3366                                 last_subclass = f->subclass;
3367                         }
3368                         ast_frfree(f);
3369                 }
3370         }
3371
3372         /* Final fixups */
3373         if (oh) {
3374                 if (!ast_strlen_zero(oh->context))
3375                         ast_copy_string(chan->context, oh->context, sizeof(chan->context));
3376                 if (!ast_strlen_zero(oh->exten))
3377                         ast_copy_string(chan->exten, oh->exten, sizeof(chan->exten));
3378                 if (oh->priority)       
3379                         chan->priority = oh->priority;
3380         }
3381         if (chan->_state == AST_STATE_UP)
3382                 *outstate = AST_CONTROL_ANSWER;
3383
3384         if (res <= 0) {
3385                 if ( AST_CONTROL_RINGING == last_subclass ) 
3386                         chan->hangupcause = AST_CAUSE_NO_ANSWER;
3387                 if (!chan->cdr && (chan->cdr = ast_cdr_alloc()))
3388                         ast_cdr_init(chan->cdr, chan);
3389                 if (chan->cdr) {
3390                         char tmp[256];
3391                         snprintf(tmp, sizeof(tmp), "%s/%s", type, (char *)data);
3392                         ast_cdr_setapp(chan->cdr,"Dial",tmp);
3393                         ast_cdr_update(chan);
3394                         ast_cdr_start(chan->cdr);
3395                         ast_cdr_end(chan->cdr);
3396                         /* If the cause wasn't handled properly */
3397                         if (ast_cdr_disposition(chan->cdr,chan->hangupcause))
3398                                 ast_cdr_failed(chan->cdr);
3399                 }
3400                 ast_hangup(chan);
3401                 chan = NULL;
3402         }
3403         return chan;
3404 }
3405
3406 struct ast_channel *ast_request_and_dial(const char *type, int format, void *data, int timeout, int *outstate, const char *cidnum, const char *cidname)
3407 {
3408         return __ast_request_and_dial(type, format, data, timeout, outstate, cidnum, cidname, NULL);
3409 }
3410
3411 struct ast_channel *ast_request(const char *type, int format, void *data, int *cause)
3412 {
3413         struct chanlist *chan;
3414         struct ast_channel *c;
3415         int capabilities;
3416         int fmt;
3417         int res;
3418         int foo;
3419         int videoformat = format & AST_FORMAT_VIDEO_MASK;
3420         int textformat = format & AST_FORMAT_TEXT_MASK;
3421
3422         if (!cause)
3423                 cause = &foo;
3424         *cause = AST_CAUSE_NOTDEFINED;
3425
3426         if (AST_RWLIST_RDLOCK(&channels)) {
3427                 ast_log(LOG_WARNING, "Unable to lock channel list\n");
3428                 return NULL;
3429         }
3430
3431         AST_LIST_TRAVERSE(&backends, chan, list) {
3432                 if (strcasecmp(type, chan->tech->type))
3433                         continue;
3434
3435                 capabilities = chan->tech->capabilities;
3436                 fmt = format & AST_FORMAT_AUDIO_MASK;
3437                 if (fmt) {
3438                         /* We have audio - is it possible to connect the various calls to each other? 
3439                                 (Avoid this check for calls without audio, like text+video calls)
3440                         */
3441                         res = ast_translator_best_choice(&fmt, &capabilities);
3442                         if (res < 0) {
3443                                 ast_log(LOG_WARNING, "No translator path exists for channel type %s (native 0x%x) to 0x%x\n", type, chan->tech->capabilities, format);
3444                                 *cause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
3445                                 AST_RWLIST_UNLOCK(&channels);
3446                                 return NULL;
3447                         }
3448                 }
3449                 AST_RWLIST_UNLOCK(&channels);
3450                 if (!chan->tech->requester)
3451                         return NULL;
3452                 
3453                 if (!(c = chan->tech->requester(type, capabilities | videoformat | textformat, data, cause)))
3454                         return NULL;
3455                 
3456                 /* no need to generate a Newchannel event here; it is done in the channel_alloc call */
3457                 return c;
3458         }
3459
3460         ast_log(LOG_WARNING, "No channel type registered for '%s'\n", type);
3461         *cause = AST_CAUSE_NOSUCHDRIVER;
3462         AST_RWLIST_UNLOCK(&channels);
3463
3464         return NULL;
3465 }
3466
3467 int ast_call(struct ast_channel *chan, char *addr, int timeout)
3468 {
3469         /* Place an outgoing call, but don't wait any longer than timeout ms before returning.
3470            If the remote end does not answer within the timeout, then do NOT hang up, but
3471            return anyway.  */
3472         int res = -1;
3473         /* Stop if we're a zombie or need a soft hangup */
3474         ast_channel_lock(chan);
3475         if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
3476                 if (chan->cdr)
3477                         ast_set_flag(chan->cdr, AST_CDR_FLAG_DIALED);
3478                 if (chan->tech->call)
3479                         res = chan->tech->call(chan, addr, timeout);
3480                 ast_set_flag(chan, AST_FLAG_OUTGOING);
3481         }
3482         ast_channel_unlock(chan);
3483         return res;
3484 }
3485
3486 /*!
3487   \brief Transfer a call to dest, if the channel supports transfer
3488
3489   Called by:
3490         \arg app_transfer
3491         \arg the manager interface
3492 */
3493 int ast_transfer(struct ast_channel *chan, char *dest)
3494 {
3495         int res = -1;
3496
3497         /* Stop if we're a zombie or need a soft hangup */
3498         ast_channel_lock(chan);
3499         if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
3500                 if (chan->tech->transfer) {
3501                         res = chan->tech->transfer(chan, dest);
3502                         if (!res)
3503                                 res = 1;
3504                 } else
3505                         res = 0;
3506         }
3507         ast_channel_unlock(chan);
3508         return res;
3509 }
3510
3511 int ast_readstring(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders)
3512 {
3513         return ast_readstring_full(c, s, len, timeout, ftimeout, enders, -1, -1);
3514 }
3515
3516 int ast_readstring_full(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders, int audiofd, int ctrlfd)
3517 {
3518         int pos = 0;    /* index in the buffer where we accumulate digits */
3519         int to = ftimeout;
3520
3521         /* Stop if we're a zombie or need a soft hangup */
3522         if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
3523                 return -1;
3524         if (!len)
3525                 return -1;
3526         for (;;) {
3527                 int d;
3528                 if (c->stream) {
3529                         d = ast_waitstream_full(c, AST_DIGIT_ANY, audiofd, ctrlfd);
3530                         ast_stopstream(c);
3531                         usleep(1000);
3532                         if (!d)
3533                                 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
3534                 } else {
3535                         d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);