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