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