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