Adds pass-through support for codec CELT.
[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                 /*! CELT supports crazy high sample rates */
1085                 AST_FORMAT_CELT,
1086                 /*! Ick, LPC10 sounds terrible, but at least we have code for it, if you're tacky enough
1087                     to use it */
1088                 AST_FORMAT_LPC10,
1089                 /*! G.729a is faster than 723 and slightly less expensive */
1090                 AST_FORMAT_G729A,
1091                 /*! Down to G.723.1 which is proprietary but at least designed for voice */
1092                 AST_FORMAT_G723_1,
1093         };
1094         char buf[512];
1095         int x;
1096
1097         /* Find the first preferred codec in the format given */
1098         for (x = 0; x < ARRAY_LEN(prefs); x++) {
1099                 if (ast_format_cap_best_byid(cap, prefs[x], result)) {
1100                         return result;
1101                 }
1102         }
1103
1104         ast_format_clear(result);
1105         ast_log(LOG_WARNING, "Don't know any of %s formats\n", ast_getformatname_multiple(buf, sizeof(buf), cap));
1106
1107         return NULL;
1108 }
1109
1110 static const struct ast_channel_tech null_tech = {
1111         .type = "NULL",
1112         .description = "Null channel (should not see this)",
1113 };
1114
1115 static void ast_channel_destructor(void *obj);
1116 static void ast_dummy_channel_destructor(void *obj);
1117
1118 /*! \brief Create a new channel structure */
1119 static struct ast_channel * attribute_malloc __attribute__((format(printf, 13, 0)))
1120 __ast_channel_alloc_ap(int needqueue, int state, const char *cid_num, const char *cid_name,
1121                        const char *acctcode, const char *exten, const char *context,
1122                        const char *linkedid, const int amaflag, const char *file, int line,
1123                        const char *function, const char *name_fmt, va_list ap)
1124 {
1125         struct ast_channel *tmp;
1126         int x;
1127         int flags;
1128         struct varshead *headp;
1129         char *tech = "", *tech2 = NULL;
1130
1131         /* If shutting down, don't allocate any new channels */
1132         if (shutting_down) {
1133                 ast_log(LOG_WARNING, "Channel allocation failed: Refusing due to active shutdown\n");
1134                 return NULL;
1135         }
1136
1137 #if defined(REF_DEBUG)
1138         tmp = __ao2_alloc_debug(sizeof(*tmp), ast_channel_destructor, "", file, line,
1139                 function, 1);
1140 #elif defined(__AST_DEBUG_MALLOC)
1141         tmp = __ao2_alloc_debug(sizeof(*tmp), ast_channel_destructor, "", file, line,
1142                 function, 0);
1143 #else
1144         tmp = ao2_alloc(sizeof(*tmp), ast_channel_destructor);
1145 #endif
1146         if (!tmp) {
1147                 /* Channel structure allocation failure. */
1148                 return NULL;
1149         }
1150         if (!(tmp->nativeformats = ast_format_cap_alloc())) {
1151                 ao2_ref(tmp, -1);
1152                 /* format capabilities structure allocation failure */
1153                 return NULL;
1154         }
1155
1156         /*
1157          * Init file descriptors to unopened state so
1158          * the destructor can know not to close them.
1159          */
1160         tmp->timingfd = -1;
1161         for (x = 0; x < ARRAY_LEN(tmp->alertpipe); ++x) {
1162                 tmp->alertpipe[x] = -1;
1163         }
1164         for (x = 0; x < ARRAY_LEN(tmp->fds); ++x) {
1165                 tmp->fds[x] = -1;
1166         }
1167 #ifdef HAVE_EPOLL
1168         tmp->epfd = epoll_create(25);
1169 #endif
1170
1171         if (!(tmp->sched = ast_sched_context_create())) {
1172                 ast_log(LOG_WARNING, "Channel allocation failed: Unable to create schedule context\n");
1173                 return ast_channel_unref(tmp);
1174         }
1175         
1176         ast_party_dialed_init(&tmp->dialed);
1177         ast_party_caller_init(&tmp->caller);
1178         ast_party_connected_line_init(&tmp->connected);
1179         ast_party_redirecting_init(&tmp->redirecting);
1180
1181         if (cid_name) {
1182                 tmp->caller.id.name.valid = 1;
1183                 tmp->caller.id.name.str = ast_strdup(cid_name);
1184                 if (!tmp->caller.id.name.str) {
1185                         return ast_channel_unref(tmp);
1186                 }
1187         }
1188         if (cid_num) {
1189                 tmp->caller.id.number.valid = 1;
1190                 tmp->caller.id.number.str = ast_strdup(cid_num);
1191                 if (!tmp->caller.id.number.str) {
1192                         return ast_channel_unref(tmp);
1193                 }
1194         }
1195
1196         if ((tmp->timer = ast_timer_open())) {
1197                 if (strcmp(ast_timer_get_name(tmp->timer), "timerfd")) {
1198                         needqueue = 0;
1199                 }
1200                 tmp->timingfd = ast_timer_fd(tmp->timer);
1201         }
1202
1203         if (needqueue) {
1204                 if (pipe(tmp->alertpipe)) {
1205                         ast_log(LOG_WARNING, "Channel allocation failed: Can't create alert pipe! Try increasing max file descriptors with ulimit -n\n");
1206                         return ast_channel_unref(tmp);
1207                 } else {
1208                         flags = fcntl(tmp->alertpipe[0], F_GETFL);
1209                         if (fcntl(tmp->alertpipe[0], F_SETFL, flags | O_NONBLOCK) < 0) {
1210                                 ast_log(LOG_WARNING, "Channel allocation failed: Unable to set alertpipe nonblocking! (%d: %s)\n", errno, strerror(errno));
1211                                 return ast_channel_unref(tmp);
1212                         }
1213                         flags = fcntl(tmp->alertpipe[1], F_GETFL);
1214                         if (fcntl(tmp->alertpipe[1], F_SETFL, flags | O_NONBLOCK) < 0) {
1215                                 ast_log(LOG_WARNING, "Channel allocation failed: Unable to set alertpipe nonblocking! (%d: %s)\n", errno, strerror(errno));
1216                                 return ast_channel_unref(tmp);
1217                         }
1218                 }
1219         }
1220
1221         /*
1222          * This is the last place the channel constructor can fail.
1223          *
1224          * The destructor takes advantage of this fact to ensure that the
1225          * AST_CEL_CHANNEL_END is not posted if we have not posted the
1226          * AST_CEL_CHANNEL_START yet.
1227          */
1228         if ((ast_string_field_init(tmp, 128))) {
1229                 return ast_channel_unref(tmp);
1230         }
1231
1232         /* Always watch the alertpipe */
1233         ast_channel_set_fd(tmp, AST_ALERT_FD, tmp->alertpipe[0]);
1234         /* And timing pipe */
1235         ast_channel_set_fd(tmp, AST_TIMING_FD, tmp->timingfd);
1236
1237         /* Initial state */
1238         tmp->_state = state;
1239
1240         tmp->streamid = -1;
1241         
1242         tmp->fin = global_fin;
1243         tmp->fout = global_fout;
1244
1245         if (ast_strlen_zero(ast_config_AST_SYSTEM_NAME)) {
1246                 ast_string_field_build(tmp, uniqueid, "%li.%d", (long) time(NULL), 
1247                         ast_atomic_fetchadd_int(&uniqueint, 1));
1248         } else {
1249                 ast_string_field_build(tmp, uniqueid, "%s-%li.%d", ast_config_AST_SYSTEM_NAME, 
1250                         (long) time(NULL), ast_atomic_fetchadd_int(&uniqueint, 1));
1251         }
1252
1253         if (!ast_strlen_zero(linkedid)) {
1254                 ast_string_field_set(tmp, linkedid, linkedid);
1255         } else {
1256                 ast_string_field_set(tmp, linkedid, tmp->uniqueid);
1257         }
1258
1259         if (!ast_strlen_zero(name_fmt)) {
1260                 char *slash, *slash2;
1261                 /* Almost every channel is calling this function, and setting the name via the ast_string_field_build() call.
1262                  * And they all use slightly different formats for their name string.
1263                  * This means, to set the name here, we have to accept variable args, and call the string_field_build from here.
1264                  * This means, that the stringfields must have a routine that takes the va_lists directly, and 
1265                  * uses them to build the string, instead of forming the va_lists internally from the vararg ... list.
1266                  * This new function was written so this can be accomplished.
1267                  */
1268                 ast_string_field_build_va(tmp, name, name_fmt, ap);
1269                 tech = ast_strdupa(tmp->name);
1270                 if ((slash = strchr(tech, '/'))) {
1271                         if ((slash2 = strchr(slash + 1, '/'))) {
1272                                 tech2 = slash + 1;
1273                                 *slash2 = '\0';
1274                         }
1275                         *slash = '\0';
1276                 }
1277         } else {
1278                 /*
1279                  * Start the string with '-' so it becomes an empty string
1280                  * in the destructor.
1281                  */
1282                 ast_string_field_set(tmp, name, "-**Unknown**");
1283         }
1284
1285         /* Reminder for the future: under what conditions do we NOT want to track cdrs on channels? */
1286
1287         /* These 4 variables need to be set up for the cdr_init() to work right */
1288         if (amaflag)
1289                 tmp->amaflags = amaflag;
1290         else
1291                 tmp->amaflags = ast_default_amaflags;
1292         
1293         if (!ast_strlen_zero(acctcode))
1294                 ast_string_field_set(tmp, accountcode, acctcode);
1295         else
1296                 ast_string_field_set(tmp, accountcode, ast_default_accountcode);
1297                 
1298         if (!ast_strlen_zero(context))
1299                 ast_copy_string(tmp->context, context, sizeof(tmp->context));
1300         else
1301                 strcpy(tmp->context, "default");
1302
1303         if (!ast_strlen_zero(exten))
1304                 ast_copy_string(tmp->exten, exten, sizeof(tmp->exten));
1305         else
1306                 strcpy(tmp->exten, "s");
1307
1308         tmp->priority = 1;
1309
1310         tmp->cdr = ast_cdr_alloc();
1311         ast_cdr_init(tmp->cdr, tmp);
1312         ast_cdr_start(tmp->cdr);
1313
1314         ast_cel_report_event(tmp, AST_CEL_CHANNEL_START, NULL, NULL, NULL);
1315
1316         headp = &tmp->varshead;
1317         AST_LIST_HEAD_INIT_NOLOCK(headp);
1318         
1319         AST_LIST_HEAD_INIT_NOLOCK(&tmp->datastores);
1320
1321         AST_LIST_HEAD_INIT_NOLOCK(&tmp->autochans);
1322         
1323         ast_string_field_set(tmp, language, defaultlanguage);
1324
1325         tmp->tech = &null_tech;
1326
1327         ao2_link(channels, tmp);
1328
1329         /*
1330          * And now, since the channel structure is built, and has its name, let's
1331          * call the manager event generator with this Newchannel event. This is the
1332          * proper and correct place to make this call, but you sure do have to pass
1333          * a lot of data into this func to do it here!
1334          */
1335         if (ast_get_channel_tech(tech) || (tech2 && ast_get_channel_tech(tech2))) {
1336                 ast_manager_event(tmp, EVENT_FLAG_CALL, "Newchannel",
1337                         "Channel: %s\r\n"
1338                         "ChannelState: %d\r\n"
1339                         "ChannelStateDesc: %s\r\n"
1340                         "CallerIDNum: %s\r\n"
1341                         "CallerIDName: %s\r\n"
1342                         "AccountCode: %s\r\n"
1343                         "Exten: %s\r\n"
1344                         "Context: %s\r\n"
1345                         "Uniqueid: %s\r\n",
1346                         tmp->name, 
1347                         state, 
1348                         ast_state2str(state),
1349                         S_OR(cid_num, ""),
1350                         S_OR(cid_name, ""),
1351                         tmp->accountcode,
1352                         S_OR(exten, ""),
1353                         S_OR(context, ""),
1354                         tmp->uniqueid);
1355         }
1356
1357         return tmp;
1358 }
1359
1360 struct ast_channel *__ast_channel_alloc(int needqueue, int state, const char *cid_num,
1361                                         const char *cid_name, const char *acctcode,
1362                                         const char *exten, const char *context,
1363                                         const char *linkedid, const int amaflag,
1364                                         const char *file, int line, const char *function,
1365                                         const char *name_fmt, ...)
1366 {
1367         va_list ap;
1368         struct ast_channel *result;
1369
1370         va_start(ap, name_fmt);
1371         result = __ast_channel_alloc_ap(needqueue, state, cid_num, cid_name, acctcode, exten, context,
1372                                         linkedid, amaflag, file, line, function, name_fmt, ap);
1373         va_end(ap);
1374
1375         return result;
1376 }
1377
1378 /* only do the minimum amount of work needed here to make a channel
1379  * structure that can be used to expand channel vars */
1380 #if defined(REF_DEBUG) || defined(__AST_DEBUG_MALLOC)
1381 struct ast_channel *__ast_dummy_channel_alloc(const char *file, int line, const char *function)
1382 #else
1383 struct ast_channel *ast_dummy_channel_alloc(void)
1384 #endif
1385 {
1386         struct ast_channel *tmp;
1387         struct varshead *headp;
1388
1389 #if defined(REF_DEBUG)
1390         tmp = __ao2_alloc_debug(sizeof(*tmp), ast_dummy_channel_destructor, "dummy channel",
1391                 file, line, function, 1);
1392 #elif defined(__AST_DEBUG_MALLOC)
1393         tmp = __ao2_alloc_debug(sizeof(*tmp), ast_dummy_channel_destructor, "dummy channel",
1394                 file, line, function, 0);
1395 #else
1396         tmp = ao2_alloc(sizeof(*tmp), ast_dummy_channel_destructor);
1397 #endif
1398         if (!tmp) {
1399                 /* Dummy channel structure allocation failure. */
1400                 return NULL;
1401         }
1402
1403         if ((ast_string_field_init(tmp, 128))) {
1404                 return ast_channel_unref(tmp);
1405         }
1406
1407         headp = &tmp->varshead;
1408         AST_LIST_HEAD_INIT_NOLOCK(headp);
1409
1410         return tmp;
1411 }
1412
1413 static int __ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin, int head, struct ast_frame *after)
1414 {
1415         struct ast_frame *f;
1416         struct ast_frame *cur;
1417         int blah = 1;
1418         unsigned int new_frames = 0;
1419         unsigned int new_voice_frames = 0;
1420         unsigned int queued_frames = 0;
1421         unsigned int queued_voice_frames = 0;
1422         AST_LIST_HEAD_NOLOCK(, ast_frame) frames;
1423
1424         ast_channel_lock(chan);
1425
1426         /*
1427          * Check the last frame on the queue if we are queuing the new
1428          * frames after it.
1429          */
1430         cur = AST_LIST_LAST(&chan->readq);
1431         if (cur && cur->frametype == AST_FRAME_CONTROL && !head && (!after || after == cur)) {
1432                 switch (cur->subclass.integer) {
1433                 case AST_CONTROL_END_OF_Q:
1434                         if (fin->frametype == AST_FRAME_CONTROL
1435                                 && fin->subclass.integer == AST_CONTROL_HANGUP) {
1436                                 /*
1437                                  * Destroy the end-of-Q marker frame so we can queue the hangup
1438                                  * frame in its place.
1439                                  */
1440                                 AST_LIST_REMOVE(&chan->readq, cur, frame_list);
1441                                 ast_frfree(cur);
1442
1443                                 /*
1444                                  * This has degenerated to a normal queue append anyway.  Since
1445                                  * we just destroyed the last frame in the queue we must make
1446                                  * sure that "after" is NULL or bad things will happen.
1447                                  */
1448                                 after = NULL;
1449                                 break;
1450                         }
1451                         /* Fall through */
1452                 case AST_CONTROL_HANGUP:
1453                         /* Don't queue anything. */
1454                         ast_channel_unlock(chan);
1455                         return 0;
1456                 default:
1457                         break;
1458                 }
1459         }
1460
1461         /* Build copies of all the new frames and count them */
1462         AST_LIST_HEAD_INIT_NOLOCK(&frames);
1463         for (cur = fin; cur; cur = AST_LIST_NEXT(cur, frame_list)) {
1464                 if (!(f = ast_frdup(cur))) {
1465                         if (AST_LIST_FIRST(&frames)) {
1466                                 ast_frfree(AST_LIST_FIRST(&frames));
1467                         }
1468                         ast_channel_unlock(chan);
1469                         return -1;
1470                 }
1471
1472                 AST_LIST_INSERT_TAIL(&frames, f, frame_list);
1473                 new_frames++;
1474                 if (f->frametype == AST_FRAME_VOICE) {
1475                         new_voice_frames++;
1476                 }
1477         }
1478
1479         /* Count how many frames exist on the queue */
1480         AST_LIST_TRAVERSE(&chan->readq, cur, frame_list) {
1481                 queued_frames++;
1482                 if (cur->frametype == AST_FRAME_VOICE) {
1483                         queued_voice_frames++;
1484                 }
1485         }
1486
1487         if ((queued_frames + new_frames > 128 || queued_voice_frames + new_voice_frames > 96)) {
1488                 int count = 0;
1489                 ast_log(LOG_WARNING, "Exceptionally long %squeue length queuing to %s\n", queued_frames + new_frames > 128 ? "" : "voice ", chan->name);
1490                 AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->readq, cur, frame_list) {
1491                         /* Save the most recent frame */
1492                         if (!AST_LIST_NEXT(cur, frame_list)) {
1493                                 break;
1494                         } else if (cur->frametype == AST_FRAME_VOICE || cur->frametype == AST_FRAME_VIDEO || cur->frametype == AST_FRAME_NULL) {
1495                                 if (++count > 64) {
1496                                         break;
1497                                 }
1498                                 AST_LIST_REMOVE_CURRENT(frame_list);
1499                                 ast_frfree(cur);
1500                         }
1501                 }
1502                 AST_LIST_TRAVERSE_SAFE_END;
1503         }
1504
1505         if (after) {
1506                 AST_LIST_INSERT_LIST_AFTER(&chan->readq, &frames, after, frame_list);
1507         } else {
1508                 if (head) {
1509                         AST_LIST_APPEND_LIST(&frames, &chan->readq, frame_list);
1510                         AST_LIST_HEAD_INIT_NOLOCK(&chan->readq);
1511                 }
1512                 AST_LIST_APPEND_LIST(&chan->readq, &frames, frame_list);
1513         }
1514
1515         if (chan->alertpipe[1] > -1) {
1516                 if (write(chan->alertpipe[1], &blah, new_frames * sizeof(blah)) != (new_frames * sizeof(blah))) {
1517                         ast_log(LOG_WARNING, "Unable to write to alert pipe on %s (qlen = %d): %s!\n",
1518                                 chan->name, queued_frames, strerror(errno));
1519                 }
1520         } else if (chan->timingfd > -1) {
1521                 ast_timer_enable_continuous(chan->timer);
1522         } else if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
1523                 pthread_kill(chan->blocker, SIGURG);
1524         }
1525
1526         ast_channel_unlock(chan);
1527
1528         return 0;
1529 }
1530
1531 int ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin)
1532 {
1533         return __ast_queue_frame(chan, fin, 0, NULL);
1534 }
1535
1536 int ast_queue_frame_head(struct ast_channel *chan, struct ast_frame *fin)
1537 {
1538         return __ast_queue_frame(chan, fin, 1, NULL);
1539 }
1540
1541 /*! \brief Queue a hangup frame for channel */
1542 int ast_queue_hangup(struct ast_channel *chan)
1543 {
1544         struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = AST_CONTROL_HANGUP };
1545         /* Yeah, let's not change a lock-critical value without locking */
1546         if (!ast_channel_trylock(chan)) {
1547                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1548                 manager_event(EVENT_FLAG_CALL, "HangupRequest",
1549                         "Channel: %s\r\n"
1550                         "Uniqueid: %s\r\n",
1551                         chan->name,
1552                         chan->uniqueid);
1553                 ast_channel_unlock(chan);
1554         }
1555         return ast_queue_frame(chan, &f);
1556 }
1557
1558 /*! \brief Queue a hangup frame for channel */
1559 int ast_queue_hangup_with_cause(struct ast_channel *chan, int cause)
1560 {
1561         struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = AST_CONTROL_HANGUP };
1562
1563         if (cause >= 0)
1564                 f.data.uint32 = cause;
1565
1566         /* Yeah, let's not change a lock-critical value without locking */
1567         if (!ast_channel_trylock(chan)) {
1568                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1569                 if (cause < 0)
1570                         f.data.uint32 = chan->hangupcause;
1571
1572                 manager_event(EVENT_FLAG_CALL, "HangupRequest",
1573                         "Channel: %s\r\n"
1574                         "Uniqueid: %s\r\n"
1575                         "Cause: %d\r\n",
1576                         chan->name,
1577                         chan->uniqueid,
1578                         cause);
1579                 ast_channel_unlock(chan);
1580         }
1581
1582         return ast_queue_frame(chan, &f);
1583 }
1584
1585 /*! \brief Queue a control frame */
1586 int ast_queue_control(struct ast_channel *chan, enum ast_control_frame_type control)
1587 {
1588         struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = control };
1589         return ast_queue_frame(chan, &f);
1590 }
1591
1592 /*! \brief Queue a control frame with payload */
1593 int ast_queue_control_data(struct ast_channel *chan, enum ast_control_frame_type control,
1594                            const void *data, size_t datalen)
1595 {
1596         struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = control, .data.ptr = (void *) data, .datalen = datalen };
1597         return ast_queue_frame(chan, &f);
1598 }
1599
1600 /*! \brief Set defer DTMF flag on channel */
1601 int ast_channel_defer_dtmf(struct ast_channel *chan)
1602 {
1603         int pre = 0;
1604
1605         if (chan) {
1606                 pre = ast_test_flag(chan, AST_FLAG_DEFER_DTMF);
1607                 ast_set_flag(chan, AST_FLAG_DEFER_DTMF);
1608         }
1609         return pre;
1610 }
1611
1612 /*! \brief Unset defer DTMF flag on channel */
1613 void ast_channel_undefer_dtmf(struct ast_channel *chan)
1614 {
1615         if (chan)
1616                 ast_clear_flag(chan, AST_FLAG_DEFER_DTMF);
1617 }
1618
1619 struct ast_channel *ast_channel_callback(ao2_callback_data_fn *cb_fn, void *arg,
1620                 void *data, int ao2_flags)
1621 {
1622         return ao2_callback_data(channels, ao2_flags, cb_fn, arg, data);
1623 }
1624
1625 struct ast_channel_iterator {
1626         /* storage for non-dynamically allocated iterator */
1627         struct ao2_iterator simple_iterator;
1628         /* pointer to the actual iterator (simple_iterator or a dynamically
1629          * allocated iterator)
1630          */
1631         struct ao2_iterator *active_iterator;
1632 };
1633
1634 struct ast_channel_iterator *ast_channel_iterator_destroy(struct ast_channel_iterator *i)
1635 {
1636         ao2_iterator_destroy(i->active_iterator);
1637         ast_free(i);
1638
1639         return NULL;
1640 }
1641
1642 static struct ast_channel_iterator *channel_iterator_search(const char *name,
1643                                                             size_t name_len, const char *exten,
1644                                                             const char *context)
1645 {
1646         struct ast_channel_iterator *i;
1647         struct ast_channel tmp_chan = {
1648                 .name = name,
1649                 /* This is sort of a hack.  Basically, we're using an arbitrary field
1650                  * in ast_channel to pass the name_len for a prefix match.  If this
1651                  * gets changed, then the compare callback must be changed, too. */
1652                 .rings = name_len,
1653         };
1654
1655         if (!(i = ast_calloc(1, sizeof(*i)))) {
1656                 return NULL;
1657         }
1658
1659         if (exten) {
1660                 ast_copy_string(tmp_chan.exten, exten, sizeof(tmp_chan.exten));
1661         }
1662
1663         if (context) {
1664                 ast_copy_string(tmp_chan.context, context, sizeof(tmp_chan.context));
1665         }
1666
1667         if (!(i->active_iterator = ao2_find(channels, &tmp_chan,
1668                                             OBJ_MULTIPLE | ((!ast_strlen_zero(name) && (name_len == 0)) ? OBJ_POINTER : 0)))) {
1669                     ast_free(i);
1670                     return NULL;
1671         }
1672
1673         return i;
1674 }
1675
1676 struct ast_channel_iterator *ast_channel_iterator_by_exten_new(const char *exten, const char *context)
1677 {
1678         return channel_iterator_search(NULL, 0, exten, context);
1679 }
1680
1681 struct ast_channel_iterator *ast_channel_iterator_by_name_new(const char *name, size_t name_len)
1682 {
1683         return channel_iterator_search(name, name_len, NULL, NULL);
1684 }
1685
1686 struct ast_channel_iterator *ast_channel_iterator_all_new(void)
1687 {
1688         struct ast_channel_iterator *i;
1689
1690         if (!(i = ast_calloc(1, sizeof(*i)))) {
1691                 return NULL;
1692         }
1693
1694         i->simple_iterator = ao2_iterator_init(channels, 0);
1695         i->active_iterator = &i->simple_iterator;
1696
1697         return i;
1698 }
1699
1700 struct ast_channel *ast_channel_iterator_next(struct ast_channel_iterator *i)
1701 {
1702         return ao2_iterator_next(i->active_iterator);
1703 }
1704
1705 static int ast_channel_cmp_cb(void *obj, void *arg, int flags)
1706 {
1707         struct ast_channel *chan = obj, *cmp_args = arg;
1708         size_t name_len;
1709         int ret = CMP_MATCH;
1710
1711         /* This is sort of a hack.  Basically, we're using an arbitrary field
1712          * in ast_channel to pass the name_len for a prefix match.  If this
1713          * gets changed, then the uses of ao2_find() must be changed, too. */
1714         name_len = cmp_args->rings;
1715
1716         ast_channel_lock(chan);
1717
1718         if (!ast_strlen_zero(cmp_args->name)) { /* match by name */
1719                 if ((!name_len && strcasecmp(chan->name, cmp_args->name)) ||
1720                                 (name_len && strncasecmp(chan->name, cmp_args->name, name_len))) {
1721                         ret = 0; /* name match failed */
1722                 }
1723         } else if (!ast_strlen_zero(cmp_args->exten)) {
1724                 if (cmp_args->context && strcasecmp(chan->context, cmp_args->context) &&
1725                                 strcasecmp(chan->macrocontext, cmp_args->context)) {
1726                         ret = 0; /* context match failed */
1727                 }
1728                 if (ret && strcasecmp(chan->exten, cmp_args->exten) &&
1729                                 strcasecmp(chan->macroexten, cmp_args->exten)) {
1730                         ret = 0; /* exten match failed */
1731                 }
1732         } else if (!ast_strlen_zero(cmp_args->uniqueid)) {
1733                 if ((!name_len && strcasecmp(chan->uniqueid, cmp_args->uniqueid)) ||
1734                                 (name_len && strncasecmp(chan->uniqueid, cmp_args->uniqueid, name_len))) {
1735                         ret = 0; /* uniqueid match failed */
1736                 }
1737         } else {
1738                 ret = 0;
1739         }
1740
1741         ast_channel_unlock(chan);
1742
1743         return ret;
1744 }
1745
1746 static struct ast_channel *ast_channel_get_full(const char *name, size_t name_len,
1747                                                 const char *exten, const char *context)
1748 {
1749         struct ast_channel tmp_chan = {
1750                 .name = name,
1751                 /* This is sort of a hack.  Basically, we're using an arbitrary field
1752                  * in ast_channel to pass the name_len for a prefix match.  If this
1753                  * gets changed, then the compare callback must be changed, too. */
1754                 .rings = name_len,
1755         };
1756         struct ast_channel *chan;
1757
1758         if (exten) {
1759                 ast_copy_string(tmp_chan.exten, exten, sizeof(tmp_chan.exten));
1760         }
1761
1762         if (context) {
1763                 ast_copy_string(tmp_chan.context, context, sizeof(tmp_chan.context));
1764         }
1765
1766         if ((chan = ao2_find(channels, &tmp_chan,
1767                              (!ast_strlen_zero(name) && (name_len == 0)) ? OBJ_POINTER : 0))) {
1768                 return chan;
1769         }
1770
1771         if (!name) {
1772                 return NULL;
1773         }
1774
1775         /* If name was specified, but the result was NULL, 
1776          * try a search on uniqueid, instead. */
1777
1778         {
1779                 struct ast_channel tmp_chan2 = {
1780                         .uniqueid = name,
1781                         .rings = name_len,
1782                 };
1783
1784                 return ao2_find(channels, &tmp_chan2, 0);
1785         }
1786 }
1787
1788 struct ast_channel *ast_channel_get_by_name(const char *name)
1789 {
1790         return ast_channel_get_full(name, 0, NULL, NULL);
1791 }
1792
1793 struct ast_channel *ast_channel_get_by_name_prefix(const char *name, size_t name_len)
1794 {
1795         return ast_channel_get_full(name, name_len, NULL, NULL);
1796 }
1797
1798 struct ast_channel *ast_channel_get_by_exten(const char *exten, const char *context)
1799 {
1800         return ast_channel_get_full(NULL, 0, exten, context);
1801 }
1802
1803 int ast_is_deferrable_frame(const struct ast_frame *frame)
1804 {
1805         /* Do not add a default entry in this switch statement.  Each new
1806          * frame type should be addressed directly as to whether it should
1807          * be queued up or not.
1808          */
1809         switch (frame->frametype) {
1810         case AST_FRAME_CONTROL:
1811         case AST_FRAME_TEXT:
1812         case AST_FRAME_IMAGE:
1813         case AST_FRAME_HTML:
1814                 return 1;
1815
1816         case AST_FRAME_DTMF_END:
1817         case AST_FRAME_DTMF_BEGIN:
1818         case AST_FRAME_VOICE:
1819         case AST_FRAME_VIDEO:
1820         case AST_FRAME_NULL:
1821         case AST_FRAME_IAX:
1822         case AST_FRAME_CNG:
1823         case AST_FRAME_MODEM:
1824                 return 0;
1825         }
1826         return 0;
1827 }
1828
1829 /*! \brief Wait, look for hangups and condition arg */
1830 int ast_safe_sleep_conditional(struct ast_channel *chan, int ms, int (*cond)(void*), void *data)
1831 {
1832         struct ast_frame *f;
1833         struct ast_silence_generator *silgen = NULL;
1834         int res = 0;
1835         AST_LIST_HEAD_NOLOCK(, ast_frame) deferred_frames;
1836
1837         AST_LIST_HEAD_INIT_NOLOCK(&deferred_frames);
1838
1839         /* If no other generator is present, start silencegen while waiting */
1840         if (ast_opt_transmit_silence && !chan->generatordata) {
1841                 silgen = ast_channel_start_silence_generator(chan);
1842         }
1843
1844         while (ms > 0) {
1845                 struct ast_frame *dup_f = NULL;
1846                 if (cond && ((*cond)(data) == 0)) {
1847                         break;
1848                 }
1849                 ms = ast_waitfor(chan, ms);
1850                 if (ms < 0) {
1851                         res = -1;
1852                         break;
1853                 }
1854                 if (ms > 0) {
1855                         f = ast_read(chan);
1856                         if (!f) {
1857                                 res = -1;
1858                                 break;
1859                         }
1860
1861                         if (!ast_is_deferrable_frame(f)) {
1862                                 ast_frfree(f);
1863                                 continue;
1864                         }
1865                         
1866                         if ((dup_f = ast_frisolate(f))) {
1867                                 if (dup_f != f) {
1868                                         ast_frfree(f);
1869                                 }
1870                                 AST_LIST_INSERT_HEAD(&deferred_frames, dup_f, frame_list);
1871                         }
1872                 }
1873         }
1874
1875         /* stop silgen if present */
1876         if (silgen) {
1877                 ast_channel_stop_silence_generator(chan, silgen);
1878         }
1879
1880         /* We need to free all the deferred frames, but we only need to
1881          * queue the deferred frames if there was no error and no
1882          * hangup was received
1883          */
1884         ast_channel_lock(chan);
1885         while ((f = AST_LIST_REMOVE_HEAD(&deferred_frames, frame_list))) {
1886                 if (!res) {
1887                         ast_queue_frame_head(chan, f);
1888                 }
1889                 ast_frfree(f);
1890         }
1891         ast_channel_unlock(chan);
1892
1893         return res;
1894 }
1895
1896 /*! \brief Wait, look for hangups */
1897 int ast_safe_sleep(struct ast_channel *chan, int ms)
1898 {
1899         return ast_safe_sleep_conditional(chan, ms, NULL, NULL);
1900 }
1901
1902 struct ast_channel *ast_channel_release(struct ast_channel *chan)
1903 {
1904         /* Safe, even if already unlinked. */
1905         ao2_unlink(channels, chan);
1906         return ast_channel_unref(chan);
1907 }
1908
1909 void ast_party_name_init(struct ast_party_name *init)
1910 {
1911         init->str = NULL;
1912         init->char_set = AST_PARTY_CHAR_SET_ISO8859_1;
1913         init->presentation = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
1914         init->valid = 0;
1915 }
1916
1917 void ast_party_name_copy(struct ast_party_name *dest, const struct ast_party_name *src)
1918 {
1919         if (dest == src) {
1920                 /* Don't copy to self */
1921                 return;
1922         }
1923
1924         ast_free(dest->str);
1925         dest->str = ast_strdup(src->str);
1926         dest->char_set = src->char_set;
1927         dest->presentation = src->presentation;
1928         dest->valid = src->valid;
1929 }
1930
1931 void ast_party_name_set_init(struct ast_party_name *init, const struct ast_party_name *guide)
1932 {
1933         init->str = NULL;
1934         init->char_set = guide->char_set;
1935         init->presentation = guide->presentation;
1936         init->valid = guide->valid;
1937 }
1938
1939 void ast_party_name_set(struct ast_party_name *dest, const struct ast_party_name *src)
1940 {
1941         if (dest == src) {
1942                 /* Don't set to self */
1943                 return;
1944         }
1945
1946         if (src->str && src->str != dest->str) {
1947                 ast_free(dest->str);
1948                 dest->str = ast_strdup(src->str);
1949         }
1950
1951         dest->char_set = src->char_set;
1952         dest->presentation = src->presentation;
1953         dest->valid = src->valid;
1954 }
1955
1956 void ast_party_name_free(struct ast_party_name *doomed)
1957 {
1958         ast_free(doomed->str);
1959         doomed->str = NULL;
1960 }
1961
1962 void ast_party_number_init(struct ast_party_number *init)
1963 {
1964         init->str = NULL;
1965         init->plan = 0;/* Unknown */
1966         init->presentation = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
1967         init->valid = 0;
1968 }
1969
1970 void ast_party_number_copy(struct ast_party_number *dest, const struct ast_party_number *src)
1971 {
1972         if (dest == src) {
1973                 /* Don't copy to self */
1974                 return;
1975         }
1976
1977         ast_free(dest->str);
1978         dest->str = ast_strdup(src->str);
1979         dest->plan = src->plan;
1980         dest->presentation = src->presentation;
1981         dest->valid = src->valid;
1982 }
1983
1984 void ast_party_number_set_init(struct ast_party_number *init, const struct ast_party_number *guide)
1985 {
1986         init->str = NULL;
1987         init->plan = guide->plan;
1988         init->presentation = guide->presentation;
1989         init->valid = guide->valid;
1990 }
1991
1992 void ast_party_number_set(struct ast_party_number *dest, const struct ast_party_number *src)
1993 {
1994         if (dest == src) {
1995                 /* Don't set to self */
1996                 return;
1997         }
1998
1999         if (src->str && src->str != dest->str) {
2000                 ast_free(dest->str);
2001                 dest->str = ast_strdup(src->str);
2002         }
2003
2004         dest->plan = src->plan;
2005         dest->presentation = src->presentation;
2006         dest->valid = src->valid;
2007 }
2008
2009 void ast_party_number_free(struct ast_party_number *doomed)
2010 {
2011         ast_free(doomed->str);
2012         doomed->str = NULL;
2013 }
2014
2015 void ast_party_subaddress_init(struct ast_party_subaddress *init)
2016 {
2017         init->str = NULL;
2018         init->type = 0;
2019         init->odd_even_indicator = 0;
2020         init->valid = 0;
2021 }
2022
2023 void ast_party_subaddress_copy(struct ast_party_subaddress *dest, const struct ast_party_subaddress *src)
2024 {
2025         if (dest == src) {
2026                 /* Don't copy to self */
2027                 return;
2028         }
2029
2030         ast_free(dest->str);
2031         dest->str = ast_strdup(src->str);
2032         dest->type = src->type;
2033         dest->odd_even_indicator = src->odd_even_indicator;
2034         dest->valid = src->valid;
2035 }
2036
2037 void ast_party_subaddress_set_init(struct ast_party_subaddress *init, const struct ast_party_subaddress *guide)
2038 {
2039         init->str = NULL;
2040         init->type = guide->type;
2041         init->odd_even_indicator = guide->odd_even_indicator;
2042         init->valid = guide->valid;
2043 }
2044
2045 void ast_party_subaddress_set(struct ast_party_subaddress *dest, const struct ast_party_subaddress *src)
2046 {
2047         if (dest == src) {
2048                 /* Don't set to self */
2049                 return;
2050         }
2051
2052         if (src->str && src->str != dest->str) {
2053                 ast_free(dest->str);
2054                 dest->str = ast_strdup(src->str);
2055         }
2056
2057         dest->type = src->type;
2058         dest->odd_even_indicator = src->odd_even_indicator;
2059         dest->valid = src->valid;
2060 }
2061
2062 void ast_party_subaddress_free(struct ast_party_subaddress *doomed)
2063 {
2064         ast_free(doomed->str);
2065         doomed->str = NULL;
2066 }
2067
2068 void ast_party_id_init(struct ast_party_id *init)
2069 {
2070         ast_party_name_init(&init->name);
2071         ast_party_number_init(&init->number);
2072         ast_party_subaddress_init(&init->subaddress);
2073         init->tag = NULL;
2074 }
2075
2076 void ast_party_id_copy(struct ast_party_id *dest, const struct ast_party_id *src)
2077 {
2078         if (dest == src) {
2079                 /* Don't copy to self */
2080                 return;
2081         }
2082
2083         ast_party_name_copy(&dest->name, &src->name);
2084         ast_party_number_copy(&dest->number, &src->number);
2085         ast_party_subaddress_copy(&dest->subaddress, &src->subaddress);
2086
2087         ast_free(dest->tag);
2088         dest->tag = ast_strdup(src->tag);
2089 }
2090
2091 void ast_party_id_set_init(struct ast_party_id *init, const struct ast_party_id *guide)
2092 {
2093         ast_party_name_set_init(&init->name, &guide->name);
2094         ast_party_number_set_init(&init->number, &guide->number);
2095         ast_party_subaddress_set_init(&init->subaddress, &guide->subaddress);
2096         init->tag = NULL;
2097 }
2098
2099 void ast_party_id_set(struct ast_party_id *dest, const struct ast_party_id *src, const struct ast_set_party_id *update)
2100 {
2101         if (dest == src) {
2102                 /* Don't set to self */
2103                 return;
2104         }
2105
2106         if (!update || update->name) {
2107                 ast_party_name_set(&dest->name, &src->name);
2108         }
2109         if (!update || update->number) {
2110                 ast_party_number_set(&dest->number, &src->number);
2111         }
2112         if (!update || update->subaddress) {
2113                 ast_party_subaddress_set(&dest->subaddress, &src->subaddress);
2114         }
2115
2116         if (src->tag && src->tag != dest->tag) {
2117                 ast_free(dest->tag);
2118                 dest->tag = ast_strdup(src->tag);
2119         }
2120 }
2121
2122 void ast_party_id_free(struct ast_party_id *doomed)
2123 {
2124         ast_party_name_free(&doomed->name);
2125         ast_party_number_free(&doomed->number);
2126         ast_party_subaddress_free(&doomed->subaddress);
2127
2128         ast_free(doomed->tag);
2129         doomed->tag = NULL;
2130 }
2131
2132 int ast_party_id_presentation(const struct ast_party_id *id)
2133 {
2134         int number_priority;
2135         int number_value;
2136         int number_screening;
2137         int name_priority;
2138         int name_value;
2139
2140         /* Determine name presentation priority. */
2141         if (!id->name.valid) {
2142                 name_value = AST_PRES_UNAVAILABLE;
2143                 name_priority = 3;
2144         } else {
2145                 name_value = id->name.presentation & AST_PRES_RESTRICTION;
2146                 switch (name_value) {
2147                 case AST_PRES_RESTRICTED:
2148                         name_priority = 0;
2149                         break;
2150                 case AST_PRES_ALLOWED:
2151                         name_priority = 1;
2152                         break;
2153                 case AST_PRES_UNAVAILABLE:
2154                         name_priority = 2;
2155                         break;
2156                 default:
2157                         name_value = AST_PRES_UNAVAILABLE;
2158                         name_priority = 3;
2159                         break;
2160                 }
2161         }
2162
2163         /* Determine number presentation priority. */
2164         if (!id->number.valid) {
2165                 number_screening = AST_PRES_USER_NUMBER_UNSCREENED;
2166                 number_value = AST_PRES_UNAVAILABLE;
2167                 number_priority = 3;
2168         } else {
2169                 number_screening = id->number.presentation & AST_PRES_NUMBER_TYPE;
2170                 number_value = id->number.presentation & AST_PRES_RESTRICTION;
2171                 switch (number_value) {
2172                 case AST_PRES_RESTRICTED:
2173                         number_priority = 0;
2174                         break;
2175                 case AST_PRES_ALLOWED:
2176                         number_priority = 1;
2177                         break;
2178                 case AST_PRES_UNAVAILABLE:
2179                         number_priority = 2;
2180                         break;
2181                 default:
2182                         number_screening = AST_PRES_USER_NUMBER_UNSCREENED;
2183                         number_value = AST_PRES_UNAVAILABLE;
2184                         number_priority = 3;
2185                         break;
2186                 }
2187         }
2188
2189         /* Select the wining presentation value. */
2190         if (name_priority < number_priority) {
2191                 number_value = name_value;
2192         }
2193
2194         return number_value | number_screening;
2195 }
2196
2197 void ast_party_dialed_init(struct ast_party_dialed *init)
2198 {
2199         init->number.str = NULL;
2200         init->number.plan = 0;/* Unknown */
2201         ast_party_subaddress_init(&init->subaddress);
2202         init->transit_network_select = 0;
2203 }
2204
2205 void ast_party_dialed_copy(struct ast_party_dialed *dest, const struct ast_party_dialed *src)
2206 {
2207         if (dest == src) {
2208                 /* Don't copy to self */
2209                 return;
2210         }
2211
2212         ast_free(dest->number.str);
2213         dest->number.str = ast_strdup(src->number.str);
2214         dest->number.plan = src->number.plan;
2215         ast_party_subaddress_copy(&dest->subaddress, &src->subaddress);
2216         dest->transit_network_select = src->transit_network_select;
2217 }
2218
2219 void ast_party_dialed_set_init(struct ast_party_dialed *init, const struct ast_party_dialed *guide)
2220 {
2221         init->number.str = NULL;
2222         init->number.plan = guide->number.plan;
2223         ast_party_subaddress_set_init(&init->subaddress, &guide->subaddress);
2224         init->transit_network_select = guide->transit_network_select;
2225 }
2226
2227 void ast_party_dialed_set(struct ast_party_dialed *dest, const struct ast_party_dialed *src)
2228 {
2229         if (src->number.str && src->number.str != dest->number.str) {
2230                 ast_free(dest->number.str);
2231                 dest->number.str = ast_strdup(src->number.str);
2232         }
2233         dest->number.plan = src->number.plan;
2234
2235         ast_party_subaddress_set(&dest->subaddress, &src->subaddress);
2236
2237         dest->transit_network_select = src->transit_network_select;
2238 }
2239
2240 void ast_party_dialed_free(struct ast_party_dialed *doomed)
2241 {
2242         ast_free(doomed->number.str);
2243         doomed->number.str = NULL;
2244         ast_party_subaddress_free(&doomed->subaddress);
2245 }
2246
2247 void ast_party_caller_init(struct ast_party_caller *init)
2248 {
2249         ast_party_id_init(&init->id);
2250         ast_party_id_init(&init->ani);
2251         init->ani2 = 0;
2252 }
2253
2254 void ast_party_caller_copy(struct ast_party_caller *dest, const struct ast_party_caller *src)
2255 {
2256         if (dest == src) {
2257                 /* Don't copy to self */
2258                 return;
2259         }
2260
2261         ast_party_id_copy(&dest->id, &src->id);
2262         ast_party_id_copy(&dest->ani, &src->ani);
2263         dest->ani2 = src->ani2;
2264 }
2265
2266 void ast_party_caller_set_init(struct ast_party_caller *init, const struct ast_party_caller *guide)
2267 {
2268         ast_party_id_set_init(&init->id, &guide->id);
2269         ast_party_id_set_init(&init->ani, &guide->ani);
2270         init->ani2 = guide->ani2;
2271 }
2272
2273 void ast_party_caller_set(struct ast_party_caller *dest, const struct ast_party_caller *src, const struct ast_set_party_caller *update)
2274 {
2275         ast_party_id_set(&dest->id, &src->id, update ? &update->id : NULL);
2276         ast_party_id_set(&dest->ani, &src->ani, update ? &update->ani : NULL);
2277         dest->ani2 = src->ani2;
2278 }
2279
2280 void ast_party_caller_free(struct ast_party_caller *doomed)
2281 {
2282         ast_party_id_free(&doomed->id);
2283         ast_party_id_free(&doomed->ani);
2284 }
2285
2286 void ast_party_connected_line_init(struct ast_party_connected_line *init)
2287 {
2288         ast_party_id_init(&init->id);
2289         ast_party_id_init(&init->ani);
2290         init->ani2 = 0;
2291         init->source = AST_CONNECTED_LINE_UPDATE_SOURCE_UNKNOWN;
2292 }
2293
2294 void ast_party_connected_line_copy(struct ast_party_connected_line *dest, const struct ast_party_connected_line *src)
2295 {
2296         if (dest == src) {
2297                 /* Don't copy to self */
2298                 return;
2299         }
2300
2301         ast_party_id_copy(&dest->id, &src->id);
2302         ast_party_id_copy(&dest->ani, &src->ani);
2303         dest->ani2 = src->ani2;
2304         dest->source = src->source;
2305 }
2306
2307 void ast_party_connected_line_set_init(struct ast_party_connected_line *init, const struct ast_party_connected_line *guide)
2308 {
2309         ast_party_id_set_init(&init->id, &guide->id);
2310         ast_party_id_set_init(&init->ani, &guide->ani);
2311         init->ani2 = guide->ani2;
2312         init->source = guide->source;
2313 }
2314
2315 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)
2316 {
2317         ast_party_id_set(&dest->id, &src->id, update ? &update->id : NULL);
2318         ast_party_id_set(&dest->ani, &src->ani, update ? &update->ani : NULL);
2319         dest->ani2 = src->ani2;
2320         dest->source = src->source;
2321 }
2322
2323 void ast_party_connected_line_collect_caller(struct ast_party_connected_line *connected, struct ast_party_caller *caller)
2324 {
2325         connected->id = caller->id;
2326         connected->ani = caller->ani;
2327         connected->ani2 = caller->ani2;
2328         connected->source = AST_CONNECTED_LINE_UPDATE_SOURCE_UNKNOWN;
2329 }
2330
2331 void ast_party_connected_line_free(struct ast_party_connected_line *doomed)
2332 {
2333         ast_party_id_free(&doomed->id);
2334         ast_party_id_free(&doomed->ani);
2335 }
2336
2337 void ast_party_redirecting_init(struct ast_party_redirecting *init)
2338 {
2339         ast_party_id_init(&init->from);
2340         ast_party_id_init(&init->to);
2341         init->count = 0;
2342         init->reason = AST_REDIRECTING_REASON_UNKNOWN;
2343 }
2344
2345 void ast_party_redirecting_copy(struct ast_party_redirecting *dest, const struct ast_party_redirecting *src)
2346 {
2347         if (dest == src) {
2348                 /* Don't copy to self */
2349                 return;
2350         }
2351
2352         ast_party_id_copy(&dest->from, &src->from);
2353         ast_party_id_copy(&dest->to, &src->to);
2354         dest->count = src->count;
2355         dest->reason = src->reason;
2356 }
2357
2358 void ast_party_redirecting_set_init(struct ast_party_redirecting *init, const struct ast_party_redirecting *guide)
2359 {
2360         ast_party_id_set_init(&init->from, &guide->from);
2361         ast_party_id_set_init(&init->to, &guide->to);
2362         init->count = guide->count;
2363         init->reason = guide->reason;
2364 }
2365
2366 void ast_party_redirecting_set(struct ast_party_redirecting *dest, const struct ast_party_redirecting *src, const struct ast_set_party_redirecting *update)
2367 {
2368         ast_party_id_set(&dest->from, &src->from, update ? &update->from : NULL);
2369         ast_party_id_set(&dest->to, &src->to, update ? &update->to : NULL);
2370         dest->reason = src->reason;
2371         dest->count = src->count;
2372 }
2373
2374 void ast_party_redirecting_free(struct ast_party_redirecting *doomed)
2375 {
2376         ast_party_id_free(&doomed->from);
2377         ast_party_id_free(&doomed->to);
2378 }
2379
2380 /*! \brief Free a channel structure */
2381 static void ast_channel_destructor(void *obj)
2382 {
2383         struct ast_channel *chan = obj;
2384         int fd;
2385 #ifdef HAVE_EPOLL
2386         int i;
2387 #endif
2388         struct ast_var_t *vardata;
2389         struct ast_frame *f;
2390         struct varshead *headp;
2391         struct ast_datastore *datastore;
2392         char device_name[AST_CHANNEL_NAME];
2393
2394         if (chan->name) {
2395                 /* The string fields were initialized. */
2396                 ast_cel_report_event(chan, AST_CEL_CHANNEL_END, NULL, NULL, NULL);
2397                 ast_cel_check_retire_linkedid(chan);
2398         }
2399
2400         /* Get rid of each of the data stores on the channel */
2401         ast_channel_lock(chan);
2402         while ((datastore = AST_LIST_REMOVE_HEAD(&chan->datastores, entry)))
2403                 /* Free the data store */
2404                 ast_datastore_free(datastore);
2405         ast_channel_unlock(chan);
2406
2407         /* Lock and unlock the channel just to be sure nobody has it locked still
2408            due to a reference that was stored in a datastore. (i.e. app_chanspy) */
2409         ast_channel_lock(chan);
2410         ast_channel_unlock(chan);
2411
2412         if (chan->tech_pvt) {
2413                 ast_log(LOG_WARNING, "Channel '%s' may not have been hung up properly\n", chan->name);
2414                 ast_free(chan->tech_pvt);
2415         }
2416
2417         if (chan->sched) {
2418                 ast_sched_context_destroy(chan->sched);
2419         }
2420
2421         if (chan->name) {
2422                 char *dashptr;
2423
2424                 /* The string fields were initialized. */
2425                 ast_copy_string(device_name, chan->name, sizeof(device_name));
2426                 if ((dashptr = strrchr(device_name, '-'))) {
2427                         *dashptr = '\0';
2428                 }
2429         } else {
2430                 device_name[0] = '\0';
2431         }
2432
2433         /* Stop monitoring */
2434         if (chan->monitor)
2435                 chan->monitor->stop( chan, 0 );
2436
2437         /* If there is native format music-on-hold state, free it */
2438         if (chan->music_state)
2439                 ast_moh_cleanup(chan);
2440
2441         /* Free translators */
2442         if (chan->readtrans)
2443                 ast_translator_free_path(chan->readtrans);
2444         if (chan->writetrans)
2445                 ast_translator_free_path(chan->writetrans);
2446         if (chan->pbx)
2447                 ast_log(LOG_WARNING, "PBX may not have been terminated properly on '%s'\n", chan->name);
2448
2449         ast_party_dialed_free(&chan->dialed);
2450         ast_party_caller_free(&chan->caller);
2451         ast_party_connected_line_free(&chan->connected);
2452         ast_party_redirecting_free(&chan->redirecting);
2453
2454         /* Close pipes if appropriate */
2455         if ((fd = chan->alertpipe[0]) > -1)
2456                 close(fd);
2457         if ((fd = chan->alertpipe[1]) > -1)
2458                 close(fd);
2459         if (chan->timer) {
2460                 ast_timer_close(chan->timer);
2461         }
2462 #ifdef HAVE_EPOLL
2463         for (i = 0; i < AST_MAX_FDS; i++) {
2464                 if (chan->epfd_data[i])
2465                         free(chan->epfd_data[i]);
2466         }
2467         close(chan->epfd);
2468 #endif
2469         while ((f = AST_LIST_REMOVE_HEAD(&chan->readq, frame_list)))
2470                 ast_frfree(f);
2471         
2472         /* loop over the variables list, freeing all data and deleting list items */
2473         /* no need to lock the list, as the channel is already locked */
2474         headp = &chan->varshead;
2475         while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
2476                 ast_var_delete(vardata);
2477
2478         ast_app_group_discard(chan);
2479
2480         /* Destroy the jitterbuffer */
2481         ast_jb_destroy(chan);
2482
2483         if (chan->cdr) {
2484                 ast_cdr_discard(chan->cdr);
2485                 chan->cdr = NULL;
2486         }
2487
2488         if (chan->zone) {
2489                 chan->zone = ast_tone_zone_unref(chan->zone);
2490         }
2491
2492         ast_string_field_free_memory(chan);
2493
2494         if (device_name[0]) {
2495                 /*
2496                  * We have a device name to notify of a new state.
2497                  *
2498                  * Queue an unknown state, because, while we know that this particular
2499                  * instance is dead, we don't know the state of all other possible
2500                  * instances.
2501                  */
2502                 ast_devstate_changed_literal(AST_DEVICE_UNKNOWN, device_name);
2503         }
2504
2505         chan->nativeformats = ast_format_cap_destroy(chan->nativeformats);
2506 }
2507
2508 /*! \brief Free a dummy channel structure */
2509 static void ast_dummy_channel_destructor(void *obj)
2510 {
2511         struct ast_channel *chan = obj;
2512         struct ast_var_t *vardata;
2513         struct varshead *headp;
2514
2515         headp = &chan->varshead;
2516
2517         ast_party_dialed_free(&chan->dialed);
2518         ast_party_caller_free(&chan->caller);
2519         ast_party_connected_line_free(&chan->connected);
2520         ast_party_redirecting_free(&chan->redirecting);
2521
2522         /* loop over the variables list, freeing all data and deleting list items */
2523         /* no need to lock the list, as the channel is already locked */
2524         while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
2525                 ast_var_delete(vardata);
2526
2527         if (chan->cdr) {
2528                 ast_cdr_discard(chan->cdr);
2529                 chan->cdr = NULL;
2530         }
2531
2532         ast_string_field_free_memory(chan);
2533 }
2534
2535 struct ast_datastore *ast_channel_datastore_alloc(const struct ast_datastore_info *info, const char *uid)
2536 {
2537         return ast_datastore_alloc(info, uid);
2538 }
2539
2540 int ast_channel_datastore_free(struct ast_datastore *datastore)
2541 {
2542         return ast_datastore_free(datastore);
2543 }
2544
2545 int ast_channel_datastore_inherit(struct ast_channel *from, struct ast_channel *to)
2546 {
2547         struct ast_datastore *datastore = NULL, *datastore2;
2548
2549         AST_LIST_TRAVERSE(&from->datastores, datastore, entry) {
2550                 if (datastore->inheritance > 0) {
2551                         datastore2 = ast_datastore_alloc(datastore->info, datastore->uid);
2552                         if (datastore2) {
2553                                 datastore2->data = datastore->info->duplicate ? datastore->info->duplicate(datastore->data) : NULL;
2554                                 datastore2->inheritance = datastore->inheritance == DATASTORE_INHERIT_FOREVER ? DATASTORE_INHERIT_FOREVER : datastore->inheritance - 1;
2555                                 AST_LIST_INSERT_TAIL(&to->datastores, datastore2, entry);
2556                         }
2557                 }
2558         }
2559         return 0;
2560 }
2561
2562 int ast_channel_datastore_add(struct ast_channel *chan, struct ast_datastore *datastore)
2563 {
2564         int res = 0;
2565
2566         AST_LIST_INSERT_HEAD(&chan->datastores, datastore, entry);
2567
2568         return res;
2569 }
2570
2571 int ast_channel_datastore_remove(struct ast_channel *chan, struct ast_datastore *datastore)
2572 {
2573         return AST_LIST_REMOVE(&chan->datastores, datastore, entry) ? 0 : -1;
2574 }
2575
2576 struct ast_datastore *ast_channel_datastore_find(struct ast_channel *chan, const struct ast_datastore_info *info, const char *uid)
2577 {
2578         struct ast_datastore *datastore = NULL;
2579         
2580         if (info == NULL)
2581                 return NULL;
2582
2583         AST_LIST_TRAVERSE(&chan->datastores, datastore, entry) {
2584                 if (datastore->info != info) {
2585                         continue;
2586                 }
2587
2588                 if (uid == NULL) {
2589                         /* matched by type only */
2590                         break;
2591                 }
2592
2593                 if ((datastore->uid != NULL) && !strcasecmp(uid, datastore->uid)) {
2594                         /* Matched by type AND uid */
2595                         break;
2596                 }
2597         }
2598
2599         return datastore;
2600 }
2601
2602 /*! Set the file descriptor on the channel */
2603 void ast_channel_set_fd(struct ast_channel *chan, int which, int fd)
2604 {
2605 #ifdef HAVE_EPOLL
2606         struct epoll_event ev;
2607         struct ast_epoll_data *aed = NULL;
2608
2609         if (chan->fds[which] > -1) {
2610                 epoll_ctl(chan->epfd, EPOLL_CTL_DEL, chan->fds[which], &ev);
2611                 aed = chan->epfd_data[which];
2612         }
2613
2614         /* If this new fd is valid, add it to the epoll */
2615         if (fd > -1) {
2616                 if (!aed && (!(aed = ast_calloc(1, sizeof(*aed)))))
2617                         return;
2618                 
2619                 chan->epfd_data[which] = aed;
2620                 aed->chan = chan;
2621                 aed->which = which;
2622                 
2623                 ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
2624                 ev.data.ptr = aed;
2625                 epoll_ctl(chan->epfd, EPOLL_CTL_ADD, fd, &ev);
2626         } else if (aed) {
2627                 /* We don't have to keep around this epoll data structure now */
2628                 free(aed);
2629                 chan->epfd_data[which] = NULL;
2630         }
2631 #endif
2632         chan->fds[which] = fd;
2633         return;
2634 }
2635
2636 /*! Add a channel to an optimized waitfor */
2637 void ast_poll_channel_add(struct ast_channel *chan0, struct ast_channel *chan1)
2638 {
2639 #ifdef HAVE_EPOLL
2640         struct epoll_event ev;
2641         int i = 0;
2642
2643         if (chan0->epfd == -1)
2644                 return;
2645
2646         /* Iterate through the file descriptors on chan1, adding them to chan0 */
2647         for (i = 0; i < AST_MAX_FDS; i++) {
2648                 if (chan1->fds[i] == -1)
2649                         continue;
2650                 ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
2651                 ev.data.ptr = chan1->epfd_data[i];
2652                 epoll_ctl(chan0->epfd, EPOLL_CTL_ADD, chan1->fds[i], &ev);
2653         }
2654
2655 #endif
2656         return;
2657 }
2658
2659 /*! Delete a channel from an optimized waitfor */
2660 void ast_poll_channel_del(struct ast_channel *chan0, struct ast_channel *chan1)
2661 {
2662 #ifdef HAVE_EPOLL
2663         struct epoll_event ev;
2664         int i = 0;
2665
2666         if (chan0->epfd == -1)
2667                 return;
2668
2669         for (i = 0; i < AST_MAX_FDS; i++) {
2670                 if (chan1->fds[i] == -1)
2671                         continue;
2672                 epoll_ctl(chan0->epfd, EPOLL_CTL_DEL, chan1->fds[i], &ev);
2673         }
2674
2675 #endif
2676         return;
2677 }
2678
2679 void ast_channel_clear_softhangup(struct ast_channel *chan, int flag)
2680 {
2681         ast_channel_lock(chan);
2682
2683         chan->_softhangup &= ~flag;
2684
2685         if (!chan->_softhangup) {
2686                 struct ast_frame *fr;
2687
2688                 /* If we have completely cleared the softhangup flag,
2689                  * then we need to fully abort the hangup process.  This requires
2690                  * pulling the END_OF_Q frame out of the channel frame queue if it
2691                  * still happens to be there. */
2692
2693                 fr = AST_LIST_LAST(&chan->readq);
2694                 if (fr && fr->frametype == AST_FRAME_CONTROL &&
2695                                 fr->subclass.integer == AST_CONTROL_END_OF_Q) {
2696                         AST_LIST_REMOVE(&chan->readq, fr, frame_list);
2697                         ast_frfree(fr);
2698                 }
2699         }
2700
2701         ast_channel_unlock(chan);
2702 }
2703
2704 /*! \brief Softly hangup a channel, don't lock */
2705 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
2706 {
2707         ast_debug(1, "Soft-Hanging up channel '%s'\n", chan->name);
2708         /* Inform channel driver that we need to be hung up, if it cares */
2709         chan->_softhangup |= cause;
2710         ast_queue_frame(chan, &ast_null_frame);
2711         /* Interrupt any poll call or such */
2712         if (ast_test_flag(chan, AST_FLAG_BLOCKING))
2713                 pthread_kill(chan->blocker, SIGURG);
2714         return 0;
2715 }
2716
2717 /*! \brief Softly hangup a channel, lock */
2718 int ast_softhangup(struct ast_channel *chan, int cause)
2719 {
2720         int res;
2721
2722         ast_channel_lock(chan);
2723         res = ast_softhangup_nolock(chan, cause);
2724         manager_event(EVENT_FLAG_CALL, "SoftHangupRequest",
2725                 "Channel: %s\r\n"
2726                 "Uniqueid: %s\r\n"
2727                 "Cause: %d\r\n",
2728                 chan->name,
2729                 chan->uniqueid,
2730                 cause);
2731         ast_channel_unlock(chan);
2732
2733         return res;
2734 }
2735
2736 static void free_translation(struct ast_channel *clonechan)
2737 {
2738         if (clonechan->writetrans)
2739                 ast_translator_free_path(clonechan->writetrans);
2740         if (clonechan->readtrans)
2741                 ast_translator_free_path(clonechan->readtrans);
2742         clonechan->writetrans = NULL;
2743         clonechan->readtrans = NULL;
2744         if (ast_format_cap_is_empty(clonechan->nativeformats)) {
2745                 ast_format_clear(&clonechan->rawwriteformat);
2746                 ast_format_clear(&clonechan->rawreadformat);
2747         } else {
2748                 struct ast_format tmpfmt;
2749                 ast_best_codec(clonechan->nativeformats, &tmpfmt);
2750                 ast_format_copy(&clonechan->rawwriteformat, &tmpfmt);
2751                 ast_format_copy(&clonechan->rawreadformat, &tmpfmt);
2752         }
2753 }
2754
2755 void ast_set_hangupsource(struct ast_channel *chan, const char *source, int force)
2756 {
2757         struct ast_channel *bridge;
2758
2759         ast_channel_lock(chan);
2760         if (force || ast_strlen_zero(chan->hangupsource)) {
2761                 ast_string_field_set(chan, hangupsource, source);
2762         }
2763         bridge = ast_bridged_channel(chan);
2764         ast_channel_unlock(chan);
2765
2766         if (bridge && (force || ast_strlen_zero(bridge->hangupsource))) {
2767                 ast_channel_lock(bridge);
2768                 ast_string_field_set(chan, hangupsource, source);
2769                 ast_channel_unlock(bridge);
2770         }
2771 }
2772
2773 /*! \brief Hangup a channel */
2774 int ast_hangup(struct ast_channel *chan)
2775 {
2776         int res = 0;
2777         char extra_str[64]; /* used for cel logging below */
2778
2779         /* Don't actually hang up a channel that will masquerade as someone else, or
2780            if someone is going to masquerade as us */
2781         ast_channel_lock(chan);
2782
2783         if (chan->audiohooks) {
2784                 ast_audiohook_detach_list(chan->audiohooks);
2785                 chan->audiohooks = NULL;
2786         }
2787
2788         ast_framehook_list_destroy(chan);
2789
2790         ast_autoservice_stop(chan);
2791
2792         if (chan->masq) {
2793                 ast_channel_unlock(chan);
2794                 if (ast_do_masquerade(chan)) {
2795                         ast_log(LOG_WARNING, "Failed to perform masquerade\n");
2796                 }
2797                 ast_channel_lock(chan);
2798         }
2799
2800         if (chan->masq) {
2801                 ast_log(LOG_WARNING, "%s getting hung up, but someone is trying to masq into us?!?\n", chan->name);
2802                 ast_channel_unlock(chan);
2803                 return 0;
2804         }
2805         /* If this channel is one which will be masqueraded into something,
2806            mark it as a zombie already, so we know to free it later */
2807         if (chan->masqr) {
2808                 ast_set_flag(chan, AST_FLAG_ZOMBIE);
2809                 ast_channel_unlock(chan);
2810                 return 0;
2811         }
2812         ast_channel_unlock(chan);
2813
2814         ao2_unlink(channels, chan);
2815
2816         ast_channel_lock(chan);
2817         free_translation(chan);
2818         /* Close audio stream */
2819         if (chan->stream) {
2820                 ast_closestream(chan->stream);
2821                 chan->stream = NULL;
2822         }
2823         /* Close video stream */
2824         if (chan->vstream) {
2825                 ast_closestream(chan->vstream);
2826                 chan->vstream = NULL;
2827         }
2828         if (chan->sched) {
2829                 ast_sched_context_destroy(chan->sched);
2830                 chan->sched = NULL;
2831         }
2832
2833         if (chan->generatordata)        /* Clear any tone stuff remaining */
2834                 if (chan->generator && chan->generator->release)
2835                         chan->generator->release(chan, chan->generatordata);
2836         chan->generatordata = NULL;
2837         chan->generator = NULL;
2838
2839         snprintf(extra_str, sizeof(extra_str), "%d,%s,%s", chan->hangupcause, chan->hangupsource, S_OR(pbx_builtin_getvar_helper(chan, "DIALSTATUS"), ""));
2840         ast_cel_report_event(chan, AST_CEL_HANGUP, NULL, extra_str, NULL);
2841
2842         if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
2843                 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
2844                                         "is blocked by thread %ld in procedure %s!  Expect a failure\n",
2845                                         (long)pthread_self(), chan->name, (long)chan->blocker, chan->blockproc);
2846                 ast_assert(ast_test_flag(chan, AST_FLAG_BLOCKING) == 0);
2847         }
2848         if (!ast_test_flag(chan, AST_FLAG_ZOMBIE)) {
2849                 ast_debug(1, "Hanging up channel '%s'\n", chan->name);
2850                 if (chan->tech->hangup)
2851                         res = chan->tech->hangup(chan);
2852         } else {
2853                 ast_debug(1, "Hanging up zombie '%s'\n", chan->name);
2854         }
2855
2856         ast_channel_unlock(chan);
2857         ast_cc_offer(chan);
2858         ast_manager_event(chan, EVENT_FLAG_CALL, "Hangup",
2859                 "Channel: %s\r\n"
2860                 "Uniqueid: %s\r\n"
2861                 "CallerIDNum: %s\r\n"
2862                 "CallerIDName: %s\r\n"
2863                 "ConnectedLineNum: %s\r\n"
2864                 "ConnectedLineName: %s\r\n"
2865                 "Cause: %d\r\n"
2866                 "Cause-txt: %s\r\n",
2867                 chan->name,
2868                 chan->uniqueid,
2869                 S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, "<unknown>"),
2870                 S_COR(chan->caller.id.name.valid, chan->caller.id.name.str, "<unknown>"),
2871                 S_COR(chan->connected.id.number.valid, chan->connected.id.number.str, "<unknown>"),
2872                 S_COR(chan->connected.id.name.valid, chan->connected.id.name.str, "<unknown>"),
2873                 chan->hangupcause,
2874                 ast_cause2str(chan->hangupcause)
2875                 );
2876
2877         if (chan->cdr && !ast_test_flag(chan->cdr, AST_CDR_FLAG_BRIDGED) && 
2878                 !ast_test_flag(chan->cdr, AST_CDR_FLAG_POST_DISABLED) && 
2879             (chan->cdr->disposition != AST_CDR_NULL || ast_test_flag(chan->cdr, AST_CDR_FLAG_DIALED))) {
2880                 ast_channel_lock(chan);
2881                         
2882                 ast_cdr_end(chan->cdr);
2883                 ast_cdr_detach(chan->cdr);
2884                 chan->cdr = NULL;
2885                 ast_channel_unlock(chan);
2886         }
2887
2888         chan = ast_channel_release(chan);
2889
2890         return res;
2891 }
2892
2893 int ast_raw_answer(struct ast_channel *chan, int cdr_answer)
2894 {
2895         int res = 0;
2896
2897         ast_channel_lock(chan);
2898
2899         /* You can't answer an outbound call */
2900         if (ast_test_flag(chan, AST_FLAG_OUTGOING)) {
2901                 ast_channel_unlock(chan);
2902                 return 0;
2903         }
2904
2905         /* Stop if we're a zombie or need a soft hangup */
2906         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2907                 ast_channel_unlock(chan);
2908                 return -1;
2909         }
2910
2911         ast_channel_unlock(chan);
2912
2913         switch (chan->_state) {
2914         case AST_STATE_RINGING:
2915         case AST_STATE_RING:
2916                 ast_channel_lock(chan);
2917                 if (chan->tech->answer) {
2918                         res = chan->tech->answer(chan);
2919                 }
2920                 ast_setstate(chan, AST_STATE_UP);
2921                 if (cdr_answer) {
2922                         ast_cdr_answer(chan->cdr);
2923                 }
2924                 ast_cel_report_event(chan, AST_CEL_ANSWER, NULL, NULL, NULL);
2925                 ast_channel_unlock(chan);
2926                 break;
2927         case AST_STATE_UP:
2928                 ast_cel_report_event(chan, AST_CEL_ANSWER, NULL, NULL, NULL);
2929                 /* Calling ast_cdr_answer when it it has previously been called
2930                  * is essentially a no-op, so it is safe.
2931                  */
2932                 if (cdr_answer) {
2933                         ast_cdr_answer(chan->cdr);
2934                 }
2935                 break;
2936         default:
2937                 break;
2938         }
2939
2940         ast_indicate(chan, -1);
2941
2942         return res;
2943 }
2944
2945 int __ast_answer(struct ast_channel *chan, unsigned int delay, int cdr_answer)
2946 {
2947         int res = 0;
2948         enum ast_channel_state old_state;
2949
2950         old_state = chan->_state;
2951         if ((res = ast_raw_answer(chan, cdr_answer))) {
2952                 return res;
2953         }
2954
2955         switch (old_state) {
2956         case AST_STATE_RINGING:
2957         case AST_STATE_RING:
2958                 /* wait for media to start flowing, but don't wait any longer
2959                  * than 'delay' or 500 milliseconds, whichever is longer
2960                  */
2961                 do {
2962                         AST_LIST_HEAD_NOLOCK(, ast_frame) frames;
2963                         struct ast_frame *cur, *new;
2964                         int ms = MAX(delay, 500);
2965                         unsigned int done = 0;
2966
2967                         AST_LIST_HEAD_INIT_NOLOCK(&frames);
2968
2969                         for (;;) {
2970                                 ms = ast_waitfor(chan, ms);
2971                                 if (ms < 0) {
2972                                         ast_log(LOG_WARNING, "Error condition occurred when polling channel %s for a voice frame: %s\n", chan->name, strerror(errno));
2973                                         res = -1;
2974                                         break;
2975                                 }
2976                                 if (ms == 0) {
2977                                         ast_debug(2, "Didn't receive a media frame from %s within %d ms of answering. Continuing anyway\n", chan->name, MAX(delay, 500));
2978                                         break;
2979                                 }
2980                                 cur = ast_read(chan);
2981                                 if (!cur || ((cur->frametype == AST_FRAME_CONTROL) &&
2982                                              (cur->subclass.integer == AST_CONTROL_HANGUP))) {
2983                                         if (cur) {
2984                                                 ast_frfree(cur);
2985                                         }
2986                                         res = -1;
2987                                         ast_debug(2, "Hangup of channel %s detected in answer routine\n", chan->name);
2988                                         break;
2989                                 }
2990
2991                                 if ((new = ast_frisolate(cur)) != cur) {
2992                                         ast_frfree(cur);
2993                                 }
2994
2995                                 AST_LIST_INSERT_HEAD(&frames, new, frame_list);
2996
2997                                 /* if a specific delay period was requested, continue
2998                                  * until that delay has passed. don't stop just because
2999                                  * incoming media has arrived.
3000                                  */
3001                                 if (delay) {
3002                                         continue;
3003                                 }
3004
3005                                 switch (new->frametype) {
3006                                         /* all of these frametypes qualify as 'media' */
3007                                 case AST_FRAME_VOICE:
3008                                 case AST_FRAME_VIDEO:
3009                                 case AST_FRAME_TEXT:
3010                                 case AST_FRAME_DTMF_BEGIN:
3011                                 case AST_FRAME_DTMF_END:
3012                                 case AST_FRAME_IMAGE:
3013                                 case AST_FRAME_HTML:
3014                                 case AST_FRAME_MODEM:
3015                                         done = 1;
3016                                         break;
3017                                 case AST_FRAME_CONTROL:
3018                                 case AST_FRAME_IAX:
3019                                 case AST_FRAME_NULL:
3020                                 case AST_FRAME_CNG:
3021                                         break;
3022                                 }
3023
3024                                 if (done) {
3025                                         break;
3026                                 }
3027                         }
3028
3029                         if (res == 0) {
3030                                 ast_channel_lock(chan);
3031                                 while ((cur = AST_LIST_REMOVE_HEAD(&frames, frame_list))) {
3032                                         ast_queue_frame_head(chan, cur);
3033                                         ast_frfree(cur);
3034                                 }
3035                                 ast_channel_unlock(chan);
3036                         }
3037                 } while (0);
3038                 break;
3039         default:
3040                 break;
3041         }
3042
3043         return res;
3044 }
3045
3046 int ast_answer(struct ast_channel *chan)
3047 {
3048         return __ast_answer(chan, 0, 1);
3049 }
3050
3051 void ast_deactivate_generator(struct ast_channel *chan)
3052 {
3053         ast_channel_lock(chan);
3054         if (chan->generatordata) {
3055                 if (chan->generator && chan->generator->release)
3056                         chan->generator->release(chan, chan->generatordata);
3057                 chan->generatordata = NULL;
3058                 chan->generator = NULL;
3059                 ast_channel_set_fd(chan, AST_GENERATOR_FD, -1);
3060                 ast_clear_flag(chan, AST_FLAG_WRITE_INT);
3061                 ast_settimeout(chan, 0, NULL, NULL);
3062         }
3063         ast_channel_unlock(chan);
3064 }
3065
3066 static void generator_write_format_change(struct ast_channel *chan)
3067 {
3068         ast_channel_lock(chan);
3069         if (chan->generator && chan->generator->write_format_change) {
3070                 chan->generator->write_format_change(chan, chan->generatordata);
3071         }
3072         ast_channel_unlock(chan);
3073 }
3074
3075 static int generator_force(const void *data)
3076 {
3077         /* Called if generator doesn't have data */
3078         void *tmp;
3079         int res;
3080         int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples) = NULL;
3081         struct ast_channel *chan = (struct ast_channel *)data;
3082
3083         ast_channel_lock(chan);
3084         tmp = chan->generatordata;
3085         chan->generatordata = NULL;
3086         if (chan->generator)
3087                 generate = chan->generator->generate;
3088         ast_channel_unlock(chan);
3089
3090         if (!tmp || !generate)
3091                 return 0;
3092
3093         res = generate(chan, tmp, 0, ast_format_rate(&chan->writeformat) / 50);
3094
3095         chan->generatordata = tmp;
3096
3097         if (res) {
3098                 ast_debug(1, "Auto-deactivating generator\n");
3099                 ast_deactivate_generator(chan);
3100         }
3101
3102         return 0;
3103 }
3104
3105 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
3106 {
3107         int res = 0;
3108
3109         ast_channel_lock(chan);
3110         if (chan->generatordata) {
3111                 if (chan->generator && chan->generator->release)
3112                         chan->generator->release(chan, chan->generatordata);
3113                 chan->generatordata = NULL;
3114         }
3115         if (gen->alloc && !(chan->generatordata = gen->alloc(chan, params))) {
3116                 res = -1;
3117         }
3118         if (!res) {
3119                 ast_settimeout(chan, 50, generator_force, chan);
3120                 chan->generator = gen;
3121         }
3122         ast_channel_unlock(chan);
3123
3124         ast_prod(chan);
3125
3126         return res;
3127 }
3128
3129 /*! \brief Wait for x amount of time on a file descriptor to have input.  */
3130 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
3131 {
3132         int winner = -1;
3133         ast_waitfor_nandfds(NULL, 0, fds, n, exception, &winner, ms);
3134         return winner;
3135 }
3136
3137 /*! \brief Wait for x amount of time on a file descriptor to have input.  */
3138 #ifdef HAVE_EPOLL
3139 static struct ast_channel *ast_waitfor_nandfds_classic(struct ast_channel **c, int n, int *fds, int nfds,
3140                                         int *exception, int *outfd, int *ms)
3141 #else
3142 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
3143                                         int *exception, int *outfd, int *ms)
3144 #endif
3145 {
3146         struct timeval start = { 0 , 0 };
3147         struct pollfd *pfds = NULL;
3148         int res;
3149         long rms;
3150         int x, y, max;
3151         int sz;
3152         struct timeval now = { 0, 0 };
3153         struct timeval whentohangup = { 0, 0 }, diff;
3154         struct ast_channel *winner = NULL;
3155         struct fdmap {
3156                 int chan;
3157                 int fdno;
3158         } *fdmap = NULL;
3159
3160         if ((sz = n * AST_MAX_FDS + nfds)) {
3161                 pfds = alloca(sizeof(*pfds) * sz);
3162                 fdmap = alloca(sizeof(*fdmap) * sz);
3163         }
3164
3165         if (outfd)
3166                 *outfd = -99999;
3167         if (exception)
3168                 *exception = 0;
3169         
3170         /* Perform any pending masquerades */
3171         for (x = 0; x < n; x++) {
3172                 if (c[x]->masq && ast_do_masquerade(c[x])) {
3173                         ast_log(LOG_WARNING, "Masquerade failed\n");
3174                         *ms = -1;
3175                         return NULL;
3176                 }
3177
3178                 ast_channel_lock(c[x]);
3179                 if (!ast_tvzero(c[x]->whentohangup)) {
3180                         if (ast_tvzero(whentohangup))
3181                                 now = ast_tvnow();
3182                         diff = ast_tvsub(c[x]->whentohangup, now);
3183                         if (diff.tv_sec < 0 || ast_tvzero(diff)) {
3184                                 /* Should already be hungup */
3185                                 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
3186                                 ast_channel_unlock(c[x]);
3187                                 return c[x];
3188                         }
3189                         if (ast_tvzero(whentohangup) || ast_tvcmp(diff, whentohangup) < 0)
3190                                 whentohangup = diff;
3191                 }
3192                 ast_channel_unlock(c[x]);
3193         }
3194         /* Wait full interval */
3195         rms = *ms;
3196         /* INT_MAX, not LONG_MAX, because it matters on 64-bit */
3197         if (!ast_tvzero(whentohangup) && whentohangup.tv_sec < INT_MAX / 1000) {
3198                 rms = whentohangup.tv_sec * 1000 + whentohangup.tv_usec / 1000;              /* timeout in milliseconds */
3199                 if (*ms >= 0 && *ms < rms) {                                                 /* original *ms still smaller */
3200                         rms =  *ms;
3201                 }
3202         } else if (!ast_tvzero(whentohangup) && rms < 0) {
3203                 /* Tiny corner case... call would need to last >24 days */
3204                 rms = INT_MAX;
3205         }
3206         /*
3207          * Build the pollfd array, putting the channels' fds first,
3208          * followed by individual fds. Order is important because
3209          * individual fd's must have priority over channel fds.
3210          */
3211         max = 0;
3212         for (x = 0; x < n; x++) {
3213                 for (y = 0; y < AST_MAX_FDS; y++) {
3214                         fdmap[max].fdno = y;  /* fd y is linked to this pfds */
3215                         fdmap[max].chan = x;  /* channel x is linked to this pfds */
3216                         max += ast_add_fd(&pfds[max], c[x]->fds[y]);
3217                 }
3218                 CHECK_BLOCKING(c[x]);
3219         }
3220         /* Add the individual fds */
3221         for (x = 0; x < nfds; x++) {
3222                 fdmap[max].chan = -1;
3223                 max += ast_add_fd(&pfds[max], fds[x]);
3224         }
3225
3226         if (*ms > 0)
3227                 start = ast_tvnow();
3228         
3229         if (sizeof(int) == 4) { /* XXX fix timeout > 600000 on linux x86-32 */
3230                 do {
3231                         int kbrms = rms;
3232                         if (kbrms > 600000)
3233                                 kbrms = 600000;
3234                         res = ast_poll(pfds, max, kbrms);
3235                         if (!res)
3236                                 rms -= kbrms;
3237                 } while (!res && (rms > 0));
3238         } else {
3239                 res = ast_poll(pfds, max, rms);
3240         }
3241         for (x = 0; x < n; x++)
3242                 ast_clear_flag(c[x], AST_FLAG_BLOCKING);
3243         if (res < 0) { /* Simulate a timeout if we were interrupted */
3244                 if (errno != EINTR)
3245                         *ms = -1;
3246                 return NULL;
3247         }
3248         if (!ast_tvzero(whentohangup)) {   /* if we have a timeout, check who expired */
3249                 now = ast_tvnow();
3250                 for (x = 0; x < n; x++) {
3251                         if (!ast_tvzero(c[x]->whentohangup) && ast_tvcmp(c[x]->whentohangup, now) <= 0) {
3252                                 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
3253                                 if (winner == NULL)
3254                                         winner = c[x];
3255                         }
3256                 }
3257         }
3258         if (res == 0) { /* no fd ready, reset timeout and done */
3259                 *ms = 0;        /* XXX use 0 since we may not have an exact timeout. */
3260                 return winner;
3261         }
3262         /*
3263          * Then check if any channel or fd has a pending event.
3264          * Remember to check channels first and fds last, as they
3265          * must have priority on setting 'winner'
3266          */
3267         for (x = 0; x < max; x++) {
3268                 res = pfds[x].revents;
3269                 if (res == 0)
3270                         continue;
3271                 if (fdmap[x].chan >= 0) {       /* this is a channel */
3272                         winner = c[fdmap[x].chan];      /* override previous winners */
3273                         if (res & POLLPRI)
3274                                 ast_set_flag(winner, AST_FLAG_EXCEPTION);
3275                         else
3276                                 ast_clear_flag(winner, AST_FLAG_EXCEPTION);
3277                         winner->fdno = fdmap[x].fdno;
3278                 } else {                        /* this is an fd */
3279                         if (outfd)
3280                                 *outfd = pfds[x].fd;
3281                         if (exception)
3282                                 *exception = (res & POLLPRI) ? -1 : 0;
3283                         winner = NULL;
3284                 }
3285         }
3286         if (*ms > 0) {
3287                 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
3288                 if (*ms < 0)
3289                         *ms = 0;
3290         }
3291         return winner;
3292 }
3293
3294 #ifdef HAVE_EPOLL
3295 static struct ast_channel *ast_waitfor_nandfds_simple(struct ast_channel *chan, int *ms)
3296 {
3297         struct timeval start = { 0 , 0 };
3298         int res = 0;
3299         struct epoll_event ev[1];
3300         long diff, rms = *ms;
3301         struct ast_channel *winner = NULL;
3302         struct ast_epoll_data *aed = NULL;
3303
3304
3305         /* See if this channel needs to be masqueraded */
3306         if (chan->masq && ast_do_masquerade(chan)) {
3307                 ast_log(LOG_WARNING, "Failed to perform masquerade on %s\n", chan->name);
3308                 *ms = -1;
3309                 return NULL;
3310         }
3311
3312         ast_channel_lock(chan);
3313         /* Figure out their timeout */
3314         if (!ast_tvzero(chan->whentohangup)) {
3315                 if ((diff = ast_tvdiff_ms(chan->whentohangup, ast_tvnow())) < 0) {
3316                         /* They should already be hungup! */
3317                         chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
3318                         ast_channel_unlock(chan);
3319                         return NULL;
3320                 }
3321                 /* If this value is smaller then the current one... make it priority */
3322                 if (rms > diff)
3323                         rms = diff;
3324         }
3325
3326         ast_channel_unlock(chan);