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