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