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