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