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