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