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