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