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