Merged revisions 108135 via svnmerge from
[asterisk/asterisk.git] / main / channel.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2006, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*! \file
20  *
21  * \brief Channel Management
22  *
23  * \author Mark Spencer <markster@digium.com>
24  */
25
26 #include "asterisk.h"
27
28 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
29
30 #include "asterisk/_private.h"
31
32 #include <sys/time.h>
33 #include <signal.h>
34 #include <math.h>
35
36 #include "asterisk/paths.h"     /* use ast_config_AST_SYSTEM_NAME */
37 #include "asterisk/zapata.h"
38
39 #include "asterisk/pbx.h"
40 #include "asterisk/frame.h"
41 #include "asterisk/sched.h"
42 #include "asterisk/channel.h"
43 #include "asterisk/musiconhold.h"
44 #include "asterisk/say.h"
45 #include "asterisk/file.h"
46 #include "asterisk/cli.h"
47 #include "asterisk/translate.h"
48 #include "asterisk/manager.h"
49 #include "asterisk/chanvars.h"
50 #include "asterisk/linkedlists.h"
51 #include "asterisk/indications.h"
52 #include "asterisk/monitor.h"
53 #include "asterisk/causes.h"
54 #include "asterisk/callerid.h"
55 #include "asterisk/utils.h"
56 #include "asterisk/lock.h"
57 #include "asterisk/app.h"
58 #include "asterisk/transcap.h"
59 #include "asterisk/devicestate.h"
60 #include "asterisk/sha1.h"
61 #include "asterisk/threadstorage.h"
62 #include "asterisk/slinfactory.h"
63 #include "asterisk/audiohook.h"
64
65 #ifdef HAVE_EPOLL
66 #include <sys/epoll.h>
67 #endif
68
69 struct ast_epoll_data {
70         struct ast_channel *chan;
71         int which;
72 };
73
74 /* uncomment if you have problems with 'monitoring' synchronized files */
75 #if 0
76 #define MONITOR_CONSTANT_DELAY
77 #define MONITOR_DELAY   150 * 8         /*!< 150 ms of MONITORING DELAY */
78 #endif
79
80 /*! \brief Prevent new channel allocation if shutting down. */
81 static int shutting_down;
82
83 static int uniqueint;
84
85 unsigned long global_fin, global_fout;
86
87 AST_THREADSTORAGE(state2str_threadbuf);
88 #define STATE2STR_BUFSIZE   32
89
90 /*! Default amount of time to use when emulating a digit as a begin and end 
91  *  100ms */
92 #define AST_DEFAULT_EMULATE_DTMF_DURATION 100
93
94 /*! Minimum allowed digit length - 80ms */
95 #define AST_MIN_DTMF_DURATION 80
96
97 /*! Minimum amount of time between the end of the last digit and the beginning 
98  *  of a new one - 45ms */
99 #define AST_MIN_DTMF_GAP 45
100
101 /*! \brief List of channel drivers */
102 struct chanlist {
103         const struct ast_channel_tech *tech;
104         AST_LIST_ENTRY(chanlist) list;
105 };
106
107 #ifdef CHANNEL_TRACE
108 /*! \brief Structure to hold channel context backtrace data */
109 struct ast_chan_trace_data {
110         int enabled;
111         AST_LIST_HEAD_NOLOCK(, ast_chan_trace) trace;
112 };
113
114 /*! \brief Structure to save contexts where an ast_chan has been into */
115 struct ast_chan_trace {
116         char context[AST_MAX_CONTEXT];
117         char exten[AST_MAX_EXTENSION];
118         int priority;
119         AST_LIST_ENTRY(ast_chan_trace) entry;
120 };
121 #endif
122
123 /*! \brief the list of registered channel types */
124 static AST_LIST_HEAD_NOLOCK_STATIC(backends, chanlist);
125
126 /*! \brief the list of channels we have. Note that the lock for this list is used for
127         both the channels list and the backends list.  */
128 static AST_RWLIST_HEAD_STATIC(channels, ast_channel);
129
130 /*! \brief map AST_CAUSE's to readable string representations 
131  *
132  * \ref causes.h
133 */
134 const struct ast_cause {
135         int cause;
136         const char *name;
137         const char *desc;
138 } causes[] = {
139         { AST_CAUSE_UNALLOCATED, "UNALLOCATED", "Unallocated (unassigned) number" },
140         { AST_CAUSE_NO_ROUTE_TRANSIT_NET, "NO_ROUTE_TRANSIT_NET", "No route to specified transmit network" },
141         { AST_CAUSE_NO_ROUTE_DESTINATION, "NO_ROUTE_DESTINATION", "No route to destination" },
142         { AST_CAUSE_CHANNEL_UNACCEPTABLE, "CHANNEL_UNACCEPTABLE", "Channel unacceptable" },
143         { AST_CAUSE_CALL_AWARDED_DELIVERED, "CALL_AWARDED_DELIVERED", "Call awarded and being delivered in an established channel" },
144         { AST_CAUSE_NORMAL_CLEARING, "NORMAL_CLEARING", "Normal Clearing" },
145         { AST_CAUSE_USER_BUSY, "USER_BUSY", "User busy" },
146         { AST_CAUSE_NO_USER_RESPONSE, "NO_USER_RESPONSE", "No user responding" },
147         { AST_CAUSE_NO_ANSWER, "NO_ANSWER", "User alerting, no answer" },
148         { AST_CAUSE_CALL_REJECTED, "CALL_REJECTED", "Call Rejected" },
149         { AST_CAUSE_NUMBER_CHANGED, "NUMBER_CHANGED", "Number changed" },
150         { AST_CAUSE_DESTINATION_OUT_OF_ORDER, "DESTINATION_OUT_OF_ORDER", "Destination out of order" },
151         { AST_CAUSE_INVALID_NUMBER_FORMAT, "INVALID_NUMBER_FORMAT", "Invalid number format" },
152         { AST_CAUSE_FACILITY_REJECTED, "FACILITY_REJECTED", "Facility rejected" },
153         { AST_CAUSE_RESPONSE_TO_STATUS_ENQUIRY, "RESPONSE_TO_STATUS_ENQUIRY", "Response to STATus ENQuiry" },
154         { AST_CAUSE_NORMAL_UNSPECIFIED, "NORMAL_UNSPECIFIED", "Normal, unspecified" },
155         { AST_CAUSE_NORMAL_CIRCUIT_CONGESTION, "NORMAL_CIRCUIT_CONGESTION", "Circuit/channel congestion" },
156         { AST_CAUSE_NETWORK_OUT_OF_ORDER, "NETWORK_OUT_OF_ORDER", "Network out of order" },
157         { AST_CAUSE_NORMAL_TEMPORARY_FAILURE, "NORMAL_TEMPORARY_FAILURE", "Temporary failure" },
158         { AST_CAUSE_SWITCH_CONGESTION, "SWITCH_CONGESTION", "Switching equipment congestion" },
159         { AST_CAUSE_ACCESS_INFO_DISCARDED, "ACCESS_INFO_DISCARDED", "Access information discarded" },
160         { AST_CAUSE_REQUESTED_CHAN_UNAVAIL, "REQUESTED_CHAN_UNAVAIL", "Requested channel not available" },
161         { AST_CAUSE_PRE_EMPTED, "PRE_EMPTED", "Pre-empted" },
162         { AST_CAUSE_FACILITY_NOT_SUBSCRIBED, "FACILITY_NOT_SUBSCRIBED", "Facility not subscribed" },
163         { AST_CAUSE_OUTGOING_CALL_BARRED, "OUTGOING_CALL_BARRED", "Outgoing call barred" },
164         { AST_CAUSE_INCOMING_CALL_BARRED, "INCOMING_CALL_BARRED", "Incoming call barred" },
165         { AST_CAUSE_BEARERCAPABILITY_NOTAUTH, "BEARERCAPABILITY_NOTAUTH", "Bearer capability not authorized" },
166         { AST_CAUSE_BEARERCAPABILITY_NOTAVAIL, "BEARERCAPABILITY_NOTAVAIL", "Bearer capability not available" },
167         { AST_CAUSE_BEARERCAPABILITY_NOTIMPL, "BEARERCAPABILITY_NOTIMPL", "Bearer capability not implemented" },
168         { AST_CAUSE_CHAN_NOT_IMPLEMENTED, "CHAN_NOT_IMPLEMENTED", "Channel not implemented" },
169         { AST_CAUSE_FACILITY_NOT_IMPLEMENTED, "FACILITY_NOT_IMPLEMENTED", "Facility not implemented" },
170         { AST_CAUSE_INVALID_CALL_REFERENCE, "INVALID_CALL_REFERENCE", "Invalid call reference value" },
171         { AST_CAUSE_INCOMPATIBLE_DESTINATION, "INCOMPATIBLE_DESTINATION", "Incompatible destination" },
172         { AST_CAUSE_INVALID_MSG_UNSPECIFIED, "INVALID_MSG_UNSPECIFIED", "Invalid message unspecified" },
173         { AST_CAUSE_MANDATORY_IE_MISSING, "MANDATORY_IE_MISSING", "Mandatory information element is missing" },
174         { AST_CAUSE_MESSAGE_TYPE_NONEXIST, "MESSAGE_TYPE_NONEXIST", "Message type nonexist." },
175         { AST_CAUSE_WRONG_MESSAGE, "WRONG_MESSAGE", "Wrong message" },
176         { AST_CAUSE_IE_NONEXIST, "IE_NONEXIST", "Info. element nonexist or not implemented" },
177         { AST_CAUSE_INVALID_IE_CONTENTS, "INVALID_IE_CONTENTS", "Invalid information element contents" },
178         { AST_CAUSE_WRONG_CALL_STATE, "WRONG_CALL_STATE", "Message not compatible with call state" },
179         { AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE, "RECOVERY_ON_TIMER_EXPIRE", "Recover on timer expiry" },
180         { AST_CAUSE_MANDATORY_IE_LENGTH_ERROR, "MANDATORY_IE_LENGTH_ERROR", "Mandatory IE length error" },
181         { AST_CAUSE_PROTOCOL_ERROR, "PROTOCOL_ERROR", "Protocol error, unspecified" },
182         { AST_CAUSE_INTERWORKING, "INTERWORKING", "Interworking, unspecified" },
183 };
184
185 struct ast_variable *ast_channeltype_list(void)
186 {
187         struct chanlist *cl;
188         struct ast_variable *var=NULL, *prev = NULL;
189         AST_LIST_TRAVERSE(&backends, cl, list) {
190                 if (prev)  {
191                         if ((prev->next = ast_variable_new(cl->tech->type, cl->tech->description, "")))
192                                 prev = prev->next;
193                 } else {
194                         var = ast_variable_new(cl->tech->type, cl->tech->description, "");
195                         prev = var;
196                 }
197         }
198         return var;
199 }
200
201 /*! \brief Show channel types - CLI command */
202 static char *handle_cli_core_show_channeltypes(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
203 {
204 #define FORMAT  "%-10.10s  %-40.40s %-12.12s %-12.12s %-12.12s\n"
205         struct chanlist *cl;
206         int count_chan = 0;
207
208         switch (cmd) {
209         case CLI_INIT:
210                 e->command = "core show channeltypes";
211                 e->usage =
212                         "Usage: core show channeltypes\n"
213                         "       Lists available channel types registered in your\n"
214                         "       Asterisk server.\n";
215                 return NULL;
216         case CLI_GENERATE:
217                 return NULL;
218         }
219
220         if (a->argc != 3)
221                 return CLI_SHOWUSAGE;
222
223         ast_cli(a->fd, FORMAT, "Type", "Description",       "Devicestate", "Indications", "Transfer");
224         ast_cli(a->fd, FORMAT, "----------", "-----------", "-----------", "-----------", "--------");
225
226         AST_RWLIST_RDLOCK(&channels);
227
228         AST_LIST_TRAVERSE(&backends, cl, list) {
229                 ast_cli(a->fd, FORMAT, cl->tech->type, cl->tech->description,
230                         (cl->tech->devicestate) ? "yes" : "no",
231                         (cl->tech->indicate) ? "yes" : "no",
232                         (cl->tech->transfer) ? "yes" : "no");
233                 count_chan++;
234         }
235
236         AST_RWLIST_UNLOCK(&channels);
237
238         ast_cli(a->fd, "----------\n%d channel drivers registered.\n", count_chan);
239
240         return CLI_SUCCESS;
241
242 #undef FORMAT
243 }
244
245 static char *complete_channeltypes(struct ast_cli_args *a)
246 {
247         struct chanlist *cl;
248         int which = 0;
249         int wordlen;
250         char *ret = NULL;
251
252         if (a->pos != 3)
253                 return NULL;
254
255         wordlen = strlen(a->word);
256
257         AST_LIST_TRAVERSE(&backends, cl, list) {
258                 if (!strncasecmp(a->word, cl->tech->type, wordlen) && ++which > a->n) {
259                         ret = ast_strdup(cl->tech->type);
260                         break;
261                 }
262         }
263         
264         return ret;
265 }
266
267 /*! \brief Show details about a channel driver - CLI command */
268 static char *handle_cli_core_show_channeltype(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
269 {
270         struct chanlist *cl = NULL;
271
272         switch (cmd) {
273         case CLI_INIT:
274                 e->command = "core show channeltype";
275                 e->usage =
276                         "Usage: core show channeltype <name>\n"
277                         "       Show details about the specified channel type, <name>.\n";
278                 return NULL;
279         case CLI_GENERATE:
280                 return complete_channeltypes(a);
281         }
282
283         if (a->argc != 4)
284                 return CLI_SHOWUSAGE;
285         
286         AST_RWLIST_RDLOCK(&channels);
287
288         AST_LIST_TRAVERSE(&backends, cl, list) {
289                 if (!strncasecmp(cl->tech->type, a->argv[3], strlen(cl->tech->type)))
290                         break;
291         }
292
293
294         if (!cl) {
295                 ast_cli(a->fd, "\n%s is not a registered channel driver.\n", a->argv[3]);
296                 AST_RWLIST_UNLOCK(&channels);
297                 return CLI_FAILURE;
298         }
299
300         ast_cli(a->fd,
301                 "-- Info about channel driver: %s --\n"
302                 "  Device State: %s\n"
303                 "    Indication: %s\n"
304                 "     Transfer : %s\n"
305                 "  Capabilities: %d\n"
306                 "   Digit Begin: %s\n"
307                 "     Digit End: %s\n"
308                 "    Send HTML : %s\n"
309                 " Image Support: %s\n"
310                 "  Text Support: %s\n",
311                 cl->tech->type,
312                 (cl->tech->devicestate) ? "yes" : "no",
313                 (cl->tech->indicate) ? "yes" : "no",
314                 (cl->tech->transfer) ? "yes" : "no",
315                 (cl->tech->capabilities) ? cl->tech->capabilities : -1,
316                 (cl->tech->send_digit_begin) ? "yes" : "no",
317                 (cl->tech->send_digit_end) ? "yes" : "no",
318                 (cl->tech->send_html) ? "yes" : "no",
319                 (cl->tech->send_image) ? "yes" : "no",
320                 (cl->tech->send_text) ? "yes" : "no"
321                 
322         );
323
324         AST_RWLIST_UNLOCK(&channels);
325         return CLI_SUCCESS;
326 }
327
328 static struct ast_cli_entry cli_channel[] = {
329         AST_CLI_DEFINE(handle_cli_core_show_channeltypes, "List available channel types"),
330         AST_CLI_DEFINE(handle_cli_core_show_channeltype,  "Give more details on that channel type")
331 };
332
333 #ifdef CHANNEL_TRACE
334 /*! \brief Destructor for the channel trace datastore */
335 static void ast_chan_trace_destroy_cb(void *data)
336 {
337         struct ast_chan_trace *trace;
338         struct ast_chan_trace_data *traced = data;
339         while ((trace = AST_LIST_REMOVE_HEAD(&traced->trace, entry))) {
340                 ast_free(trace);
341         }
342         ast_free(traced);
343 }
344
345 /*! \brief Datastore to put the linked list of ast_chan_trace and trace status */
346 const struct ast_datastore_info ast_chan_trace_datastore_info = {
347         .type = "ChanTrace",
348         .destroy = ast_chan_trace_destroy_cb
349 };
350
351 /*! \brief Put the channel backtrace in a string */
352 int ast_channel_trace_serialize(struct ast_channel *chan, struct ast_str **buf)
353 {
354         int total = 0;
355         struct ast_chan_trace *trace;
356         struct ast_chan_trace_data *traced;
357         struct ast_datastore *store;
358
359         ast_channel_lock(chan);
360         store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
361         if (!store) {
362                 ast_channel_unlock(chan);
363                 return total;
364         }
365         traced = store->data;
366         (*buf)->used = 0;
367         (*buf)->str[0] = '\0';
368         AST_LIST_TRAVERSE(&traced->trace, trace, entry) {
369                 if (ast_str_append(buf, 0, "[%d] => %s, %s, %d\n", total, trace->context, trace->exten, trace->priority) < 0) {
370                         ast_log(LOG_ERROR, "Data Buffer Size Exceeded!\n");
371                         total = -1;
372                         break;
373                 }
374                 total++;
375         }
376         ast_channel_unlock(chan);
377         return total;
378 }
379
380 /* !\brief Whether or not context tracing is enabled */
381 int ast_channel_trace_is_enabled(struct ast_channel *chan)
382 {
383         struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
384         if (!store)
385                 return 0;
386         return ((struct ast_chan_trace_data *)store->data)->enabled;
387 }
388
389 /*! \brief Update the context backtrace data if tracing is enabled */
390 static int ast_channel_trace_data_update(struct ast_channel *chan, struct ast_chan_trace_data *traced)
391 {
392         struct ast_chan_trace *trace;
393         if (!traced->enabled)
394                 return 0;
395         /* If the last saved context does not match the current one
396            OR we have not saved any context so far, then save the current context */
397         if ((!AST_LIST_EMPTY(&traced->trace) && strcasecmp(AST_LIST_FIRST(&traced->trace)->context, chan->context)) || 
398             (AST_LIST_EMPTY(&traced->trace))) {
399                 /* Just do some debug logging */
400                 if (AST_LIST_EMPTY(&traced->trace))
401                         ast_log(LOG_DEBUG, "Setting initial trace context to %s\n", chan->context);
402                 else
403                         ast_log(LOG_DEBUG, "Changing trace context from %s to %s\n", AST_LIST_FIRST(&traced->trace)->context, chan->context);
404                 /* alloc or bail out */
405                 trace = ast_malloc(sizeof(*trace));
406                 if (!trace) 
407                         return -1;
408                 /* save the current location and store it in the trace list */
409                 ast_copy_string(trace->context, chan->context, sizeof(trace->context));
410                 ast_copy_string(trace->exten, chan->exten, sizeof(trace->exten));
411                 trace->priority = chan->priority;
412                 AST_LIST_INSERT_HEAD(&traced->trace, trace, entry);
413         }
414         return 0;
415 }
416
417 /*! \brief Update the context backtrace if tracing is enabled */
418 int ast_channel_trace_update(struct ast_channel *chan)
419 {
420         struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
421         if (!store)
422                 return 0;
423         return ast_channel_trace_data_update(chan, store->data);
424 }
425
426 /*! \brief Enable context tracing in the channel */
427 int ast_channel_trace_enable(struct ast_channel *chan)
428 {
429         struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
430         struct ast_chan_trace_data *traced;
431         if (!store) {
432                 store = ast_channel_datastore_alloc(&ast_chan_trace_datastore_info, "ChanTrace");
433                 if (!store) 
434                         return -1;
435                 traced = ast_calloc(1, sizeof(*traced));
436                 if (!traced) {
437                         ast_channel_datastore_free(store);
438                         return -1;
439                 }       
440                 store->data = traced;
441                 AST_LIST_HEAD_INIT_NOLOCK(&traced->trace);
442                 ast_channel_datastore_add(chan, store);
443         }       
444         ((struct ast_chan_trace_data *)store->data)->enabled = 1;
445         ast_channel_trace_data_update(chan, store->data);
446         return 0;
447 }
448
449 /*! \brief Disable context tracing in the channel */
450 int ast_channel_trace_disable(struct ast_channel *chan)
451 {
452         struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
453         if (!store)
454                 return 0;
455         ((struct ast_chan_trace_data *)store->data)->enabled = 0;
456         return 0;
457 }
458 #endif /* CHANNEL_TRACE */
459
460 /*! \brief Checks to see if a channel is needing hang up */
461 int ast_check_hangup(struct ast_channel *chan)
462 {
463         if (chan->_softhangup)          /* yes if soft hangup flag set */
464                 return 1;
465         if (!chan->tech_pvt)            /* yes if no technology private data */
466                 return 1;
467         if (!chan->whentohangup)        /* no if no hangup scheduled */
468                 return 0;
469         if (chan->whentohangup > time(NULL))    /* no if hangup time has not come yet. */
470                 return 0;
471         chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;    /* record event */
472         return 1;
473 }
474
475 static int ast_check_hangup_locked(struct ast_channel *chan)
476 {
477         int res;
478         ast_channel_lock(chan);
479         res = ast_check_hangup(chan);
480         ast_channel_unlock(chan);
481         return res;
482 }
483
484 /*! \brief Initiate system shutdown */
485 void ast_begin_shutdown(int hangup)
486 {
487         struct ast_channel *c;
488         shutting_down = 1;
489         if (hangup) {
490                 AST_RWLIST_RDLOCK(&channels);
491                 AST_RWLIST_TRAVERSE(&channels, c, chan_list)
492                         ast_softhangup(c, AST_SOFTHANGUP_SHUTDOWN);
493                 AST_RWLIST_UNLOCK(&channels);
494         }
495 }
496
497 /*! \brief returns number of active/allocated channels */
498 int ast_active_channels(void)
499 {
500         struct ast_channel *c;
501         int cnt = 0;
502         AST_RWLIST_RDLOCK(&channels);
503         AST_RWLIST_TRAVERSE(&channels, c, chan_list)
504                 cnt++;
505         AST_RWLIST_UNLOCK(&channels);
506         return cnt;
507 }
508
509 /*! \brief Cancel a shutdown in progress */
510 void ast_cancel_shutdown(void)
511 {
512         shutting_down = 0;
513 }
514
515 /*! \brief Returns non-zero if Asterisk is being shut down */
516 int ast_shutting_down(void)
517 {
518         return shutting_down;
519 }
520
521 /*! \brief Set when to hangup channel */
522 void ast_channel_setwhentohangup(struct ast_channel *chan, time_t offset)
523 {
524         chan->whentohangup = offset ? time(NULL) + offset : 0;
525         ast_queue_frame(chan, &ast_null_frame);
526         return;
527 }
528
529 /*! \brief Compare a offset with when to hangup channel */
530 int ast_channel_cmpwhentohangup(struct ast_channel *chan, time_t offset)
531 {
532         time_t whentohangup;
533
534         if (!chan->whentohangup)
535                 return (offset == 0) ? 0 : -1;
536
537         if (!offset) /* XXX why is this special? */
538                 return 1;
539
540         whentohangup = offset + time(NULL);
541
542         if (chan->whentohangup < whentohangup)
543                 return 1;
544         else if (chan->whentohangup == whentohangup)
545                 return 0;
546         else
547                 return -1;
548 }
549
550 /*! \brief Register a new telephony channel in Asterisk */
551 int ast_channel_register(const struct ast_channel_tech *tech)
552 {
553         struct chanlist *chan;
554
555         AST_RWLIST_WRLOCK(&channels);
556
557         AST_LIST_TRAVERSE(&backends, chan, list) {
558                 if (!strcasecmp(tech->type, chan->tech->type)) {
559                         ast_log(LOG_WARNING, "Already have a handler for type '%s'\n", tech->type);
560                         AST_RWLIST_UNLOCK(&channels);
561                         return -1;
562                 }
563         }
564         
565         if (!(chan = ast_calloc(1, sizeof(*chan)))) {
566                 AST_RWLIST_UNLOCK(&channels);
567                 return -1;
568         }
569         chan->tech = tech;
570         AST_LIST_INSERT_HEAD(&backends, chan, list);
571
572         ast_debug(1, "Registered handler for '%s' (%s)\n", chan->tech->type, chan->tech->description);
573
574         ast_verb(2, "Registered channel type '%s' (%s)\n", chan->tech->type, chan->tech->description);
575
576         AST_RWLIST_UNLOCK(&channels);
577         return 0;
578 }
579
580 /*! \brief Unregister channel driver */
581 void ast_channel_unregister(const struct ast_channel_tech *tech)
582 {
583         struct chanlist *chan;
584
585         ast_debug(1, "Unregistering channel type '%s'\n", tech->type);
586
587         AST_RWLIST_WRLOCK(&channels);
588
589         AST_LIST_TRAVERSE_SAFE_BEGIN(&backends, chan, list) {
590                 if (chan->tech == tech) {
591                         AST_LIST_REMOVE_CURRENT(list);
592                         ast_free(chan);
593                         ast_verb(2, "Unregistered channel type '%s'\n", tech->type);
594                         break;  
595                 }
596         }
597         AST_LIST_TRAVERSE_SAFE_END;
598
599         AST_RWLIST_UNLOCK(&channels);
600 }
601
602 /*! \brief Get handle to channel driver based on name */
603 const struct ast_channel_tech *ast_get_channel_tech(const char *name)
604 {
605         struct chanlist *chanls;
606         const struct ast_channel_tech *ret = NULL;
607
608         AST_RWLIST_RDLOCK(&channels);
609
610         AST_LIST_TRAVERSE(&backends, chanls, list) {
611                 if (!strcasecmp(name, chanls->tech->type)) {
612                         ret = chanls->tech;
613                         break;
614                 }
615         }
616
617         AST_RWLIST_UNLOCK(&channels);
618         
619         return ret;
620 }
621
622 /*! \brief Gives the string form of a given hangup cause */
623 const char *ast_cause2str(int cause)
624 {
625         int x;
626
627         for (x = 0; x < ARRAY_LEN(causes); x++) {
628                 if (causes[x].cause == cause)
629                         return causes[x].desc;
630         }
631
632         return "Unknown";
633 }
634
635 /*! \brief Convert a symbolic hangup cause to number */
636 int ast_str2cause(const char *name)
637 {
638         int x;
639
640         for (x = 0; x < ARRAY_LEN(causes); x++)
641                 if (!strncasecmp(causes[x].name, name, strlen(causes[x].name)))
642                         return causes[x].cause;
643
644         return -1;
645 }
646
647 /*! \brief Gives the string form of a given channel state.
648         \note This function is not reentrant.
649  */
650 const char *ast_state2str(enum ast_channel_state state)
651 {
652         char *buf;
653
654         switch (state) {
655         case AST_STATE_DOWN:
656                 return "Down";
657         case AST_STATE_RESERVED:
658                 return "Rsrvd";
659         case AST_STATE_OFFHOOK:
660                 return "OffHook";
661         case AST_STATE_DIALING:
662                 return "Dialing";
663         case AST_STATE_RING:
664                 return "Ring";
665         case AST_STATE_RINGING:
666                 return "Ringing";
667         case AST_STATE_UP:
668                 return "Up";
669         case AST_STATE_BUSY:
670                 return "Busy";
671         case AST_STATE_DIALING_OFFHOOK:
672                 return "Dialing Offhook";
673         case AST_STATE_PRERING:
674                 return "Pre-ring";
675         default:
676                 if (!(buf = ast_threadstorage_get(&state2str_threadbuf, STATE2STR_BUFSIZE)))
677                         return "Unknown";
678                 snprintf(buf, STATE2STR_BUFSIZE, "Unknown (%d)", state);
679                 return buf;
680         }
681 }
682
683 /*! \brief Gives the string form of a given transfer capability */
684 char *ast_transfercapability2str(int transfercapability)
685 {
686         switch (transfercapability) {
687         case AST_TRANS_CAP_SPEECH:
688                 return "SPEECH";
689         case AST_TRANS_CAP_DIGITAL:
690                 return "DIGITAL";
691         case AST_TRANS_CAP_RESTRICTED_DIGITAL:
692                 return "RESTRICTED_DIGITAL";
693         case AST_TRANS_CAP_3_1K_AUDIO:
694                 return "3K1AUDIO";
695         case AST_TRANS_CAP_DIGITAL_W_TONES:
696                 return "DIGITAL_W_TONES";
697         case AST_TRANS_CAP_VIDEO:
698                 return "VIDEO";
699         default:
700                 return "UNKNOWN";
701         }
702 }
703
704 /*! \brief Pick the best audio codec */
705 int ast_best_codec(int fmts)
706 {
707         /* This just our opinion, expressed in code.  We are asked to choose
708            the best codec to use, given no information */
709         int x;
710         static const int prefs[] =
711         {
712                 /*! Okay, ulaw is used by all telephony equipment, so start with it */
713                 AST_FORMAT_ULAW,
714                 /*! Unless of course, you're a silly European, so then prefer ALAW */
715                 AST_FORMAT_ALAW,
716                 /*! G.722 is better then all below, but not as common as the above... so give ulaw and alaw priority */
717                 AST_FORMAT_G722,
718                 /*! Okay, well, signed linear is easy to translate into other stuff */
719                 AST_FORMAT_SLINEAR16,
720                 AST_FORMAT_SLINEAR,
721                 /*! G.726 is standard ADPCM, in RFC3551 packing order */
722                 AST_FORMAT_G726,
723                 /*! G.726 is standard ADPCM, in AAL2 packing order */
724                 AST_FORMAT_G726_AAL2,
725                 /*! ADPCM has great sound quality and is still pretty easy to translate */
726                 AST_FORMAT_ADPCM,
727                 /*! Okay, we're down to vocoders now, so pick GSM because it's small and easier to
728                     translate and sounds pretty good */
729                 AST_FORMAT_GSM,
730                 /*! iLBC is not too bad */
731                 AST_FORMAT_ILBC,
732                 /*! Speex is free, but computationally more expensive than GSM */
733                 AST_FORMAT_SPEEX,
734                 /*! Ick, LPC10 sounds terrible, but at least we have code for it, if you're tacky enough
735                     to use it */
736                 AST_FORMAT_LPC10,
737                 /*! G.729a is faster than 723 and slightly less expensive */
738                 AST_FORMAT_G729A,
739                 /*! Down to G.723.1 which is proprietary but at least designed for voice */
740                 AST_FORMAT_G723_1,
741         };
742
743         /* Strip out video */
744         fmts &= AST_FORMAT_AUDIO_MASK;
745         
746         /* Find the first preferred codec in the format given */
747         for (x = 0; x < (sizeof(prefs) / sizeof(prefs[0]) ); x++) {
748                 if (fmts & prefs[x])
749                         return prefs[x];
750         }
751
752         ast_log(LOG_WARNING, "Don't know any of 0x%x formats\n", fmts);
753
754         return 0;
755 }
756
757 static const struct ast_channel_tech null_tech = {
758         .type = "NULL",
759         .description = "Null channel (should not see this)",
760 };
761
762 /*! \brief Create a new channel structure */
763 struct ast_channel *ast_channel_alloc(int needqueue, int state, const char *cid_num, const char *cid_name, const char *acctcode, const char *exten, const char *context, const int amaflag, const char *name_fmt, ...)
764 {
765         struct ast_channel *tmp;
766         int x;
767         int flags;
768         struct varshead *headp;
769         va_list ap1, ap2;
770
771         /* If shutting down, don't allocate any new channels */
772         if (shutting_down) {
773                 ast_log(LOG_WARNING, "Channel allocation failed: Refusing due to active shutdown\n");
774                 return NULL;
775         }
776
777         if (!(tmp = ast_calloc(1, sizeof(*tmp))))
778                 return NULL;
779
780         if (!(tmp->sched = sched_context_create())) {
781                 ast_log(LOG_WARNING, "Channel allocation failed: Unable to create schedule context\n");
782                 ast_free(tmp);
783                 return NULL;
784         }
785         
786         if ((ast_string_field_init(tmp, 128))) {
787                 sched_context_destroy(tmp->sched);
788                 ast_free(tmp);
789                 return NULL;
790         }
791
792 #ifdef HAVE_EPOLL
793         tmp->epfd = epoll_create(25);
794 #endif
795
796         for (x = 0; x < AST_MAX_FDS; x++) {
797                 tmp->fds[x] = -1;
798 #ifdef HAVE_EPOLL
799                 tmp->epfd_data[x] = NULL;
800 #endif
801         }
802
803 #ifdef HAVE_ZAPTEL
804         tmp->timingfd = open("/dev/zap/timer", O_RDWR);
805         if (tmp->timingfd > -1) {
806                 /* Check if timing interface supports new
807                    ping/pong scheme */
808                 flags = 1;
809                 if (!ioctl(tmp->timingfd, ZT_TIMERPONG, &flags))
810                         needqueue = 0;
811         }
812 #else
813         tmp->timingfd = -1;                                     
814 #endif                                  
815
816         if (needqueue) {
817                 if (pipe(tmp->alertpipe)) {
818                         ast_log(LOG_WARNING, "Channel allocation failed: Can't create alert pipe!\n");
819 #ifdef HAVE_ZAPTEL
820                         if (tmp->timingfd > -1)
821                                 close(tmp->timingfd);
822 #endif
823                         sched_context_destroy(tmp->sched);
824                         ast_string_field_free_memory(tmp);
825                         ast_free(tmp);
826                         return NULL;
827                 } else {
828                         flags = fcntl(tmp->alertpipe[0], F_GETFL);
829                         fcntl(tmp->alertpipe[0], F_SETFL, flags | O_NONBLOCK);
830                         flags = fcntl(tmp->alertpipe[1], F_GETFL);
831                         fcntl(tmp->alertpipe[1], F_SETFL, flags | O_NONBLOCK);
832                 }
833         } else  /* Make sure we've got it done right if they don't */
834                 tmp->alertpipe[0] = tmp->alertpipe[1] = -1;
835
836         /* Always watch the alertpipe */
837         ast_channel_set_fd(tmp, AST_ALERT_FD, tmp->alertpipe[0]);
838         /* And timing pipe */
839         ast_channel_set_fd(tmp, AST_TIMING_FD, tmp->timingfd);
840         ast_string_field_set(tmp, name, "**Unknown**");
841
842         /* Initial state */
843         tmp->_state = state;
844
845         tmp->streamid = -1;
846         
847         tmp->fin = global_fin;
848         tmp->fout = global_fout;
849
850         if (ast_strlen_zero(ast_config_AST_SYSTEM_NAME)) {
851                 ast_string_field_build(tmp, uniqueid, "%li.%d", (long) time(NULL), 
852                                        ast_atomic_fetchadd_int(&uniqueint, 1));
853         } else {
854                 ast_string_field_build(tmp, uniqueid, "%s-%li.%d", ast_config_AST_SYSTEM_NAME, 
855                                        (long) time(NULL), ast_atomic_fetchadd_int(&uniqueint, 1));
856         }
857
858         tmp->cid.cid_name = ast_strdup(cid_name);
859         tmp->cid.cid_num = ast_strdup(cid_num);
860         
861         if (!ast_strlen_zero(name_fmt)) {
862                 /* Almost every channel is calling this function, and setting the name via the ast_string_field_build() call.
863                  * And they all use slightly different formats for their name string.
864                  * This means, to set the name here, we have to accept variable args, and call the string_field_build from here.
865                  * This means, that the stringfields must have a routine that takes the va_lists directly, and 
866                  * uses them to build the string, instead of forming the va_lists internally from the vararg ... list.
867                  * This new function was written so this can be accomplished.
868                  */
869                 va_start(ap1, name_fmt);
870                 va_start(ap2, name_fmt);
871                 ast_string_field_build_va(tmp, name, name_fmt, ap1, ap2);
872                 va_end(ap1);
873                 va_end(ap2);
874         }
875
876         /* Reminder for the future: under what conditions do we NOT want to track cdrs on channels? */
877
878         /* These 4 variables need to be set up for the cdr_init() to work right */
879         if (amaflag)
880                 tmp->amaflags = amaflag;
881         else
882                 tmp->amaflags = ast_default_amaflags;
883         
884         if (!ast_strlen_zero(acctcode))
885                 ast_string_field_set(tmp, accountcode, acctcode);
886         else
887                 ast_string_field_set(tmp, accountcode, ast_default_accountcode);
888                 
889         if (!ast_strlen_zero(context))
890                 ast_copy_string(tmp->context, context, sizeof(tmp->context));
891         else
892                 strcpy(tmp->context, "default");
893
894         if (!ast_strlen_zero(exten))
895                 ast_copy_string(tmp->exten, exten, sizeof(tmp->exten));
896         else
897                 strcpy(tmp->exten, "s");
898
899         tmp->priority = 1;
900                 
901         tmp->cdr = ast_cdr_alloc();
902         ast_cdr_init(tmp->cdr, tmp);
903         ast_cdr_start(tmp->cdr);
904         
905         headp = &tmp->varshead;
906         AST_LIST_HEAD_INIT_NOLOCK(headp);
907         
908         ast_mutex_init(&tmp->lock_dont_use);
909         
910         AST_LIST_HEAD_INIT_NOLOCK(&tmp->datastores);
911         
912         ast_string_field_set(tmp, language, defaultlanguage);
913
914         tmp->tech = &null_tech;
915
916         AST_RWLIST_WRLOCK(&channels);
917         AST_RWLIST_INSERT_HEAD(&channels, tmp, chan_list);
918         AST_RWLIST_UNLOCK(&channels);
919
920         /*\!note
921          * and now, since the channel structure is built, and has its name, let's
922          * call the manager event generator with this Newchannel event. This is the
923          * proper and correct place to make this call, but you sure do have to pass
924          * a lot of data into this func to do it here!
925          */
926         if (!ast_strlen_zero(name_fmt)) {
927                 manager_event(EVENT_FLAG_CALL, "Newchannel",
928                         "Channel: %s\r\n"
929                         "ChannelState: %d\r\n"
930                         "ChannelStateDesc: %s\r\n"
931                         "CallerIDNum: %s\r\n"
932                         "CallerIDName: %s\r\n"
933                         "AccountCode: %s\r\n"
934                         "Uniqueid: %s\r\n",
935                         tmp->name, 
936                         state, 
937                         ast_state2str(state),
938                         S_OR(cid_num, ""),
939                         S_OR(cid_name, ""),
940                         tmp->accountcode,
941                         tmp->uniqueid);
942         }
943
944         return tmp;
945 }
946
947 /*! \brief Queue an outgoing media frame */
948 int ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin)
949 {
950         struct ast_frame *f;
951         struct ast_frame *cur;
952         int blah = 1;
953         int qlen = 0;
954
955         /* Build us a copy and free the original one */
956         if (!(f = ast_frdup(fin))) {
957                 ast_log(LOG_WARNING, "Unable to duplicate frame\n");
958                 return -1;
959         }
960         ast_channel_lock(chan);
961
962         /* See if the last frame on the queue is a hangup, if so don't queue anything */
963         if ((cur = AST_LIST_LAST(&chan->readq)) && (cur->frametype == AST_FRAME_CONTROL) && (cur->subclass == AST_CONTROL_HANGUP)) {
964                 ast_frfree(f);
965                 ast_channel_unlock(chan);
966                 return 0;
967         }
968
969         /* Count how many frames exist on the queue */
970         AST_LIST_TRAVERSE(&chan->readq, cur, frame_list) {
971                 qlen++;
972         }
973
974         /* Allow up to 96 voice frames outstanding, and up to 128 total frames */
975         if (((fin->frametype == AST_FRAME_VOICE) && (qlen > 96)) || (qlen  > 128)) {
976                 if (fin->frametype != AST_FRAME_VOICE) {
977                         ast_log(LOG_WARNING, "Exceptionally long queue length queuing to %s\n", chan->name);
978                         CRASH;
979                 } else {
980                         ast_debug(1, "Dropping voice to exceptionally long queue on %s\n", chan->name);
981                         ast_frfree(f);
982                         ast_channel_unlock(chan);
983                         return 0;
984                 }
985         }
986         AST_LIST_INSERT_TAIL(&chan->readq, f, frame_list);
987         if (chan->alertpipe[1] > -1) {
988                 if (write(chan->alertpipe[1], &blah, sizeof(blah)) != sizeof(blah))
989                         ast_log(LOG_WARNING, "Unable to write to alert pipe on %s, frametype/subclass %d/%d (qlen = %d): %s!\n",
990                                 chan->name, f->frametype, f->subclass, qlen, strerror(errno));
991 #ifdef HAVE_ZAPTEL
992         } else if (chan->timingfd > -1) {
993                 ioctl(chan->timingfd, ZT_TIMERPING, &blah);
994 #endif                          
995         } else if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
996                 pthread_kill(chan->blocker, SIGURG);
997         }
998         ast_channel_unlock(chan);
999         return 0;
1000 }
1001
1002 /*! \brief Queue a hangup frame for channel */
1003 int ast_queue_hangup(struct ast_channel *chan)
1004 {
1005         struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_HANGUP };
1006         /* Yeah, let's not change a lock-critical value without locking */
1007         if (!ast_channel_trylock(chan)) {
1008                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1009                 ast_channel_unlock(chan);
1010         }
1011         return ast_queue_frame(chan, &f);
1012 }
1013
1014 /*! \brief Queue a control frame */
1015 int ast_queue_control(struct ast_channel *chan, enum ast_control_frame_type control)
1016 {
1017         struct ast_frame f = { AST_FRAME_CONTROL, };
1018
1019         f.subclass = control;
1020
1021         return ast_queue_frame(chan, &f);
1022 }
1023
1024 /*! \brief Queue a control frame with payload */
1025 int ast_queue_control_data(struct ast_channel *chan, enum ast_control_frame_type control,
1026                            const void *data, size_t datalen)
1027 {
1028         struct ast_frame f = { AST_FRAME_CONTROL, };
1029
1030         f.subclass = control;
1031         f.data = (void *) data;
1032         f.datalen = datalen;
1033
1034         return ast_queue_frame(chan, &f);
1035 }
1036
1037 /*! \brief Set defer DTMF flag on channel */
1038 int ast_channel_defer_dtmf(struct ast_channel *chan)
1039 {
1040         int pre = 0;
1041
1042         if (chan) {
1043                 pre = ast_test_flag(chan, AST_FLAG_DEFER_DTMF);
1044                 ast_set_flag(chan, AST_FLAG_DEFER_DTMF);
1045         }
1046         return pre;
1047 }
1048
1049 /*! \brief Unset defer DTMF flag on channel */
1050 void ast_channel_undefer_dtmf(struct ast_channel *chan)
1051 {
1052         if (chan)
1053                 ast_clear_flag(chan, AST_FLAG_DEFER_DTMF);
1054 }
1055
1056 /*!
1057  * \brief Helper function to find channels.
1058  *
1059  * It supports these modes:
1060  *
1061  * prev != NULL : get channel next in list after prev
1062  * name != NULL : get channel with matching name
1063  * name != NULL && namelen != 0 : get channel whose name starts with prefix
1064  * exten != NULL : get channel whose exten or macroexten matches
1065  * context != NULL && exten != NULL : get channel whose context or macrocontext
1066  *
1067  * It returns with the channel's lock held. If getting the individual lock fails,
1068  * unlock and retry quickly up to 10 times, then give up.
1069  *
1070  * \note XXX Note that this code has cost O(N) because of the need to verify
1071  * that the object is still on the global list.
1072  *
1073  * \note XXX also note that accessing fields (e.g. c->name in ast_log())
1074  * can only be done with the lock held or someone could delete the
1075  * object while we work on it. This causes some ugliness in the code.
1076  * Note that removing the first ast_log() may be harmful, as it would
1077  * shorten the retry period and possibly cause failures.
1078  * We should definitely go for a better scheme that is deadlock-free.
1079  */
1080 static struct ast_channel *channel_find_locked(const struct ast_channel *prev,
1081                                                const char *name, const int namelen,
1082                                                const char *context, const char *exten)
1083 {
1084         const char *msg = prev ? "deadlock" : "initial deadlock";
1085         int retries;
1086         struct ast_channel *c;
1087         const struct ast_channel *_prev = prev;
1088
1089         for (retries = 0; retries < 10; retries++) {
1090                 int done;
1091                 AST_RWLIST_RDLOCK(&channels);
1092                 AST_RWLIST_TRAVERSE(&channels, c, chan_list) {
1093                         prev = _prev;
1094                         if (prev) {     /* look for next item */
1095                                 if (c != prev)  /* not this one */
1096                                         continue;
1097                                 /* found, prepare to return c->next */
1098                                 if ((c = AST_RWLIST_NEXT(c, chan_list)) == NULL) break;
1099                                 /* If prev was the last item on the channel list, then we just
1100                                  * want to return NULL, instead of trying to deref NULL in the
1101                                  * next section.
1102                                  */
1103                                 prev = NULL;
1104                                 /* We want prev to be NULL in case we end up doing more searching through
1105                                  * the channel list to find the channel (ie: name searching). If we didn't
1106                                  * set this to NULL the logic would just blow up
1107                                  * XXX Need a better explanation for this ...
1108                                  */
1109                         }
1110                         if (name) { /* want match by name */
1111                                 if ((!namelen && strcasecmp(c->name, name) && strcmp(c->uniqueid, name)) ||
1112                                     (namelen && strncasecmp(c->name, name, namelen)))
1113                                         continue;       /* name match failed */
1114                         } else if (exten) {
1115                                 if (context && strcasecmp(c->context, context) &&
1116                                     strcasecmp(c->macrocontext, context))
1117                                         continue;       /* context match failed */
1118                                 if (strcasecmp(c->exten, exten) &&
1119                                     strcasecmp(c->macroexten, exten))
1120                                         continue;       /* exten match failed */
1121                         }
1122                         /* if we get here, c points to the desired record */
1123                         break;
1124                 }
1125                 /* exit if chan not found or mutex acquired successfully */
1126                 /* this is slightly unsafe, as we _should_ hold the lock to access c->name */
1127                 done = c == NULL || ast_channel_trylock(c) == 0;
1128                 if (!done) {
1129                         ast_debug(1, "Avoiding %s for channel '%p'\n", msg, c);
1130                         if (retries == 9) {
1131                                 /* We are about to fail due to a deadlock, so report this
1132                                  * while we still have the list lock.
1133                                  */
1134                                 ast_debug(1, "Failure, could not lock '%p' after %d retries!\n", c, retries);
1135                                 /* As we have deadlocked, we will skip this channel and
1136                                  * see if there is another match.
1137                                  * NOTE: No point doing this for a full-name match,
1138                                  * as there can be no more matches.
1139                                  */
1140                                 if (!(name && !namelen)) {
1141                                         prev = c;
1142                                         retries = -1;
1143                                 }
1144                         }
1145                 }
1146                 AST_RWLIST_UNLOCK(&channels);
1147                 if (done)
1148                         return c;
1149                 /* If we reach this point we basically tried to lock a channel and failed. Instead of
1150                  * starting from the beginning of the list we can restore our saved pointer to the previous
1151                  * channel and start from there.
1152                  */
1153                 prev = _prev;
1154                 usleep(1);      /* give other threads a chance before retrying */
1155         }
1156
1157         return NULL;
1158 }
1159
1160 /*! \brief Browse channels in use */
1161 struct ast_channel *ast_channel_walk_locked(const struct ast_channel *prev)
1162 {
1163         return channel_find_locked(prev, NULL, 0, NULL, NULL);
1164 }
1165
1166 /*! \brief Get channel by name and lock it */
1167 struct ast_channel *ast_get_channel_by_name_locked(const char *name)
1168 {
1169         return channel_find_locked(NULL, name, 0, NULL, NULL);
1170 }
1171
1172 /*! \brief Get channel by name prefix and lock it */
1173 struct ast_channel *ast_get_channel_by_name_prefix_locked(const char *name, const int namelen)
1174 {
1175         return channel_find_locked(NULL, name, namelen, NULL, NULL);
1176 }
1177
1178 /*! \brief Get next channel by name prefix and lock it */
1179 struct ast_channel *ast_walk_channel_by_name_prefix_locked(const struct ast_channel *chan, const char *name,
1180                                                            const int namelen)
1181 {
1182         return channel_find_locked(chan, name, namelen, NULL, NULL);
1183 }
1184
1185 /*! \brief Get channel by exten (and optionally context) and lock it */
1186 struct ast_channel *ast_get_channel_by_exten_locked(const char *exten, const char *context)
1187 {
1188         return channel_find_locked(NULL, NULL, 0, context, exten);
1189 }
1190
1191 /*! \brief Get next channel by exten (and optionally context) and lock it */
1192 struct ast_channel *ast_walk_channel_by_exten_locked(const struct ast_channel *chan, const char *exten,
1193                                                      const char *context)
1194 {
1195         return channel_find_locked(chan, NULL, 0, context, exten);
1196 }
1197
1198 /*! \brief Wait, look for hangups and condition arg */
1199 int ast_safe_sleep_conditional(struct ast_channel *chan, int ms, int (*cond)(void*), void *data)
1200 {
1201         struct ast_frame *f;
1202
1203         while (ms > 0) {
1204                 if (cond && ((*cond)(data) == 0))
1205                         return 0;
1206                 ms = ast_waitfor(chan, ms);
1207                 if (ms < 0)
1208                         return -1;
1209                 if (ms > 0) {
1210                         f = ast_read(chan);
1211                         if (!f)
1212                                 return -1;
1213                         ast_frfree(f);
1214                 }
1215         }
1216         return 0;
1217 }
1218
1219 /*! \brief Wait, look for hangups */
1220 int ast_safe_sleep(struct ast_channel *chan, int ms)
1221 {
1222         return ast_safe_sleep_conditional(chan, ms, NULL, NULL);
1223 }
1224
1225 static void free_cid(struct ast_callerid *cid)
1226 {
1227         if (cid->cid_dnid)
1228                 ast_free(cid->cid_dnid);
1229         if (cid->cid_num)
1230                 ast_free(cid->cid_num); 
1231         if (cid->cid_name)
1232                 ast_free(cid->cid_name);        
1233         if (cid->cid_ani)
1234                 ast_free(cid->cid_ani);
1235         if (cid->cid_rdnis)
1236                 ast_free(cid->cid_rdnis);
1237         cid->cid_dnid = cid->cid_num = cid->cid_name = cid->cid_ani = cid->cid_rdnis = NULL;
1238 }
1239
1240 /*! \brief Free a channel structure */
1241 void ast_channel_free(struct ast_channel *chan)
1242 {
1243         int fd;
1244 #ifdef HAVE_EPOLL
1245         int i;
1246 #endif
1247         struct ast_var_t *vardata;
1248         struct ast_frame *f;
1249         struct varshead *headp;
1250         struct ast_datastore *datastore = NULL;
1251         char name[AST_CHANNEL_NAME];
1252         
1253         headp=&chan->varshead;
1254         
1255         AST_RWLIST_WRLOCK(&channels);
1256         if (!AST_RWLIST_REMOVE(&channels, chan, chan_list)) {
1257                 AST_RWLIST_UNLOCK(&channels);
1258                 ast_log(LOG_ERROR, "Unable to find channel in list to free. Assuming it has already been done.\n");
1259         }
1260         /* Lock and unlock the channel just to be sure nobody has it locked still
1261            due to a reference retrieved from the channel list. */
1262         ast_channel_lock(chan);
1263         ast_channel_unlock(chan);
1264
1265         /* Get rid of each of the data stores on the channel */
1266         while ((datastore = AST_LIST_REMOVE_HEAD(&chan->datastores, entry)))
1267                 /* Free the data store */
1268                 ast_channel_datastore_free(datastore);
1269
1270         /* Lock and unlock the channel just to be sure nobody has it locked still
1271            due to a reference that was stored in a datastore. (i.e. app_chanspy) */
1272         ast_channel_lock(chan);
1273         ast_channel_unlock(chan);
1274
1275         if (chan->tech_pvt) {
1276                 ast_log(LOG_WARNING, "Channel '%s' may not have been hung up properly\n", chan->name);
1277                 ast_free(chan->tech_pvt);
1278         }
1279
1280         if (chan->sched)
1281                 sched_context_destroy(chan->sched);
1282
1283         ast_copy_string(name, chan->name, sizeof(name));
1284
1285         /* Stop monitoring */
1286         if (chan->monitor)
1287                 chan->monitor->stop( chan, 0 );
1288
1289         /* If there is native format music-on-hold state, free it */
1290         if (chan->music_state)
1291                 ast_moh_cleanup(chan);
1292
1293         /* Free translators */
1294         if (chan->readtrans)
1295                 ast_translator_free_path(chan->readtrans);
1296         if (chan->writetrans)
1297                 ast_translator_free_path(chan->writetrans);
1298         if (chan->pbx)
1299                 ast_log(LOG_WARNING, "PBX may not have been terminated properly on '%s'\n", chan->name);
1300         free_cid(&chan->cid);
1301         /* Close pipes if appropriate */
1302         if ((fd = chan->alertpipe[0]) > -1)
1303                 close(fd);
1304         if ((fd = chan->alertpipe[1]) > -1)
1305                 close(fd);
1306         if ((fd = chan->timingfd) > -1)
1307                 close(fd);
1308 #ifdef HAVE_EPOLL
1309         for (i = 0; i < AST_MAX_FDS; i++) {
1310                 if (chan->epfd_data[i])
1311                         free(chan->epfd_data[i]);
1312         }
1313         close(chan->epfd);
1314 #endif
1315         while ((f = AST_LIST_REMOVE_HEAD(&chan->readq, frame_list)))
1316                 ast_frfree(f);
1317         
1318         /* loop over the variables list, freeing all data and deleting list items */
1319         /* no need to lock the list, as the channel is already locked */
1320         
1321         while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
1322                 ast_var_delete(vardata);
1323
1324         ast_app_group_discard(chan);
1325
1326         /* Destroy the jitterbuffer */
1327         ast_jb_destroy(chan);
1328         
1329         ast_mutex_destroy(&chan->lock_dont_use);
1330
1331         ast_string_field_free_memory(chan);
1332         ast_free(chan);
1333         AST_RWLIST_UNLOCK(&channels);
1334
1335         ast_device_state_changed_literal(name);
1336 }
1337
1338 struct ast_datastore *ast_channel_datastore_alloc(const struct ast_datastore_info *info, const char *uid)
1339 {
1340         struct ast_datastore *datastore = NULL;
1341
1342         /* Make sure we at least have type so we can identify this */
1343         if (!info) {
1344                 return NULL;
1345         }
1346
1347         /* Allocate memory for datastore and clear it */
1348         datastore = ast_calloc(1, sizeof(*datastore));
1349         if (!datastore) {
1350                 return NULL;
1351         }
1352
1353         datastore->info = info;
1354
1355         datastore->uid = ast_strdup(uid);
1356
1357         return datastore;
1358 }
1359
1360 int ast_channel_datastore_free(struct ast_datastore *datastore)
1361 {
1362         int res = 0;
1363
1364         /* Using the destroy function (if present) destroy the data */
1365         if (datastore->info->destroy != NULL && datastore->data != NULL) {
1366                 datastore->info->destroy(datastore->data);
1367                 datastore->data = NULL;
1368         }
1369
1370         /* Free allocated UID memory */
1371         if (datastore->uid != NULL) {
1372                 ast_free((void *) datastore->uid);
1373                 datastore->uid = NULL;
1374         }
1375
1376         /* Finally free memory used by ourselves */
1377         ast_free(datastore);
1378
1379         return res;
1380 }
1381
1382 int ast_channel_datastore_inherit(struct ast_channel *from, struct ast_channel *to)
1383 {
1384         struct ast_datastore *datastore = NULL, *datastore2;
1385
1386         AST_LIST_TRAVERSE(&from->datastores, datastore, entry) {
1387                 if (datastore->inheritance > 0) {
1388                         datastore2 = ast_channel_datastore_alloc(datastore->info, datastore->uid);
1389                         if (datastore2) {
1390                                 datastore2->data = datastore->info->duplicate(datastore->data);
1391                                 datastore2->inheritance = datastore->inheritance == DATASTORE_INHERIT_FOREVER ? DATASTORE_INHERIT_FOREVER : datastore->inheritance - 1;
1392                                 AST_LIST_INSERT_TAIL(&to->datastores, datastore2, entry);
1393                         }
1394                 }
1395         }
1396         return 0;
1397 }
1398
1399 int ast_channel_datastore_add(struct ast_channel *chan, struct ast_datastore *datastore)
1400 {
1401         int res = 0;
1402
1403         AST_LIST_INSERT_HEAD(&chan->datastores, datastore, entry);
1404
1405         return res;
1406 }
1407
1408 int ast_channel_datastore_remove(struct ast_channel *chan, struct ast_datastore *datastore)
1409 {
1410         return AST_LIST_REMOVE(&chan->datastores, datastore, entry) ? 0 : -1;
1411 }
1412
1413 struct ast_datastore *ast_channel_datastore_find(struct ast_channel *chan, const struct ast_datastore_info *info, const char *uid)
1414 {
1415         struct ast_datastore *datastore = NULL;
1416         
1417         if (info == NULL)
1418                 return NULL;
1419
1420         AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->datastores, datastore, entry) {
1421                 if (datastore->info == info) {
1422                         if (uid != NULL && datastore->uid != NULL) {
1423                                 if (!strcasecmp(uid, datastore->uid)) {
1424                                         /* Matched by type AND uid */
1425                                         break;
1426                                 }
1427                         } else {
1428                                 /* Matched by type at least */
1429                                 break;
1430                         }
1431                 }
1432         }
1433         AST_LIST_TRAVERSE_SAFE_END
1434
1435         return datastore;
1436 }
1437
1438 /*! Set the file descriptor on the channel */
1439 void ast_channel_set_fd(struct ast_channel *chan, int which, int fd)
1440 {
1441 #ifdef HAVE_EPOLL
1442         struct epoll_event ev;
1443         struct ast_epoll_data *aed = NULL;
1444
1445         if (chan->fds[which] > -1) {
1446                 epoll_ctl(chan->epfd, EPOLL_CTL_DEL, chan->fds[which], &ev);
1447                 aed = chan->epfd_data[which];
1448         }
1449
1450         /* If this new fd is valid, add it to the epoll */
1451         if (fd > -1) {
1452                 if (!aed && (!(aed = ast_calloc(1, sizeof(*aed)))))
1453                         return;
1454                 
1455                 chan->epfd_data[which] = aed;
1456                 aed->chan = chan;
1457                 aed->which = which;
1458                 
1459                 ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
1460                 ev.data.ptr = aed;
1461                 epoll_ctl(chan->epfd, EPOLL_CTL_ADD, fd, &ev);
1462         } else if (aed) {
1463                 /* We don't have to keep around this epoll data structure now */
1464                 free(aed);
1465                 chan->epfd_data[which] = NULL;
1466         }
1467 #endif
1468         chan->fds[which] = fd;
1469         return;
1470 }
1471
1472 /*! Add a channel to an optimized waitfor */
1473 void ast_poll_channel_add(struct ast_channel *chan0, struct ast_channel *chan1)
1474 {
1475 #ifdef HAVE_EPOLL
1476         struct epoll_event ev;
1477         int i = 0;
1478
1479         if (chan0->epfd == -1)
1480                 return;
1481
1482         /* Iterate through the file descriptors on chan1, adding them to chan0 */
1483         for (i = 0; i < AST_MAX_FDS; i++) {
1484                 if (chan1->fds[i] == -1)
1485                         continue;
1486                 ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
1487                 ev.data.ptr = chan1->epfd_data[i];
1488                 epoll_ctl(chan0->epfd, EPOLL_CTL_ADD, chan1->fds[i], &ev);
1489         }
1490
1491 #endif
1492         return;
1493 }
1494
1495 /*! Delete a channel from an optimized waitfor */
1496 void ast_poll_channel_del(struct ast_channel *chan0, struct ast_channel *chan1)
1497 {
1498 #ifdef HAVE_EPOLL
1499         struct epoll_event ev;
1500         int i = 0;
1501
1502         if (chan0->epfd == -1)
1503                 return;
1504
1505         for (i = 0; i < AST_MAX_FDS; i++) {
1506                 if (chan1->fds[i] == -1)
1507                         continue;
1508                 epoll_ctl(chan0->epfd, EPOLL_CTL_DEL, chan1->fds[i], &ev);
1509         }
1510
1511 #endif
1512         return;
1513 }
1514
1515 /*! \brief Softly hangup a channel, don't lock */
1516 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
1517 {
1518         ast_debug(1, "Soft-Hanging up channel '%s'\n", chan->name);
1519         /* Inform channel driver that we need to be hung up, if it cares */
1520         chan->_softhangup |= cause;
1521         ast_queue_frame(chan, &ast_null_frame);
1522         /* Interrupt any poll call or such */
1523         if (ast_test_flag(chan, AST_FLAG_BLOCKING))
1524                 pthread_kill(chan->blocker, SIGURG);
1525         return 0;
1526 }
1527
1528 /*! \brief Softly hangup a channel, lock */
1529 int ast_softhangup(struct ast_channel *chan, int cause)
1530 {
1531         int res;
1532         ast_channel_lock(chan);
1533         res = ast_softhangup_nolock(chan, cause);
1534         ast_channel_unlock(chan);
1535         return res;
1536 }
1537
1538 static void free_translation(struct ast_channel *clone)
1539 {
1540         if (clone->writetrans)
1541                 ast_translator_free_path(clone->writetrans);
1542         if (clone->readtrans)
1543                 ast_translator_free_path(clone->readtrans);
1544         clone->writetrans = NULL;
1545         clone->readtrans = NULL;
1546         clone->rawwriteformat = clone->nativeformats;
1547         clone->rawreadformat = clone->nativeformats;
1548 }
1549
1550 /*! \brief Hangup a channel */
1551 int ast_hangup(struct ast_channel *chan)
1552 {
1553         int res = 0;
1554         struct ast_cdr *cdr = NULL;
1555
1556         /* Don't actually hang up a channel that will masquerade as someone else, or
1557            if someone is going to masquerade as us */
1558         ast_channel_lock(chan);
1559
1560         if (chan->audiohooks) {
1561                 ast_audiohook_detach_list(chan->audiohooks);
1562                 chan->audiohooks = NULL;
1563         }
1564
1565         ast_autoservice_stop(chan);
1566
1567         if (chan->masq) {
1568                 if (ast_do_masquerade(chan))
1569                         ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1570         }
1571
1572         if (chan->masq) {
1573                 ast_log(LOG_WARNING, "%s getting hung up, but someone is trying to masq into us?!?\n", chan->name);
1574                 ast_channel_unlock(chan);
1575                 return 0;
1576         }
1577         /* If this channel is one which will be masqueraded into something,
1578            mark it as a zombie already, so we know to free it later */
1579         if (chan->masqr) {
1580                 ast_set_flag(chan, AST_FLAG_ZOMBIE);
1581                 ast_channel_unlock(chan);
1582                 return 0;
1583         }
1584         free_translation(chan);
1585         /* Close audio stream */
1586         if (chan->stream) {
1587                 ast_closestream(chan->stream);
1588                 chan->stream = NULL;
1589         }
1590         /* Close video stream */
1591         if (chan->vstream) {
1592                 ast_closestream(chan->vstream);
1593                 chan->vstream = NULL;
1594         }
1595         if (chan->sched) {
1596                 sched_context_destroy(chan->sched);
1597                 chan->sched = NULL;
1598         }
1599         
1600         if (chan->generatordata)        /* Clear any tone stuff remaining */
1601                 if (chan->generator && chan->generator->release)
1602                         chan->generator->release(chan, chan->generatordata);
1603         chan->generatordata = NULL;
1604         chan->generator = NULL;
1605         if (chan->cdr) {                /* End the CDR if it hasn't already */
1606                 ast_cdr_end(chan->cdr);
1607                 cdr = chan->cdr;
1608                 chan->cdr = NULL;
1609         }
1610         if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
1611                 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
1612                                         "is blocked by thread %ld in procedure %s!  Expect a failure\n",
1613                                         (long)pthread_self(), chan->name, (long)chan->blocker, chan->blockproc);
1614                 CRASH;
1615         }
1616         if (!ast_test_flag(chan, AST_FLAG_ZOMBIE)) {
1617                 ast_debug(1, "Hanging up channel '%s'\n", chan->name);
1618                 if (chan->tech->hangup)
1619                         res = chan->tech->hangup(chan);
1620         } else {
1621                 ast_debug(1, "Hanging up zombie '%s'\n", chan->name);
1622         }
1623                         
1624         ast_channel_unlock(chan);
1625         manager_event(EVENT_FLAG_CALL, "Hangup",
1626                         "Channel: %s\r\n"
1627                         "Uniqueid: %s\r\n"
1628                         "CallerIDNum: %s\r\n"
1629                         "CallerIDName: %s\r\n"
1630                         "Cause: %d\r\n"
1631                         "Cause-txt: %s\r\n",
1632                         chan->name,
1633                         chan->uniqueid,
1634                         S_OR(chan->cid.cid_num, "<unknown>"),
1635                         S_OR(chan->cid.cid_name, "<unknown>"),
1636                         chan->hangupcause,
1637                         ast_cause2str(chan->hangupcause)
1638                         );
1639         ast_channel_free(chan);
1640
1641         if (cdr)
1642                 ast_cdr_detach(cdr);
1643
1644         return res;
1645 }
1646
1647 int __ast_answer(struct ast_channel *chan, unsigned int delay)
1648 {
1649         int res = 0;
1650
1651         ast_channel_lock(chan);
1652
1653         /* You can't answer an outbound call */
1654         if (ast_test_flag(chan, AST_FLAG_OUTGOING)) {
1655                 ast_channel_unlock(chan);
1656                 return 0;
1657         }
1658
1659         /* Stop if we're a zombie or need a soft hangup */
1660         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
1661                 ast_channel_unlock(chan);
1662                 return -1;
1663         }
1664
1665         switch (chan->_state) {
1666         case AST_STATE_RINGING:
1667         case AST_STATE_RING:
1668                 if (chan->tech->answer)
1669                         res = chan->tech->answer(chan);
1670                 ast_setstate(chan, AST_STATE_UP);
1671                 ast_cdr_answer(chan->cdr);
1672                 ast_channel_unlock(chan);
1673                 if (delay)
1674                         ast_safe_sleep(chan, delay);
1675                 return res;
1676                 break;
1677         case AST_STATE_UP:
1678                 ast_cdr_answer(chan->cdr);
1679                 break;
1680         default:
1681                 break;
1682         }
1683         chan->visible_indication = 0;
1684         ast_channel_unlock(chan);
1685
1686         return res;
1687 }
1688
1689 int ast_answer(struct ast_channel *chan)
1690 {
1691         return __ast_answer(chan, 500);
1692 }
1693
1694 void ast_deactivate_generator(struct ast_channel *chan)
1695 {
1696         ast_channel_lock(chan);
1697         if (chan->generatordata) {
1698                 if (chan->generator && chan->generator->release)
1699                         chan->generator->release(chan, chan->generatordata);
1700                 chan->generatordata = NULL;
1701                 chan->generator = NULL;
1702                 ast_channel_set_fd(chan, AST_GENERATOR_FD, -1);
1703                 ast_clear_flag(chan, AST_FLAG_WRITE_INT);
1704                 ast_settimeout(chan, 0, NULL, NULL);
1705         }
1706         ast_channel_unlock(chan);
1707 }
1708
1709 static int generator_force(const void *data)
1710 {
1711         /* Called if generator doesn't have data */
1712         void *tmp;
1713         int res;
1714         int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples) = NULL;
1715         struct ast_channel *chan = (struct ast_channel *)data;
1716
1717         ast_channel_lock(chan);
1718         tmp = chan->generatordata;
1719         chan->generatordata = NULL;
1720         if (chan->generator)
1721                 generate = chan->generator->generate;
1722         ast_channel_unlock(chan);
1723
1724         if (!tmp || !generate)
1725                 return 0;
1726
1727         res = generate(chan, tmp, 0, 160);
1728
1729         chan->generatordata = tmp;
1730
1731         if (res) {
1732                 ast_debug(1, "Auto-deactivating generator\n");
1733                 ast_deactivate_generator(chan);
1734         }
1735
1736         return 0;
1737 }
1738
1739 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
1740 {
1741         int res = 0;
1742
1743         ast_channel_lock(chan);
1744
1745         if (chan->generatordata) {
1746                 if (chan->generator && chan->generator->release)
1747                         chan->generator->release(chan, chan->generatordata);
1748                 chan->generatordata = NULL;
1749         }
1750
1751         ast_prod(chan);
1752         if (gen->alloc && !(chan->generatordata = gen->alloc(chan, params))) {
1753                 res = -1;
1754         }
1755         
1756         if (!res) {
1757                 ast_settimeout(chan, 160, generator_force, chan);
1758                 chan->generator = gen;
1759         }
1760
1761         ast_channel_unlock(chan);
1762
1763         return res;
1764 }
1765
1766 /*! \brief Wait for x amount of time on a file descriptor to have input.  */
1767 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
1768 {
1769         int winner = -1;
1770         ast_waitfor_nandfds(NULL, 0, fds, n, exception, &winner, ms);
1771         return winner;
1772 }
1773
1774 /*! \brief Wait for x amount of time on a file descriptor to have input.  */
1775 #ifdef HAVE_EPOLL
1776 static struct ast_channel *ast_waitfor_nandfds_classic(struct ast_channel **c, int n, int *fds, int nfds,
1777                                         int *exception, int *outfd, int *ms)
1778 #else
1779 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
1780                                         int *exception, int *outfd, int *ms)
1781 #endif
1782 {
1783         struct timeval start = { 0 , 0 };
1784         struct pollfd *pfds = NULL;
1785         int res;
1786         long rms;
1787         int x, y, max;
1788         int sz;
1789         time_t now = 0;
1790         long whentohangup = 0, diff;
1791         struct ast_channel *winner = NULL;
1792         struct fdmap {
1793                 int chan;
1794                 int fdno;
1795         } *fdmap = NULL;
1796
1797         if ((sz = n * AST_MAX_FDS + nfds)) {
1798                 pfds = alloca(sizeof(*pfds) * sz);
1799                 fdmap = alloca(sizeof(*fdmap) * sz);
1800         }
1801
1802         if (outfd)
1803                 *outfd = -99999;
1804         if (exception)
1805                 *exception = 0;
1806         
1807         /* Perform any pending masquerades */
1808         for (x = 0; x < n; x++) {
1809                 ast_channel_lock(c[x]);
1810                 if (c[x]->masq && ast_do_masquerade(c[x])) {
1811                         ast_log(LOG_WARNING, "Masquerade failed\n");
1812                         *ms = -1;
1813                         ast_channel_unlock(c[x]);
1814                         return NULL;
1815                 }
1816                 if (c[x]->whentohangup) {
1817                         if (!whentohangup)
1818                                 time(&now);
1819                         diff = c[x]->whentohangup - now;
1820                         if (diff < 1) {
1821                                 /* Should already be hungup */
1822                                 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1823                                 ast_channel_unlock(c[x]);
1824                                 return c[x];
1825                         }
1826                         if (!whentohangup || (diff < whentohangup))
1827                                 whentohangup = diff;
1828                 }
1829                 ast_channel_unlock(c[x]);
1830         }
1831         /* Wait full interval */
1832         rms = *ms;
1833         if (whentohangup) {
1834                 rms = whentohangup * 1000;              /* timeout in milliseconds */
1835                 if (*ms >= 0 && *ms < rms)              /* original *ms still smaller */
1836                         rms =  *ms;
1837         }
1838         /*
1839          * Build the pollfd array, putting the channels' fds first,
1840          * followed by individual fds. Order is important because
1841          * individual fd's must have priority over channel fds.
1842          */
1843         max = 0;
1844         for (x = 0; x < n; x++) {
1845                 for (y = 0; y < AST_MAX_FDS; y++) {
1846                         fdmap[max].fdno = y;  /* fd y is linked to this pfds */
1847                         fdmap[max].chan = x;  /* channel x is linked to this pfds */
1848                         max += ast_add_fd(&pfds[max], c[x]->fds[y]);
1849                 }
1850                 CHECK_BLOCKING(c[x]);
1851         }
1852         /* Add the individual fds */
1853         for (x = 0; x < nfds; x++) {
1854                 fdmap[max].chan = -1;
1855                 max += ast_add_fd(&pfds[max], fds[x]);
1856         }
1857
1858         if (*ms > 0)
1859                 start = ast_tvnow();
1860         
1861         if (sizeof(int) == 4) { /* XXX fix timeout > 600000 on linux x86-32 */
1862                 do {
1863                         int kbrms = rms;
1864                         if (kbrms > 600000)
1865                                 kbrms = 600000;
1866                         res = poll(pfds, max, kbrms);
1867                         if (!res)
1868                                 rms -= kbrms;
1869                 } while (!res && (rms > 0));
1870         } else {
1871                 res = poll(pfds, max, rms);
1872         }
1873         for (x = 0; x < n; x++)
1874                 ast_clear_flag(c[x], AST_FLAG_BLOCKING);
1875         if (res < 0) { /* Simulate a timeout if we were interrupted */
1876                 if (errno != EINTR)
1877                         *ms = -1;
1878                 return NULL;
1879         }
1880         if (whentohangup) {   /* if we have a timeout, check who expired */
1881                 time(&now);
1882                 for (x = 0; x < n; x++) {
1883                         if (c[x]->whentohangup && now >= c[x]->whentohangup) {
1884                                 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1885                                 if (winner == NULL)
1886                                         winner = c[x];
1887                         }
1888                 }
1889         }
1890         if (res == 0) { /* no fd ready, reset timeout and done */
1891                 *ms = 0;        /* XXX use 0 since we may not have an exact timeout. */
1892                 return winner;
1893         }
1894         /*
1895          * Then check if any channel or fd has a pending event.
1896          * Remember to check channels first and fds last, as they
1897          * must have priority on setting 'winner'
1898          */
1899         for (x = 0; x < max; x++) {
1900                 res = pfds[x].revents;
1901                 if (res == 0)
1902                         continue;
1903                 if (fdmap[x].chan >= 0) {       /* this is a channel */
1904                         winner = c[fdmap[x].chan];      /* override previous winners */
1905                         if (res & POLLPRI)
1906                                 ast_set_flag(winner, AST_FLAG_EXCEPTION);
1907                         else
1908                                 ast_clear_flag(winner, AST_FLAG_EXCEPTION);
1909                         winner->fdno = fdmap[x].fdno;
1910                 } else {                        /* this is an fd */
1911                         if (outfd)
1912                                 *outfd = pfds[x].fd;
1913                         if (exception)
1914                                 *exception = (res & POLLPRI) ? -1 : 0;
1915                         winner = NULL;
1916                 }
1917         }
1918         if (*ms > 0) {
1919                 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
1920                 if (*ms < 0)
1921                         *ms = 0;
1922         }
1923         return winner;
1924 }
1925
1926 #ifdef HAVE_EPOLL
1927 static struct ast_channel *ast_waitfor_nandfds_simple(struct ast_channel *chan, int *ms)
1928 {
1929         struct timeval start = { 0 , 0 };
1930         int res = 0;
1931         struct epoll_event ev[1];
1932         long whentohangup = 0, rms = *ms;
1933         time_t now;
1934         struct ast_channel *winner = NULL;
1935         struct ast_epoll_data *aed = NULL;
1936
1937         ast_channel_lock(chan);
1938
1939         /* See if this channel needs to be masqueraded */
1940         if (chan->masq && ast_do_masquerade(chan)) {
1941                 ast_log(LOG_WARNING, "Failed to perform masquerade on %s\n", chan->name);
1942                 *ms = -1;
1943                 ast_channel_unlock(chan);
1944                 return NULL;
1945         }
1946
1947         /* Figure out their timeout */
1948         if (chan->whentohangup) {
1949                 time(&now);
1950                 if ((whentohangup = chan->whentohangup - now) < 1) {
1951                         /* They should already be hungup! */
1952                         chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1953                         ast_channel_unlock(chan);
1954                         return NULL;
1955                 }
1956                 /* If this value is smaller then the current one... make it priority */
1957                 whentohangup *= 1000;
1958                 if (rms > whentohangup)
1959                         rms = whentohangup;
1960         }
1961
1962         ast_channel_unlock(chan);
1963
1964         /* Time to make this channel block... */
1965         CHECK_BLOCKING(chan);
1966
1967         if (*ms > 0)
1968                 start = ast_tvnow();
1969
1970         /* We don't have to add any file descriptors... they are already added, we just have to wait! */
1971         res = epoll_wait(chan->epfd, ev, 1, rms);
1972
1973         /* Stop blocking */
1974         ast_clear_flag(chan, AST_FLAG_BLOCKING);
1975
1976         /* Simulate a timeout if we were interrupted */
1977         if (res < 0) {
1978                 if (errno != EINTR)
1979                         *ms = -1;
1980                 return NULL;
1981         }
1982
1983         /* If this channel has a timeout see if it expired */
1984         if (chan->whentohangup) {
1985                 time(&now);
1986                 if (now >= chan->whentohangup) {
1987                         chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1988                         winner = chan;
1989                 }
1990         }
1991
1992         /* No fd ready, reset timeout and be done for now */
1993         if (!res) {
1994                 *ms = 0;
1995                 return winner;
1996         }
1997
1998         /* See what events are pending */
1999         aed = ev[0].data.ptr;
2000         chan->fdno = aed->which;
2001         if (ev[0].events & EPOLLPRI)
2002                 ast_set_flag(chan, AST_FLAG_EXCEPTION);
2003         else
2004                 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
2005
2006         if (*ms > 0) {
2007                 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
2008                 if (*ms < 0)
2009                         *ms = 0;
2010         }
2011
2012         return chan;
2013 }
2014
2015 static struct ast_channel *ast_waitfor_nandfds_complex(struct ast_channel **c, int n, int *ms)
2016 {
2017         struct timeval start = { 0 , 0 };
2018         int res = 0, i;
2019         struct epoll_event ev[25] = { { 0, } };
2020         long whentohangup = 0, diff, rms = *ms;
2021         time_t now;
2022         struct ast_channel *winner = NULL;
2023
2024         for (i = 0; i < n; i++) {
2025                 ast_channel_lock(c[i]);
2026                 if (c[i]->masq && ast_do_masquerade(c[i])) {
2027                         ast_log(LOG_WARNING, "Masquerade failed\n");
2028                         *ms = -1;
2029                         ast_channel_unlock(c[i]);
2030                         return NULL;
2031                 }
2032                 if (c[i]->whentohangup) {
2033                         if (!whentohangup)
2034                                 time(&now);
2035                         if ((diff = c[i]->whentohangup - now) < 1) {
2036                                 c[i]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
2037                                 ast_channel_unlock(c[i]);
2038                                 return c[i];
2039                         }
2040                         if (!whentohangup || (diff < whentohangup))
2041                                 whentohangup = diff;
2042                 }
2043                 ast_channel_unlock(c[i]);
2044                 CHECK_BLOCKING(c[i]);
2045         }
2046
2047         rms = *ms;
2048         if (whentohangup) {
2049                 rms = whentohangup * 1000;
2050                 if (*ms >= 0 && *ms < rms)
2051                         rms = *ms;
2052         }
2053
2054         if (*ms > 0)
2055                 start = ast_tvnow();
2056
2057         res = epoll_wait(c[0]->epfd, ev, 25, rms);
2058
2059         for (i = 0; i < n; i++)
2060                 ast_clear_flag(c[i], AST_FLAG_BLOCKING);
2061
2062         if (res < 0) {
2063                 if (errno != EINTR)
2064                         *ms = -1;
2065                 return NULL;
2066         }
2067
2068         if (whentohangup) {
2069                 time(&now);
2070                 for (i = 0; i < n; i++) {
2071                         if (c[i]->whentohangup && now >= c[i]->whentohangup) {
2072                                 c[i]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
2073                                 if (!winner)
2074                                         winner = c[i];
2075                         }
2076                 }
2077         }
2078
2079         if (!res) {
2080                 *ms = 0;
2081                 return winner;
2082         }
2083
2084         for (i = 0; i < res; i++) {
2085                 struct ast_epoll_data *aed = ev[i].data.ptr;
2086
2087                 if (!ev[i].events || !aed)
2088                         continue;
2089
2090                 winner = aed->chan;
2091                 if (ev[i].events & EPOLLPRI)
2092                         ast_set_flag(winner, AST_FLAG_EXCEPTION);
2093                 else
2094                         ast_clear_flag(winner, AST_FLAG_EXCEPTION);
2095                 winner->fdno = aed->which;
2096         }
2097
2098         if (*ms > 0) {
2099                 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
2100                 if (*ms < 0)
2101                         *ms = 0;
2102         }
2103
2104         return winner;
2105 }
2106
2107 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
2108                                         int *exception, int *outfd, int *ms)
2109 {
2110         /* Clear all provided values in one place. */
2111         if (outfd)
2112                 *outfd = -99999;
2113         if (exception)
2114                 *exception = 0;
2115
2116         /* If no epoll file descriptor is available resort to classic nandfds */
2117         if (!n || nfds || c[0]->epfd == -1)
2118                 return ast_waitfor_nandfds_classic(c, n, fds, nfds, exception, outfd, ms);
2119         else if (!nfds && n == 1)
2120                 return ast_waitfor_nandfds_simple(c[0], ms);
2121         else
2122                 return ast_waitfor_nandfds_complex(c, n, ms);
2123 }
2124 #endif
2125
2126 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
2127 {
2128         return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
2129 }
2130
2131 int ast_waitfor(struct ast_channel *c, int ms)
2132 {
2133         int oldms = ms; /* -1 if no timeout */
2134
2135         ast_waitfor_nandfds(&c, 1, NULL, 0, NULL, NULL, &ms);
2136         if ((ms < 0) && (oldms < 0))
2137                 ms = 0;
2138         return ms;
2139 }
2140
2141 /* XXX never to be called with ms = -1 */
2142 int ast_waitfordigit(struct ast_channel *c, int ms)
2143 {
2144         return ast_waitfordigit_full(c, ms, -1, -1);
2145 }
2146
2147 int ast_settimeout(struct ast_channel *c, int samples, int (*func)(const void *data), void *data)
2148 {
2149         int res = -1;
2150 #ifdef HAVE_ZAPTEL
2151         if (c->timingfd > -1) {
2152                 if (!func) {
2153                         samples = 0;
2154                         data = 0;
2155                 }
2156                 ast_debug(1, "Scheduling timer at %d sample intervals\n", samples);
2157                 res = ioctl(c->timingfd, ZT_TIMERCONFIG, &samples);
2158                 c->timingfunc = func;
2159                 c->timingdata = data;
2160         }
2161 #endif  
2162         return res;
2163 }
2164
2165 int ast_waitfordigit_full(struct ast_channel *c, int ms, int audiofd, int cmdfd)
2166 {
2167         /* Stop if we're a zombie or need a soft hangup */
2168         if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
2169                 return -1;
2170
2171         /* Only look for the end of DTMF, don't bother with the beginning and don't emulate things */
2172         ast_set_flag(c, AST_FLAG_END_DTMF_ONLY);
2173
2174         /* Wait for a digit, no more than ms milliseconds total. */
2175         
2176         while (ms) {
2177                 struct ast_channel *rchan;
2178                 int outfd=-1;
2179
2180                 errno = 0;
2181                 rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
2182                 
2183                 if (!rchan && outfd < 0 && ms) {
2184                         if (errno == 0 || errno == EINTR)
2185                                 continue;
2186                         ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
2187                         ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2188                         return -1;
2189                 } else if (outfd > -1) {
2190                         /* The FD we were watching has something waiting */
2191                         ast_log(LOG_WARNING, "The FD we were waiting for has something waiting. Waitfordigit returning numeric 1\n");
2192                         ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2193                         return 1;
2194                 } else if (rchan) {
2195                         int res;
2196                         struct ast_frame *f = ast_read(c);
2197                         if (!f)
2198                                 return -1;
2199
2200                         switch (f->frametype) {
2201                         case AST_FRAME_DTMF_BEGIN:
2202                                 break;
2203                         case AST_FRAME_DTMF_END:
2204                                 res = f->subclass;
2205                                 ast_frfree(f);
2206                                 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2207                                 return res;
2208                         case AST_FRAME_CONTROL:
2209                                 switch (f->subclass) {
2210                                 case AST_CONTROL_HANGUP:
2211                                         ast_frfree(f);
2212                                         ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2213                                         return -1;
2214                                 case AST_CONTROL_RINGING:
2215                                 case AST_CONTROL_ANSWER:
2216                                 case AST_CONTROL_SRCUPDATE:
2217                                         /* Unimportant */
2218                                         break;
2219                                 default:
2220                                         ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", f->subclass);
2221                                         break;
2222                                 }
2223                                 break;
2224                         case AST_FRAME_VOICE:
2225                                 /* Write audio if appropriate */
2226                                 if (audiofd > -1)
2227                                         write(audiofd, f->data, f->datalen);
2228                         default:
2229                                 /* Ignore */
2230                                 break;
2231                         }
2232                         ast_frfree(f);
2233                 }
2234         }
2235
2236         ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2237
2238         return 0; /* Time is up */
2239 }
2240
2241 static void send_dtmf_event(const struct ast_channel *chan, const char *direction, const char digit, const char *begin, const char *end)
2242 {
2243         manager_event(EVENT_FLAG_DTMF,
2244                         "DTMF",
2245                         "Channel: %s\r\n"
2246                         "Uniqueid: %s\r\n"
2247                         "Digit: %c\r\n"
2248                         "Direction: %s\r\n"
2249                         "Begin: %s\r\n"
2250                         "End: %s\r\n",
2251                         chan->name, chan->uniqueid, digit, direction, begin, end);
2252 }
2253
2254 static void ast_read_generator_actions(struct ast_channel *chan, struct ast_frame *f)
2255 {
2256         if (chan->generatordata &&  !ast_internal_timing_enabled(chan)) {
2257                 void *tmp = chan->generatordata;
2258                 int res;
2259
2260                 if (chan->timingfunc) {
2261                         if (option_debug > 1)
2262                                 ast_log(LOG_DEBUG, "Generator got voice, switching to phase locked mode\n");
2263                         ast_settimeout(chan, 0, NULL, NULL);
2264                 }
2265
2266                 chan->generatordata = NULL;     /* reset, to let writes go through */
2267                 res = chan->generator->generate(chan, tmp, f->datalen, f->samples);
2268                 chan->generatordata = tmp;
2269                 if (res) {
2270                         if (option_debug > 1)
2271                                 ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
2272                         ast_deactivate_generator(chan);
2273                 }
2274
2275         } else if (f->frametype == AST_FRAME_CNG) {
2276                 if (chan->generator && !chan->timingfunc && (chan->timingfd > -1)) {
2277                         if (option_debug > 1)
2278                                 ast_log(LOG_DEBUG, "Generator got CNG, switching to timed mode\n");
2279                         ast_settimeout(chan, 160, generator_force, chan);
2280                 }
2281         }
2282 }
2283
2284 static struct ast_frame *__ast_read(struct ast_channel *chan, int dropaudio)
2285 {
2286         struct ast_frame *f = NULL;     /* the return value */
2287         int blah;
2288         int prestate;
2289         int count = 0;
2290
2291         /* this function is very long so make sure there is only one return
2292          * point at the end (there are only two exceptions to this).
2293          */
2294         while(ast_channel_trylock(chan)) {
2295                 if(count++ > 10) 
2296                         /*cannot goto done since the channel is not locked*/
2297                         return &ast_null_frame;
2298                 usleep(1);
2299         }
2300
2301         if (chan->masq) {
2302                 if (ast_do_masquerade(chan))
2303                         ast_log(LOG_WARNING, "Failed to perform masquerade\n");
2304                 else
2305                         f =  &ast_null_frame;
2306                 goto done;
2307         }
2308
2309         /* Stop if we're a zombie or need a soft hangup */
2310         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2311                 if (chan->generator)
2312                         ast_deactivate_generator(chan);
2313                 goto done;
2314         }
2315         prestate = chan->_state;
2316
2317         if (!ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_EMULATE_DTMF | AST_FLAG_IN_DTMF) && 
2318             !ast_strlen_zero(chan->dtmfq) && 
2319                 (ast_tvzero(chan->dtmf_tv) || ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) > AST_MIN_DTMF_GAP) ) {
2320                 /* We have DTMF that has been deferred.  Return it now */
2321                 chan->dtmff.subclass = chan->dtmfq[0];
2322                 /* Drop first digit from the buffer */
2323                 memmove(chan->dtmfq, chan->dtmfq + 1, sizeof(chan->dtmfq) - 1);
2324                 f = &chan->dtmff;
2325                 if (ast_test_flag(chan, AST_FLAG_END_DTMF_ONLY)) {
2326                         ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass, chan->name);
2327                         chan->dtmff.frametype = AST_FRAME_DTMF_END;
2328                 } else {
2329                         ast_log(LOG_DTMF, "DTMF begin emulation of '%c' with duration %d queued on %s\n", f->subclass, AST_DEFAULT_EMULATE_DTMF_DURATION, chan->name);
2330                         chan->dtmff.frametype = AST_FRAME_DTMF_BEGIN;
2331                         ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
2332                         chan->emulate_dtmf_digit = f->subclass;
2333                         chan->emulate_dtmf_duration = AST_DEFAULT_EMULATE_DTMF_DURATION;
2334                 }
2335                 chan->dtmf_tv = ast_tvnow();
2336                 goto done;
2337         }
2338         
2339         /* Read and ignore anything on the alertpipe, but read only
2340            one sizeof(blah) per frame that we send from it */
2341         if (chan->alertpipe[0] > -1)
2342                 read(chan->alertpipe[0], &blah, sizeof(blah));
2343
2344 #ifdef HAVE_ZAPTEL
2345         if (chan->timingfd > -1 && chan->fdno == AST_TIMING_FD && ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
2346                 int res;
2347
2348                 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
2349                 blah = -1;
2350                 /* IF we can't get event, assume it's an expired as-per the old interface */
2351                 res = ioctl(chan->timingfd, ZT_GETEVENT, &blah);
2352                 if (res)
2353                         blah = ZT_EVENT_TIMER_EXPIRED;
2354
2355                 if (blah == ZT_EVENT_TIMER_PING) {
2356                         if (AST_LIST_EMPTY(&chan->readq) || !AST_LIST_NEXT(AST_LIST_FIRST(&chan->readq), frame_list)) {
2357                                 /* Acknowledge PONG unless we need it again */
2358                                 if (ioctl(chan->timingfd, ZT_TIMERPONG, &blah)) {
2359                                         ast_log(LOG_WARNING, "Failed to pong timer on '%s': %s\n", chan->name, strerror(errno));
2360                                 }
2361                         }
2362                 } else if (blah == ZT_EVENT_TIMER_EXPIRED) {
2363                         ioctl(chan->timingfd, ZT_TIMERACK, &blah);
2364                         if (chan->timingfunc) {
2365                                 /* save a copy of func/data before unlocking the channel */
2366                                 int (*func)(const void *) = chan->timingfunc;
2367                                 void *data = chan->timingdata;
2368                                 ast_channel_unlock(chan);
2369                                 func(data);
2370                         } else {
2371                                 blah = 0;
2372                                 ioctl(chan->timingfd, ZT_TIMERCONFIG, &blah);
2373                                 chan->timingdata = NULL;
2374                                 ast_channel_unlock(chan);
2375                         }
2376                         /* cannot 'goto done' because the channel is already unlocked */
2377                         return &ast_null_frame;
2378                 } else
2379                         ast_log(LOG_NOTICE, "No/unknown event '%d' on timer for '%s'?\n", blah, chan->name);
2380         } else
2381 #endif
2382         if (chan->fds[AST_GENERATOR_FD] > -1 && chan->fdno == AST_GENERATOR_FD) {
2383                 /* if the AST_GENERATOR_FD is set, call the generator with args
2384                  * set to -1 so it can do whatever it needs to.
2385                  */
2386                 void *tmp = chan->generatordata;
2387                 chan->generatordata = NULL;     /* reset to let ast_write get through */
2388                 chan->generator->generate(chan, tmp, -1, -1);
2389                 chan->generatordata = tmp;
2390                 f = &ast_null_frame;
2391                 goto done;
2392         }
2393
2394         /* Check for pending read queue */
2395         if (!AST_LIST_EMPTY(&chan->readq)) {
2396                 f = AST_LIST_REMOVE_HEAD(&chan->readq, frame_list);
2397                 /* Interpret hangup and return NULL */
2398                 /* XXX why not the same for frames from the channel ? */
2399                 if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP) {
2400                         ast_frfree(f);
2401                         f = NULL;
2402                 }
2403         } else {
2404                 chan->blocker = pthread_self();
2405                 if (ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
2406                         if (chan->tech->exception)
2407                                 f = chan->tech->exception(chan);
2408                         else {
2409                                 ast_log(LOG_WARNING, "Exception flag set on '%s', but no exception handler\n", chan->name);
2410                                 f = &ast_null_frame;
2411                         }
2412                         /* Clear the exception flag */
2413                         ast_clear_flag(chan, AST_FLAG_EXCEPTION);
2414                 } else if (chan->tech->read)
2415                         f = chan->tech->read(chan);
2416                 else
2417                         ast_log(LOG_WARNING, "No read routine on channel %s\n", chan->name);
2418         }
2419
2420         if (f) {
2421                 /* if the channel driver returned more than one frame, stuff the excess
2422                    into the readq for the next ast_read call (note that we can safely assume
2423                    that the readq is empty, because otherwise we would not have called into
2424                    the channel driver and f would be only a single frame)
2425                 */
2426                 if (AST_LIST_NEXT(f, frame_list)) {
2427                         AST_LIST_HEAD_SET_NOLOCK(&chan->readq, AST_LIST_NEXT(f, frame_list));
2428                         AST_LIST_NEXT(f, frame_list) = NULL;
2429                 }
2430
2431                 switch (f->frametype) {
2432                 case AST_FRAME_CONTROL:
2433                         if (f->subclass == AST_CONTROL_ANSWER) {
2434                                 if (!ast_test_flag(chan, AST_FLAG_OUTGOING)) {
2435                                         ast_debug(1, "Ignoring answer on an inbound call!\n");
2436                                         ast_frfree(f);
2437                                         f = &ast_null_frame;
2438                                 } else if (prestate == AST_STATE_UP) {
2439                                         ast_debug(1, "Dropping duplicate answer!\n");
2440                                         ast_frfree(f);
2441                                         f = &ast_null_frame;
2442                                 } else {
2443                                         /* Answer the CDR */
2444                                         ast_setstate(chan, AST_STATE_UP);
2445                                         if (!chan->cdr) { /* up till now, this insertion hasn't been done. Therefore,
2446                                                                                  to keep from throwing off the basic order of the universe,
2447                                                                                  we will try to keep this cdr from getting posted. */
2448                                                 chan->cdr = ast_cdr_alloc();
2449                                                 ast_cdr_init(chan->cdr, chan);
2450                                                 ast_cdr_start(chan->cdr);
2451                                         }
2452                                         
2453                                         ast_cdr_answer(chan->cdr);
2454                                 }
2455                         }
2456                         break;
2457                 case AST_FRAME_DTMF_END:
2458                         send_dtmf_event(chan, "Received", f->subclass, "No", "Yes");
2459                         ast_log(LOG_DTMF, "DTMF end '%c' received on %s, duration %ld ms\n", f->subclass, chan->name, f->len);
2460                         /* Queue it up if DTMF is deffered, or if DTMF emulation is forced.
2461                          * However, only let emulation be forced if the other end cares about BEGIN frames */
2462                         if ( ast_test_flag(chan, AST_FLAG_DEFER_DTMF) ||
2463                                 (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !ast_test_flag(chan, AST_FLAG_END_DTMF_ONLY)) ) {
2464                                 if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2) {
2465                                         ast_log(LOG_DTMF, "DTMF end '%c' put into dtmf queue on %s\n", f->subclass, chan->name);
2466                                         chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
2467                                 } else
2468                                         ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
2469                                 ast_frfree(f);
2470                                 f = &ast_null_frame;
2471                         } else if (!ast_test_flag(chan, AST_FLAG_IN_DTMF | AST_FLAG_END_DTMF_ONLY)) {
2472                                 if (!ast_tvzero(chan->dtmf_tv) && 
2473                                     ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) < AST_MIN_DTMF_GAP) {
2474                                         /* If it hasn't been long enough, defer this digit */
2475                                         if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2) {
2476                                                 ast_log(LOG_DTMF, "DTMF end '%c' put into dtmf queue on %s\n", f->subclass, chan->name);
2477                                                 chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
2478                                         } else
2479                                                 ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
2480                                         ast_frfree(f);
2481                                         f = &ast_null_frame;
2482                                 } else {
2483                                         /* There was no begin, turn this into a begin and send the end later */
2484                                         f->frametype = AST_FRAME_DTMF_BEGIN;
2485                                         ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
2486                                         chan->emulate_dtmf_digit = f->subclass;
2487                                         chan->dtmf_tv = ast_tvnow();
2488                                         if (f->len) {
2489                                                 if (f->len > AST_MIN_DTMF_DURATION)
2490                                                         chan->emulate_dtmf_duration = f->len;
2491                                                 else 
2492                                                         chan->emulate_dtmf_duration = AST_MIN_DTMF_DURATION;
2493                                         } else
2494                                                 chan->emulate_dtmf_duration = AST_DEFAULT_EMULATE_DTMF_DURATION;
2495                                         ast_log(LOG_DTMF, "DTMF begin emulation of '%c' with duration %u queued on %s\n", f->subclass, chan->emulate_dtmf_duration, chan->name);
2496                                 }
2497                                 if (chan->audiohooks) {
2498                                         struct ast_frame *old_frame = f;
2499                                         /*!
2500                                          * \todo XXX It is possible to write a digit to the audiohook twice
2501                                          * if the digit was originally read while the channel was in autoservice. */
2502                                         f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
2503                                         if (old_frame != f)
2504                                                 ast_frfree(old_frame);
2505                                 }
2506                         } else {
2507                                 struct timeval now = ast_tvnow();
2508                                 if (ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
2509                                         ast_log(LOG_DTMF, "DTMF end accepted with begin '%c' on %s\n", f->subclass, chan->name);
2510                                         ast_clear_flag(chan, AST_FLAG_IN_DTMF);
2511                                         if (!f->len)
2512                                                 f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
2513                                 } else if (!f->len) {
2514                                         ast_log(LOG_DTMF, "DTMF end accepted without begin '%c' on %s\n", f->subclass, chan->name);
2515                                         f->len = AST_MIN_DTMF_DURATION;
2516                                 }
2517                                 if (f->len < AST_MIN_DTMF_DURATION) {
2518                                         ast_log(LOG_DTMF, "DTMF end '%c' has duration %ld but want minimum %d, emulating on %s\n", f->subclass, f->len, AST_MIN_DTMF_DURATION, chan->name);
2519                                         ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
2520                                         chan->emulate_dtmf_digit = f->subclass;
2521                                         chan->emulate_dtmf_duration = AST_MIN_DTMF_DURATION - f->len;
2522                                         ast_frfree(f);
2523                                         f = &ast_null_frame;
2524                                 } else {
2525                                         ast_log(LOG_DTMF, "DTMF end passthrough '%c' on %s\n", f->subclass, chan->name);
2526                                         chan->dtmf_tv = now;
2527                                 }
2528                                 if (chan->audiohooks) {
2529                                         struct ast_frame *old_frame = f;
2530                                         f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
2531                                         if (old_frame != f)
2532                                                 ast_frfree(old_frame);
2533                                 }
2534                         }
2535                         break;
2536                 case AST_FRAME_DTMF_BEGIN:
2537                         send_dtmf_event(chan, "Received", f->subclass, "Yes", "No");
2538                         ast_log(LOG_DTMF, "DTMF begin '%c' received on %s\n", f->subclass, chan->name);
2539                         if ( ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_END_DTMF_ONLY | AST_FLAG_EMULATE_DTMF) || 
2540                             (!ast_tvzero(chan->dtmf_tv) && 
2541                               ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) < AST_MIN_DTMF_GAP) ) {
2542                                 ast_log(LOG_DTMF, "DTMF begin ignored '%c' on %s\n", f->subclass, chan->name);
2543                                 ast_frfree(f);
2544                                 f = &ast_null_frame;
2545                         } else {
2546                                 ast_set_flag(chan, AST_FLAG_IN_DTMF);
2547                                 chan->dtmf_tv = ast_tvnow();
2548                                 ast_log(LOG_DTMF, "DTMF begin passthrough '%c' on %s\n", f->subclass, chan->name);
2549                         }
2550                         break;
2551                 case AST_FRAME_NULL:
2552                         /* The EMULATE_DTMF flag must be cleared here as opposed to when the duration
2553                          * is reached , because we want to make sure we pass at least one
2554                          * voice frame through before starting the next digit, to ensure a gap
2555                          * between DTMF digits. */
2556                         if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF)) {
2557                                 struct timeval now = ast_tvnow();
2558                                 if (!chan->emulate_dtmf_duration) {
2559                                         ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
2560                                         chan->emulate_dtmf_digit = 0;
2561                                 } else if (ast_tvdiff_ms(now, chan->dtmf_tv) >= chan->emulate_dtmf_duration) {
2562                                         chan->emulate_dtmf_duration = 0;
2563                                         ast_frfree(f);
2564                                         f = &chan->dtmff;
2565                                         f->frametype = AST_FRAME_DTMF_END;
2566                                         f->subclass = chan->emulate_dtmf_digit;
2567                                         f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
2568                                         chan->dtmf_tv = now;
2569                                         ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
2570                                         chan->emulate_dtmf_digit = 0;
2571                                         ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass, chan->name);
2572                                 }
2573                         }
2574                         break;
2575                 case AST_FRAME_VOICE:
2576                         /* The EMULATE_DTMF flag must be cleared here as opposed to when the duration
2577                          * is reached , because we want to make sure we pass at least one
2578                          * voice frame through before starting the next digit, to ensure a gap
2579                          * between DTMF digits. */
2580                         if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !chan->emulate_dtmf_duration) {
2581                                 ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
2582                                 chan->emulate_dtmf_digit = 0;
2583                         }
2584
2585                         if (dropaudio || ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
2586                                 if (dropaudio)
2587                                         ast_read_generator_actions(chan, f);
2588                                 ast_frfree(f);
2589                                 f = &ast_null_frame;
2590                         }
2591
2592                         if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
2593                                 struct timeval now = ast_tvnow();
2594                                 if (ast_tvdiff_ms(now, chan->dtmf_tv) >= chan->emulate_dtmf_duration) {
2595                                         chan->emulate_dtmf_duration = 0;
2596                                         ast_frfree(f);
2597                                         f = &chan->dtmff;
2598                                         f->frametype = AST_FRAME_DTMF_END;
2599                                         f->subclass = chan->emulate_dtmf_digit;
2600                                         f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
2601                                         chan->dtmf_tv = now;
2602                                         if (chan->audiohooks) {
2603                                                 struct ast_frame *old_frame = f;
2604                                                 f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
2605                                                 if (old_frame != f)
2606                                                         ast_frfree(old_frame);
2607                                         }
2608                                         ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass, chan->name);
2609                                 } else {
2610                                         /* Drop voice frames while we're still in the middle of the digit */
2611                                         ast_frfree(f);
2612                                         f = &ast_null_frame;
2613                                 }
2614                         } else if ((f->frametype == AST_FRAME_VOICE) && !(f->subclass & chan->nativeformats)) {
2615                                 /* This frame can't be from the current native formats -- drop it on the
2616                                    floor */
2617                                 ast_log(LOG_NOTICE, "Dropping incompatible voice frame on %s of format %s since our native format has changed to %s\n",
2618                                         chan->name, ast_getformatname(f->subclass), ast_getformatname(chan->nativeformats));
2619                                 ast_frfree(f);
2620                                 f = &ast_null_frame;
2621                         } else if ((f->frametype == AST_FRAME_VOICE)) {
2622                                 /* Send frame to audiohooks if present */
2623                                 if (chan->audiohooks) {
2624                                         struct ast_frame *old_frame = f;
2625                                         f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
2626                                         if (old_frame != f)
2627                                                 ast_frfree(old_frame);
2628                                 }
2629                                 if (chan->monitor && chan->monitor->read_stream ) {
2630                                         /* XXX what does this do ? */
2631 #ifndef MONITOR_CONSTANT_DELAY
2632                                         int jump = chan->outsmpl - chan->insmpl - 4 * f->samples;
2633                                         if (jump >= 0) {
2634                                                 jump = chan->outsmpl - chan->insmpl;
2635                                                 if (ast_seekstream(chan->monitor->read_stream, jump, SEEK_FORCECUR) == -1)
2636                                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
2637                                                 chan->insmpl += jump + f->samples;
2638                                         } else
2639                                                 chan->insmpl+= f->samples;
2640 #else
2641                                         int jump = chan->outsmpl - chan->insmpl;
2642                                         if (jump - MONITOR_DELAY >= 0) {
2643                                                 if (ast_seekstream(chan->monitor->read_stream, jump - f->samples, SEEK_FORCECUR) == -1)
2644                                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
2645                                                 chan->insmpl += jump;
2646                                         } else
2647                                                 chan->insmpl += f->samples;
2648 #endif
2649                                         if (chan->monitor->state == AST_MONITOR_RUNNING) {
2650                                                 if (ast_writestream(chan->monitor->read_stream, f) < 0)
2651                                                         ast_log(LOG_WARNING, "Failed to write data to channel monitor read stream\n");
2652                                         }
2653                                 }
2654
2655                                 if (chan->readtrans && (f = ast_translate(chan->readtrans, f, 1)) == NULL)
2656                                         f = &ast_null_frame;
2657                                 else
2658                                         /* Run generator sitting on the line if timing device not available
2659                                          * and synchronous generation of outgoing frames is necessary       */
2660                                         ast_read_generator_actions(chan, f);
2661                         }
2662                 default:
2663                         /* Just pass it on! */
2664                         break;
2665                 }
2666         } else {
2667                 /* Make sure we always return NULL in the future */
2668                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
2669                 if (chan->generator)
2670                         ast_deactivate_generator(chan);
2671                 /* End the CDR if appropriate */
2672                 if (chan->cdr)
2673                         ast_cdr_end(chan->cdr);
2674         }
2675
2676         /* High bit prints debugging */
2677         if (chan->fin & DEBUGCHAN_FLAG)
2678                 ast_frame_dump(chan->name, f, "<<");
2679         chan->fin = FRAMECOUNT_INC(chan->fin);
2680
2681 done:
2682         if (chan->music_state && chan->generator && chan->generator->digit && f && f->frametype == AST_FRAME_DTMF_END)
2683                 chan->generator->digit(chan, f->subclass);
2684
2685         ast_channel_unlock(chan);
2686         return f;
2687 }
2688
2689 int ast_internal_timing_enabled(struct ast_channel *chan)
2690 {
2691         int ret = ast_opt_internal_timing && chan->timingfd > -1;
2692         ast_debug(5, "Internal timing is %s (option_internal_timing=%d chan->timingfd=%d)\n", ret? "enabled": "disabled", ast_opt_internal_timing, chan->timingfd);
2693         return ret;
2694 }
2695
2696 struct ast_frame *ast_read(struct ast_channel *chan)
2697 {
2698         return __ast_read(chan, 0);
2699 }
2700
2701 struct ast_frame *ast_read_noaudio(struct ast_channel *chan)
2702 {
2703         return __ast_read(chan, 1);
2704 }
2705
2706 int ast_indicate(struct ast_channel *chan, int condition)
2707 {
2708         return ast_indicate_data(chan, condition, NULL, 0);
2709 }
2710
2711 int ast_indicate_data(struct ast_channel *chan, int condition, const void *data, size_t datalen)
2712 {
2713         int res = -1;
2714
2715         ast_channel_lock(chan);
2716         /* Stop if we're a zombie or need a soft hangup */
2717         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2718                 ast_channel_unlock(chan);
2719                 return -1;
2720         }
2721         if (chan->tech->indicate)
2722                 res = chan->tech->indicate(chan, condition, data, datalen);
2723         ast_channel_unlock(chan);
2724         if (!chan->tech->indicate || res) {
2725                 /*
2726                  * Device does not support (that) indication, lets fake
2727                  * it by doing our own tone generation. (PM2002)
2728                  */
2729                 if (condition < 0)
2730                         ast_playtones_stop(chan);
2731                 else {
2732                         const struct ind_tone_zone_sound *ts = NULL;
2733                         switch (condition) {
2734                         case AST_CONTROL_RINGING:
2735                                 ts = ast_get_indication_tone(chan->zone, "ring");
2736                                 break;
2737                         case AST_CONTROL_BUSY:
2738                                 ts = ast_get_indication_tone(chan->zone, "busy");
2739                                 break;
2740                         case AST_CONTROL_CONGESTION:
2741                                 ts = ast_get_indication_tone(chan->zone, "congestion");
2742                                 break;
2743                         }
2744                         if (ts && ts->data[0]) {
2745                                 ast_debug(1, "Driver for channel '%s' does not support indication %d, emulating it\n", chan->name, condition);
2746                                 ast_playtones_start(chan,0,ts->data, 1);
2747                                 res = 0;
2748                                 chan->visible_indication = condition;
2749                         } else if (condition == AST_CONTROL_PROGRESS) {
2750                                 /* ast_playtones_stop(chan); */
2751                         } else if (condition == AST_CONTROL_PROCEEDING) {
2752                                 /* Do nothing, really */
2753                         } else if (condition == AST_CONTROL_HOLD) {
2754                                 /* Do nothing.... */
2755                         } else if (condition == AST_CONTROL_UNHOLD) {
2756                                 /* Do nothing.... */
2757                         } else if (condition == AST_CONTROL_VIDUPDATE) {
2758                                 /* Do nothing.... */
2759                         } else if (condition == AST_CONTROL_SRCUPDATE) {
2760                                 /* Do nothing... */
2761                         } else {
2762                                 /* not handled */
2763                                 ast_log(LOG_WARNING, "Unable to handle indication %d for '%s'\n", condition, chan->name);
2764                                 res = -1;
2765                         }
2766                 }
2767         } else
2768                 chan->visible_indication = condition;
2769
2770         return res;
2771 }
2772
2773 int ast_recvchar(struct ast_channel *chan, int timeout)
2774 {
2775         int c;
2776         char *buf = ast_recvtext(chan, timeout);
2777         if (buf == NULL)
2778                 return -1;      /* error or timeout */
2779         c = *(unsigned char *)buf;
2780         ast_free(buf);
2781         return c;
2782 }
2783
2784 char *ast_recvtext(struct ast_channel *chan, int timeout)
2785 {
2786         int res, done = 0;
2787         char *buf = NULL;
2788         
2789         while (!done) {
2790                 struct ast_frame *f;
2791                 if (ast_check_hangup(chan))
2792                         break;
2793                 res = ast_waitfor(chan, timeout);
2794                 if (res <= 0) /* timeout or error */
2795                         break;
2796                 timeout = res;  /* update timeout */
2797                 f = ast_read(chan);
2798                 if (f == NULL)
2799                         break; /* no frame */
2800                 if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP)
2801                         done = 1;       /* force a break */
2802                 else if (f->frametype == AST_FRAME_TEXT) {              /* what we want */
2803                         buf = ast_strndup((char *) f->data, f->datalen);        /* dup and break */
2804                         done = 1;
2805                 }
2806                 ast_frfree(f);
2807         }
2808         return buf;
2809 }
2810
2811 int ast_sendtext(struct ast_channel *chan, const char *text)
2812 {
2813         int res = 0;
2814         /* Stop if we're a zombie or need a soft hangup */
2815         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
2816                 return -1;
2817         CHECK_BLOCKING(chan);
2818         if (chan->tech->send_text)
2819                 res = chan->tech->send_text(chan, text);
2820         ast_clear_flag(chan, AST_FLAG_BLOCKING);
2821         return res;
2822 }
2823
2824 int ast_senddigit_begin(struct ast_channel *chan, char digit)
2825 {
2826         /* Device does not support DTMF tones, lets fake
2827          * it by doing our own generation. */
2828         static const char* dtmf_tones[] = {
2829                 "941+1336", /* 0 */
2830                 "697+1209", /* 1 */
2831                 "697+1336", /* 2 */
2832                 "697+1477", /* 3 */
2833                 "770+1209", /* 4 */
2834                 "770+1336", /* 5 */
2835                 "770+1477", /* 6 */
2836                 "852+1209", /* 7 */
2837                 "852+1336", /* 8 */
2838                 "852+1477", /* 9 */
2839                 "697+1633", /* A */
2840                 "770+1633", /* B */
2841                 "852+1633", /* C */
2842                 "941+1633", /* D */
2843                 "941+1209", /* * */
2844                 "941+1477"  /* # */
2845         };
2846
2847         if (!chan->tech->send_digit_begin)
2848                 return 0;
2849
2850         if (!chan->tech->send_digit_begin(chan, digit))
2851                 return 0;
2852
2853         if (digit >= '0' && digit <='9')
2854                 ast_playtones_start(chan, 0, dtmf_tones[digit-'0'], 0);
2855         else if (digit >= 'A' && digit <= 'D')
2856                 ast_playtones_start(chan, 0, dtmf_tones[digit-'A'+10], 0);
2857         else if (digit == '*')
2858                 ast_playtones_start(chan, 0, dtmf_tones[14], 0);
2859         else if (digit == '#')
2860                 ast_playtones_start(chan, 0, dtmf_tones[15], 0);
2861         else {
2862                 /* not handled */
2863                 ast_debug(1, "Unable to generate DTMF tone '%c' for '%s'\n", digit, chan->name);
2864         }
2865
2866         return 0;
2867 }
2868
2869 int ast_senddigit_end(struct ast_channel *chan, char digit, unsigned int duration)
2870 {
2871         int res = -1;
2872
2873         if (chan->tech->send_digit_end)
2874                 res = chan->tech->send_digit_end(chan, digit, duration);
2875
2876         if (res && chan->generator)
2877                 ast_playtones_stop(chan);
2878         
2879         return 0;
2880 }
2881
2882 int ast_senddigit(struct ast_channel *chan, char digit, unsigned int duration)
2883 {
2884         if (chan->tech->send_digit_begin) {
2885                 ast_senddigit_begin(chan, digit);
2886                 ast_safe_sleep(chan, (duration >= AST_DEFAULT_EMULATE_DTMF_DURATION ? duration : AST_DEFAULT_EMULATE_DTMF_DURATION));
2887         }
2888         
2889         return ast_senddigit_end(chan, digit, (duration >= AST_DEFAULT_EMULATE_DTMF_DURATION ? duration : AST_DEFAULT_EMULATE_DTMF_DURATION));
2890 }
2891
2892 int ast_prod(struct ast_channel *chan)
2893 {
2894         struct ast_frame a = { AST_FRAME_VOICE };
2895         char nothing[128];
2896
2897         /* Send an empty audio frame to get things moving */
2898         if (chan->_state != AST_STATE_UP) {
2899                 ast_debug(1, "Prodding channel '%s'\n", chan->name);
2900                 a.subclass = chan->rawwriteformat;
2901                 a.data = nothing + AST_FRIENDLY_OFFSET;
2902                 a.src = "ast_prod";
2903                 if (ast_write(chan, &a))
2904                         ast_log(LOG_WARNING, "Prodding channel '%s' failed\n", chan->name);
2905         }
2906         return 0;
2907 }
2908
2909 int ast_write_video(struct ast_channel *chan, struct ast_frame *fr)
2910 {
2911         int res;
2912         if (!chan->tech->write_video)
2913                 return 0;
2914         res = ast_write(chan, fr);
2915         if (!res)
2916                 res = 1;
2917         return res;
2918 }
2919
2920 int ast_write(struct ast_channel *chan, struct ast_frame *fr)
2921 {
2922         int res = -1;
2923         struct ast_frame *f = NULL, *f2 = NULL;
2924         int count = 0;
2925
2926         /*Deadlock avoidance*/
2927         while(ast_channel_trylock(chan)) {
2928                 /*cannot goto done since the channel is not locked*/
2929                 if(count++ > 10) {
2930                         ast_debug(1, "Deadlock avoided for write to channel '%s'\n", chan->name);
2931                         return 0;
2932                 }
2933                 usleep(1);
2934         }
2935         /* Stop if we're a zombie or need a soft hangup */
2936         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
2937                 goto done;
2938
2939         /* Handle any pending masquerades */
2940         if (chan->masq && ast_do_masquerade(chan)) {
2941                 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
2942                 goto done;
2943         }
2944         if (chan->masqr) {
2945                 res = 0;        /* XXX explain, why 0 ? */
2946                 goto done;
2947         }
2948         if (chan->generatordata) {
2949                 if (ast_test_flag(chan, AST_FLAG_WRITE_INT))
2950                         ast_deactivate_generator(chan);
2951                 else {
2952                         if (fr->frametype == AST_FRAME_DTMF_END) {
2953                                 /* There is a generator running while we're in the middle of a digit.
2954                                  * It's probably inband DTMF, so go ahead and pass it so it can
2955                                  * stop the generator */
2956                                 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2957                                 ast_channel_unlock(chan);
2958                                 res = ast_senddigit_end(chan, fr->subclass, fr->len);
2959                                 ast_channel_lock(chan);
2960                                 CHECK_BLOCKING(chan);
2961                         } else if (fr->frametype == AST_FRAME_CONTROL && fr->subclass == AST_CONTROL_UNHOLD) {
2962                                 /* This is a side case where Echo is basically being called and the person put themselves on hold and took themselves off hold */
2963                                 res = (chan->tech->indicate == NULL) ? 0 :
2964                                         chan->tech->indicate(chan, fr->subclass, fr->data, fr->datalen);
2965                         }
2966                         res = 0;        /* XXX explain, why 0 ? */
2967                         goto done;
2968                 }
2969         }
2970         /* High bit prints debugging */
2971         if (chan->fout & DEBUGCHAN_FLAG)
2972                 ast_frame_dump(chan->name, fr, ">>");
2973         CHECK_BLOCKING(chan);
2974         switch (fr->frametype) {
2975         case AST_FRAME_CONTROL:
2976                 res = (chan->tech->indicate == NULL) ? 0 :
2977                         chan->tech->indicate(chan, fr->subclass, fr->data, fr->datalen);
2978                 break;
2979         case AST_FRAME_DTMF_BEGIN:
2980                 if (chan->audiohooks) {
2981                         struct ast_frame *old_frame = fr;
2982                         fr = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_WRITE, fr);
2983                         if (old_frame != fr)
2984                                 f = fr;
2985                 }
2986                 send_dtmf_event(chan, "Sent", fr->subclass, "Yes", "No");
2987                 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2988                 ast_channel_unlock(chan);
2989                 res = ast_senddigit_begin(chan, fr->subclass);
2990                 ast_channel_lock(chan);
2991                 CHECK_BLOCKING(chan);
2992                 break;
2993         case AST_FRAME_DTMF_END:
2994                 if (chan->audiohooks) {
2995                         struct ast_frame *old_frame = fr;
2996                         fr = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_WRITE, fr);
2997                         if (old_frame != fr)
2998                                 f = fr;
2999                 }
3000                 send_dtmf_event(chan, "Sent", fr->subclass, "No", "Yes");
3001                 ast_clear_flag(chan, AST_FLAG_BLOCKING);
3002                 ast_channel_unlock(chan);
3003                 res = ast_senddigit_end(chan, fr->subclass, fr->len);
3004                 ast_channel_lock(chan);
3005                 CHECK_BLOCKING(chan);
3006                 break;
3007         case AST_FRAME_TEXT:
3008                 if (fr->subclass == AST_FORMAT_T140) {
3009                         res = (chan->tech->write_text == NULL) ? 0 :
3010                                 chan->tech->write_text(chan, fr);
3011                 } else {
3012                         res = (chan->tech->send_text == NULL) ? 0 :
3013                                 chan->tech->send_text(chan, (char *) fr->data);
3014                 }
3015                 break;
3016         case AST_FRAME_HTML:
3017                 res = (chan->tech->send_html == NULL) ? 0 :
3018                         chan->tech->send_html(chan, fr->subclass, (char *) fr->data, fr->datalen);
3019                 break;
3020         case AST_FRAME_VIDEO:
3021                 /* XXX Handle translation of video codecs one day XXX */
3022                 res = (chan->tech->write_video == NULL) ? 0 :
3023                         chan->tech->write_video(chan, fr);
3024                 break;
3025         case AST_FRAME_MODEM:
3026                 res = (chan->tech->write == NULL) ? 0 :
3027                         chan->tech->write(chan, fr);
3028                 break;
3029         case AST_FRAME_VOICE:
3030                 if (chan->tech->write == NULL)
3031                         break;  /*! \todo XXX should return 0 maybe ? */
3032
3033                 /* If audiohooks are present, write the frame out */
3034                 if (chan->audiohooks) {
3035                         struct ast_frame *old_frame = fr;
3036                         fr = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_WRITE, fr);
3037                         if (old_frame != fr)
3038                                 f2 = fr;
3039                 }
3040
3041                 /* If the frame is in the raw write format, then it's easy... just use the frame - otherwise we will have to translate */
3042                 if (fr->subclass == chan->rawwriteformat)
3043                         f = fr;
3044                 else
3045                         f = (chan->writetrans) ? ast_translate(chan->writetrans, fr, 0) : fr;
3046
3047                 if (!f) {
3048                         res = 0;
3049                         break;
3050                 }
3051
3052                 /* If Monitor is running on this channel, then we have to write frames out there too */
3053                 if (chan->monitor && chan->monitor->write_stream) {
3054                         /* XXX must explain this code */
3055 #ifndef MONITOR_CONSTANT_DELAY
3056                         int jump = chan->insmpl - chan->outsmpl - 4 * f->samples;
3057                         if (jump >= 0) {
3058                                 jump = chan->insmpl - chan->outsmpl;
3059                                 if (ast_seekstream(chan->monitor->write_stream, jump, SEEK_FORCECUR) == -1)
3060                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
3061                                 chan->outsmpl += jump + f->samples;
3062                         } else
3063                                 chan->outsmpl += f->samples;
3064 #else
3065                         int jump = chan->insmpl - chan->outsmpl;
3066                         if (jump - MONITOR_DELAY >= 0) {
3067                                 if (ast_seekstream(chan->monitor->write_stream, jump - f->samples, SEEK_FORCECUR) == -1)
3068                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
3069                                 chan->outsmpl += jump;
3070                         } else
3071                                 chan->outsmpl += f->samples;
3072 #endif
3073                         if (chan->monitor->state == AST_MONITOR_RUNNING) {
3074                                 if (ast_writestream(chan->monitor->write_stream, f) < 0)
3075                                         ast_log(LOG_WARNING, "Failed to write data to channel monitor write stream\n");
3076                         }
3077                 }
3078
3079                 if (f) 
3080                         res = chan->tech->write(chan,f);
3081                 else
3082                         res = 0;
3083                 bre