Merged revisions 106788 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
1261            has it locked still */
1262         ast_channel_lock(chan);
1263         ast_channel_unlock(chan);
1264         if (chan->tech_pvt) {
1265                 ast_log(LOG_WARNING, "Channel '%s' may not have been hung up properly\n", chan->name);
1266                 ast_free(chan->tech_pvt);
1267         }
1268
1269         if (chan->sched)
1270                 sched_context_destroy(chan->sched);
1271
1272         ast_copy_string(name, chan->name, sizeof(name));
1273
1274         /* Stop monitoring */
1275         if (chan->monitor)
1276                 chan->monitor->stop( chan, 0 );
1277
1278         /* If there is native format music-on-hold state, free it */
1279         if (chan->music_state)
1280                 ast_moh_cleanup(chan);
1281
1282         /* Free translators */
1283         if (chan->readtrans)
1284                 ast_translator_free_path(chan->readtrans);
1285         if (chan->writetrans)
1286                 ast_translator_free_path(chan->writetrans);
1287         if (chan->pbx)
1288                 ast_log(LOG_WARNING, "PBX may not have been terminated properly on '%s'\n", chan->name);
1289         free_cid(&chan->cid);
1290         ast_mutex_destroy(&chan->lock_dont_use);
1291         /* Close pipes if appropriate */
1292         if ((fd = chan->alertpipe[0]) > -1)
1293                 close(fd);
1294         if ((fd = chan->alertpipe[1]) > -1)
1295                 close(fd);
1296         if ((fd = chan->timingfd) > -1)
1297                 close(fd);
1298 #ifdef HAVE_EPOLL
1299         for (i = 0; i < AST_MAX_FDS; i++) {
1300                 if (chan->epfd_data[i])
1301                         free(chan->epfd_data[i]);
1302         }
1303         close(chan->epfd);
1304 #endif
1305         while ((f = AST_LIST_REMOVE_HEAD(&chan->readq, frame_list)))
1306                 ast_frfree(f);
1307         
1308         /* Get rid of each of the data stores on the channel */
1309         while ((datastore = AST_LIST_REMOVE_HEAD(&chan->datastores, entry)))
1310                 /* Free the data store */
1311                 ast_channel_datastore_free(datastore);
1312         AST_LIST_HEAD_INIT_NOLOCK(&chan->datastores);
1313
1314         /* loop over the variables list, freeing all data and deleting list items */
1315         /* no need to lock the list, as the channel is already locked */
1316         
1317         while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
1318                 ast_var_delete(vardata);
1319
1320         ast_app_group_discard(chan);
1321
1322         /* Destroy the jitterbuffer */
1323         ast_jb_destroy(chan);
1324
1325         ast_string_field_free_memory(chan);
1326         ast_free(chan);
1327         AST_RWLIST_UNLOCK(&channels);
1328
1329         ast_device_state_changed_literal(name);
1330 }
1331
1332 struct ast_datastore *ast_channel_datastore_alloc(const struct ast_datastore_info *info, const char *uid)
1333 {
1334         struct ast_datastore *datastore = NULL;
1335
1336         /* Make sure we at least have type so we can identify this */
1337         if (!info) {
1338                 return NULL;
1339         }
1340
1341         /* Allocate memory for datastore and clear it */
1342         datastore = ast_calloc(1, sizeof(*datastore));
1343         if (!datastore) {
1344                 return NULL;
1345         }
1346
1347         datastore->info = info;
1348
1349         datastore->uid = ast_strdup(uid);
1350
1351         return datastore;
1352 }
1353
1354 int ast_channel_datastore_free(struct ast_datastore *datastore)
1355 {
1356         int res = 0;
1357
1358         /* Using the destroy function (if present) destroy the data */
1359         if (datastore->info->destroy != NULL && datastore->data != NULL) {
1360                 datastore->info->destroy(datastore->data);
1361                 datastore->data = NULL;
1362         }
1363
1364         /* Free allocated UID memory */
1365         if (datastore->uid != NULL) {
1366                 ast_free((void *) datastore->uid);
1367                 datastore->uid = NULL;
1368         }
1369
1370         /* Finally free memory used by ourselves */
1371         ast_free(datastore);
1372
1373         return res;
1374 }
1375
1376 int ast_channel_datastore_inherit(struct ast_channel *from, struct ast_channel *to)
1377 {
1378         struct ast_datastore *datastore = NULL, *datastore2;
1379
1380         AST_LIST_TRAVERSE(&from->datastores, datastore, entry) {
1381                 if (datastore->inheritance > 0) {
1382                         datastore2 = ast_channel_datastore_alloc(datastore->info, datastore->uid);
1383                         if (datastore2) {
1384                                 datastore2->data = datastore->info->duplicate(datastore->data);
1385                                 datastore2->inheritance = datastore->inheritance == DATASTORE_INHERIT_FOREVER ? DATASTORE_INHERIT_FOREVER : datastore->inheritance - 1;
1386                                 AST_LIST_INSERT_TAIL(&to->datastores, datastore2, entry);
1387                         }
1388                 }
1389         }
1390         return 0;
1391 }
1392
1393 int ast_channel_datastore_add(struct ast_channel *chan, struct ast_datastore *datastore)
1394 {
1395         int res = 0;
1396
1397         AST_LIST_INSERT_HEAD(&chan->datastores, datastore, entry);
1398
1399         return res;
1400 }
1401
1402 int ast_channel_datastore_remove(struct ast_channel *chan, struct ast_datastore *datastore)
1403 {
1404         return AST_LIST_REMOVE(&chan->datastores, datastore, entry) ? 0 : -1;
1405 }
1406
1407 struct ast_datastore *ast_channel_datastore_find(struct ast_channel *chan, const struct ast_datastore_info *info, const char *uid)
1408 {
1409         struct ast_datastore *datastore = NULL;
1410         
1411         if (info == NULL)
1412                 return NULL;
1413
1414         AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->datastores, datastore, entry) {
1415                 if (datastore->info == info) {
1416                         if (uid != NULL && datastore->uid != NULL) {
1417                                 if (!strcasecmp(uid, datastore->uid)) {
1418                                         /* Matched by type AND uid */
1419                                         break;
1420                                 }
1421                         } else {
1422                                 /* Matched by type at least */
1423                                 break;
1424                         }
1425                 }
1426         }
1427         AST_LIST_TRAVERSE_SAFE_END
1428
1429         return datastore;
1430 }
1431
1432 /*! Set the file descriptor on the channel */
1433 void ast_channel_set_fd(struct ast_channel *chan, int which, int fd)
1434 {
1435 #ifdef HAVE_EPOLL
1436         struct epoll_event ev;
1437         struct ast_epoll_data *aed = NULL;
1438
1439         if (chan->fds[which] > -1) {
1440                 epoll_ctl(chan->epfd, EPOLL_CTL_DEL, chan->fds[which], &ev);
1441                 aed = chan->epfd_data[which];
1442         }
1443
1444         /* If this new fd is valid, add it to the epoll */
1445         if (fd > -1) {
1446                 if (!aed && (!(aed = ast_calloc(1, sizeof(*aed)))))
1447                         return;
1448                 
1449                 chan->epfd_data[which] = aed;
1450                 aed->chan = chan;
1451                 aed->which = which;
1452                 
1453                 ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
1454                 ev.data.ptr = aed;
1455                 epoll_ctl(chan->epfd, EPOLL_CTL_ADD, fd, &ev);
1456         } else if (aed) {
1457                 /* We don't have to keep around this epoll data structure now */
1458                 free(aed);
1459                 chan->epfd_data[which] = NULL;
1460         }
1461 #endif
1462         chan->fds[which] = fd;
1463         return;
1464 }
1465
1466 /*! Add a channel to an optimized waitfor */
1467 void ast_poll_channel_add(struct ast_channel *chan0, struct ast_channel *chan1)
1468 {
1469 #ifdef HAVE_EPOLL
1470         struct epoll_event ev;
1471         int i = 0;
1472
1473         if (chan0->epfd == -1)
1474                 return;
1475
1476         /* Iterate through the file descriptors on chan1, adding them to chan0 */
1477         for (i = 0; i < AST_MAX_FDS; i++) {
1478                 if (chan1->fds[i] == -1)
1479                         continue;
1480                 ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
1481                 ev.data.ptr = chan1->epfd_data[i];
1482                 epoll_ctl(chan0->epfd, EPOLL_CTL_ADD, chan1->fds[i], &ev);
1483         }
1484
1485 #endif
1486         return;
1487 }
1488
1489 /*! Delete a channel from an optimized waitfor */
1490 void ast_poll_channel_del(struct ast_channel *chan0, struct ast_channel *chan1)
1491 {
1492 #ifdef HAVE_EPOLL
1493         struct epoll_event ev;
1494         int i = 0;
1495
1496         if (chan0->epfd == -1)
1497                 return;
1498
1499         for (i = 0; i < AST_MAX_FDS; i++) {
1500                 if (chan1->fds[i] == -1)
1501                         continue;
1502                 epoll_ctl(chan0->epfd, EPOLL_CTL_DEL, chan1->fds[i], &ev);
1503         }
1504
1505 #endif
1506         return;
1507 }
1508
1509 /*! \brief Softly hangup a channel, don't lock */
1510 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
1511 {
1512         ast_debug(1, "Soft-Hanging up channel '%s'\n", chan->name);
1513         /* Inform channel driver that we need to be hung up, if it cares */
1514         chan->_softhangup |= cause;
1515         ast_queue_frame(chan, &ast_null_frame);
1516         /* Interrupt any poll call or such */
1517         if (ast_test_flag(chan, AST_FLAG_BLOCKING))
1518                 pthread_kill(chan->blocker, SIGURG);
1519         return 0;
1520 }
1521
1522 /*! \brief Softly hangup a channel, lock */
1523 int ast_softhangup(struct ast_channel *chan, int cause)
1524 {
1525         int res;
1526         ast_channel_lock(chan);
1527         res = ast_softhangup_nolock(chan, cause);
1528         ast_channel_unlock(chan);
1529         return res;
1530 }
1531
1532 static void free_translation(struct ast_channel *clone)
1533 {
1534         if (clone->writetrans)
1535                 ast_translator_free_path(clone->writetrans);
1536         if (clone->readtrans)
1537                 ast_translator_free_path(clone->readtrans);
1538         clone->writetrans = NULL;
1539         clone->readtrans = NULL;
1540         clone->rawwriteformat = clone->nativeformats;
1541         clone->rawreadformat = clone->nativeformats;
1542 }
1543
1544 /*! \brief Hangup a channel */
1545 int ast_hangup(struct ast_channel *chan)
1546 {
1547         int res = 0;
1548         struct ast_cdr *cdr = NULL;
1549
1550         /* Don't actually hang up a channel that will masquerade as someone else, or
1551            if someone is going to masquerade as us */
1552         ast_channel_lock(chan);
1553
1554         if (chan->audiohooks) {
1555                 ast_audiohook_detach_list(chan->audiohooks);
1556                 chan->audiohooks = NULL;
1557         }
1558
1559         ast_autoservice_stop(chan);
1560
1561         if (chan->masq) {
1562                 if (ast_do_masquerade(chan))
1563                         ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1564         }
1565
1566         if (chan->masq) {
1567                 ast_log(LOG_WARNING, "%s getting hung up, but someone is trying to masq into us?!?\n", chan->name);
1568                 ast_channel_unlock(chan);
1569                 return 0;
1570         }
1571         /* If this channel is one which will be masqueraded into something,
1572            mark it as a zombie already, so we know to free it later */
1573         if (chan->masqr) {
1574                 ast_set_flag(chan, AST_FLAG_ZOMBIE);
1575                 ast_channel_unlock(chan);
1576                 return 0;
1577         }
1578         free_translation(chan);
1579         /* Close audio stream */
1580         if (chan->stream) {
1581                 ast_closestream(chan->stream);
1582                 chan->stream = NULL;
1583         }
1584         /* Close video stream */
1585         if (chan->vstream) {
1586                 ast_closestream(chan->vstream);
1587                 chan->vstream = NULL;
1588         }
1589         if (chan->sched) {
1590                 sched_context_destroy(chan->sched);
1591                 chan->sched = NULL;
1592         }
1593         
1594         if (chan->generatordata)        /* Clear any tone stuff remaining */
1595                 if (chan->generator && chan->generator->release)
1596                         chan->generator->release(chan, chan->generatordata);
1597         chan->generatordata = NULL;
1598         chan->generator = NULL;
1599         if (chan->cdr) {                /* End the CDR if it hasn't already */
1600                 ast_cdr_end(chan->cdr);
1601                 cdr = chan->cdr;
1602                 chan->cdr = NULL;
1603         }
1604         if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
1605                 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
1606                                         "is blocked by thread %ld in procedure %s!  Expect a failure\n",
1607                                         (long)pthread_self(), chan->name, (long)chan->blocker, chan->blockproc);
1608                 CRASH;
1609         }
1610         if (!ast_test_flag(chan, AST_FLAG_ZOMBIE)) {
1611                 ast_debug(1, "Hanging up channel '%s'\n", chan->name);
1612                 if (chan->tech->hangup)
1613                         res = chan->tech->hangup(chan);
1614         } else {
1615                 ast_debug(1, "Hanging up zombie '%s'\n", chan->name);
1616         }
1617                         
1618         ast_channel_unlock(chan);
1619         manager_event(EVENT_FLAG_CALL, "Hangup",
1620                         "Channel: %s\r\n"
1621                         "Uniqueid: %s\r\n"
1622                         "CallerIDNum: %s\r\n"
1623                         "CallerIDName: %s\r\n"
1624                         "Cause: %d\r\n"
1625                         "Cause-txt: %s\r\n",
1626                         chan->name,
1627                         chan->uniqueid,
1628                         S_OR(chan->cid.cid_num, "<unknown>"),
1629                         S_OR(chan->cid.cid_name, "<unknown>"),
1630                         chan->hangupcause,
1631                         ast_cause2str(chan->hangupcause)
1632                         );
1633         ast_channel_free(chan);
1634
1635         if (cdr)
1636                 ast_cdr_detach(cdr);
1637
1638         return res;
1639 }
1640
1641 int __ast_answer(struct ast_channel *chan, unsigned int delay)
1642 {
1643         int res = 0;
1644
1645         ast_channel_lock(chan);
1646
1647         /* You can't answer an outbound call */
1648         if (ast_test_flag(chan, AST_FLAG_OUTGOING)) {
1649                 ast_channel_unlock(chan);
1650                 return 0;
1651         }
1652
1653         /* Stop if we're a zombie or need a soft hangup */
1654         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
1655                 ast_channel_unlock(chan);
1656                 return -1;
1657         }
1658
1659         switch (chan->_state) {
1660         case AST_STATE_RINGING:
1661         case AST_STATE_RING:
1662                 if (chan->tech->answer)
1663                         res = chan->tech->answer(chan);
1664                 ast_setstate(chan, AST_STATE_UP);
1665                 ast_cdr_answer(chan->cdr);
1666                 ast_channel_unlock(chan);
1667                 if (delay)
1668                         ast_safe_sleep(chan, delay);
1669                 return res;
1670                 break;
1671         case AST_STATE_UP:
1672                 ast_cdr_answer(chan->cdr);
1673                 break;
1674         default:
1675                 break;
1676         }
1677         chan->visible_indication = 0;
1678         ast_channel_unlock(chan);
1679
1680         return res;
1681 }
1682
1683 int ast_answer(struct ast_channel *chan)
1684 {
1685         return __ast_answer(chan, 500);
1686 }
1687
1688 void ast_deactivate_generator(struct ast_channel *chan)
1689 {
1690         ast_channel_lock(chan);
1691         if (chan->generatordata) {
1692                 if (chan->generator && chan->generator->release)
1693                         chan->generator->release(chan, chan->generatordata);
1694                 chan->generatordata = NULL;
1695                 chan->generator = NULL;
1696                 ast_channel_set_fd(chan, AST_GENERATOR_FD, -1);
1697                 ast_clear_flag(chan, AST_FLAG_WRITE_INT);
1698                 ast_settimeout(chan, 0, NULL, NULL);
1699         }
1700         ast_channel_unlock(chan);
1701 }
1702
1703 static int generator_force(const void *data)
1704 {
1705         /* Called if generator doesn't have data */
1706         void *tmp;
1707         int res;
1708         int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples);
1709         struct ast_channel *chan = (struct ast_channel *)data;
1710
1711         ast_channel_lock(chan);
1712         tmp = chan->generatordata;
1713         chan->generatordata = NULL;
1714         generate = chan->generator->generate;
1715         ast_channel_unlock(chan);
1716
1717         res = generate(chan, tmp, 0, 160);
1718
1719         chan->generatordata = tmp;
1720
1721         if (res) {
1722                 ast_debug(1, "Auto-deactivating generator\n");
1723                 ast_deactivate_generator(chan);
1724         }
1725
1726         return 0;
1727 }
1728
1729 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
1730 {
1731         int res = 0;
1732
1733         ast_channel_lock(chan);
1734
1735         if (chan->generatordata) {
1736                 if (chan->generator && chan->generator->release)
1737                         chan->generator->release(chan, chan->generatordata);
1738                 chan->generatordata = NULL;
1739         }
1740
1741         ast_prod(chan);
1742         if (gen->alloc && !(chan->generatordata = gen->alloc(chan, params))) {
1743                 res = -1;
1744         }
1745         
1746         if (!res) {
1747                 ast_settimeout(chan, 160, generator_force, chan);
1748                 chan->generator = gen;
1749         }
1750
1751         ast_channel_unlock(chan);
1752
1753         return res;
1754 }
1755
1756 /*! \brief Wait for x amount of time on a file descriptor to have input.  */
1757 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
1758 {
1759         int winner = -1;
1760         ast_waitfor_nandfds(NULL, 0, fds, n, exception, &winner, ms);
1761         return winner;
1762 }
1763
1764 /*! \brief Wait for x amount of time on a file descriptor to have input.  */
1765 #ifdef HAVE_EPOLL
1766 static struct ast_channel *ast_waitfor_nandfds_classic(struct ast_channel **c, int n, int *fds, int nfds,
1767                                         int *exception, int *outfd, int *ms)
1768 #else
1769 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
1770                                         int *exception, int *outfd, int *ms)
1771 #endif
1772 {
1773         struct timeval start = { 0 , 0 };
1774         struct pollfd *pfds = NULL;
1775         int res;
1776         long rms;
1777         int x, y, max;
1778         int sz;
1779         time_t now = 0;
1780         long whentohangup = 0, diff;
1781         struct ast_channel *winner = NULL;
1782         struct fdmap {
1783                 int chan;
1784                 int fdno;
1785         } *fdmap = NULL;
1786
1787         if ((sz = n * AST_MAX_FDS + nfds)) {
1788                 pfds = alloca(sizeof(*pfds) * sz);
1789                 fdmap = alloca(sizeof(*fdmap) * sz);
1790         }
1791
1792         if (outfd)
1793                 *outfd = -99999;
1794         if (exception)
1795                 *exception = 0;
1796         
1797         /* Perform any pending masquerades */
1798         for (x = 0; x < n; x++) {
1799                 ast_channel_lock(c[x]);
1800                 if (c[x]->masq && ast_do_masquerade(c[x])) {
1801                         ast_log(LOG_WARNING, "Masquerade failed\n");
1802                         *ms = -1;
1803                         ast_channel_unlock(c[x]);
1804                         return NULL;
1805                 }
1806                 if (c[x]->whentohangup) {
1807                         if (!whentohangup)
1808                                 time(&now);
1809                         diff = c[x]->whentohangup - now;
1810                         if (diff < 1) {
1811                                 /* Should already be hungup */
1812                                 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1813                                 ast_channel_unlock(c[x]);
1814                                 return c[x];
1815                         }
1816                         if (!whentohangup || (diff < whentohangup))
1817                                 whentohangup = diff;
1818                 }
1819                 ast_channel_unlock(c[x]);
1820         }
1821         /* Wait full interval */
1822         rms = *ms;
1823         if (whentohangup) {
1824                 rms = whentohangup * 1000;              /* timeout in milliseconds */
1825                 if (*ms >= 0 && *ms < rms)              /* original *ms still smaller */
1826                         rms =  *ms;
1827         }
1828         /*
1829          * Build the pollfd array, putting the channels' fds first,
1830          * followed by individual fds. Order is important because
1831          * individual fd's must have priority over channel fds.
1832          */
1833         max = 0;
1834         for (x = 0; x < n; x++) {
1835                 for (y = 0; y < AST_MAX_FDS; y++) {
1836                         fdmap[max].fdno = y;  /* fd y is linked to this pfds */
1837                         fdmap[max].chan = x;  /* channel x is linked to this pfds */
1838                         max += ast_add_fd(&pfds[max], c[x]->fds[y]);
1839                 }
1840                 CHECK_BLOCKING(c[x]);
1841         }
1842         /* Add the individual fds */
1843         for (x = 0; x < nfds; x++) {
1844                 fdmap[max].chan = -1;
1845                 max += ast_add_fd(&pfds[max], fds[x]);
1846         }
1847
1848         if (*ms > 0)
1849                 start = ast_tvnow();
1850         
1851         if (sizeof(int) == 4) { /* XXX fix timeout > 600000 on linux x86-32 */
1852                 do {
1853                         int kbrms = rms;
1854                         if (kbrms > 600000)
1855                                 kbrms = 600000;
1856                         res = poll(pfds, max, kbrms);
1857                         if (!res)
1858                                 rms -= kbrms;
1859                 } while (!res && (rms > 0));
1860         } else {
1861                 res = poll(pfds, max, rms);
1862         }
1863         for (x = 0; x < n; x++)
1864                 ast_clear_flag(c[x], AST_FLAG_BLOCKING);
1865         if (res < 0) { /* Simulate a timeout if we were interrupted */
1866                 if (errno != EINTR)
1867                         *ms = -1;
1868                 return NULL;
1869         }
1870         if (whentohangup) {   /* if we have a timeout, check who expired */
1871                 time(&now);
1872                 for (x = 0; x < n; x++) {
1873                         if (c[x]->whentohangup && now >= c[x]->whentohangup) {
1874                                 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1875                                 if (winner == NULL)
1876                                         winner = c[x];
1877                         }
1878                 }
1879         }
1880         if (res == 0) { /* no fd ready, reset timeout and done */
1881                 *ms = 0;        /* XXX use 0 since we may not have an exact timeout. */
1882                 return winner;
1883         }
1884         /*
1885          * Then check if any channel or fd has a pending event.
1886          * Remember to check channels first and fds last, as they
1887          * must have priority on setting 'winner'
1888          */
1889         for (x = 0; x < max; x++) {
1890                 res = pfds[x].revents;
1891                 if (res == 0)
1892                         continue;
1893                 if (fdmap[x].chan >= 0) {       /* this is a channel */
1894                         winner = c[fdmap[x].chan];      /* override previous winners */
1895                         if (res & POLLPRI)
1896                                 ast_set_flag(winner, AST_FLAG_EXCEPTION);
1897                         else
1898                                 ast_clear_flag(winner, AST_FLAG_EXCEPTION);
1899                         winner->fdno = fdmap[x].fdno;
1900                 } else {                        /* this is an fd */
1901                         if (outfd)
1902                                 *outfd = pfds[x].fd;
1903                         if (exception)
1904                                 *exception = (res & POLLPRI) ? -1 : 0;
1905                         winner = NULL;
1906                 }
1907         }
1908         if (*ms > 0) {
1909                 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
1910                 if (*ms < 0)
1911                         *ms = 0;
1912         }
1913         return winner;
1914 }
1915
1916 #ifdef HAVE_EPOLL
1917 static struct ast_channel *ast_waitfor_nandfds_simple(struct ast_channel *chan, int *ms)
1918 {
1919         struct timeval start = { 0 , 0 };
1920         int res = 0;
1921         struct epoll_event ev[1];
1922         long whentohangup = 0, rms = *ms;
1923         time_t now;
1924         struct ast_channel *winner = NULL;
1925         struct ast_epoll_data *aed = NULL;
1926
1927         ast_channel_lock(chan);
1928
1929         /* See if this channel needs to be masqueraded */
1930         if (chan->masq && ast_do_masquerade(chan)) {
1931                 ast_log(LOG_WARNING, "Failed to perform masquerade on %s\n", chan->name);
1932                 *ms = -1;
1933                 ast_channel_unlock(chan);
1934                 return NULL;
1935         }
1936
1937         /* Figure out their timeout */
1938         if (chan->whentohangup) {
1939                 time(&now);
1940                 if ((whentohangup = chan->whentohangup - now) < 1) {
1941                         /* They should already be hungup! */
1942                         chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1943                         ast_channel_unlock(chan);
1944                         return NULL;
1945                 }
1946                 /* If this value is smaller then the current one... make it priority */
1947                 whentohangup *= 1000;
1948                 if (rms > whentohangup)
1949                         rms = whentohangup;
1950         }
1951
1952         ast_channel_unlock(chan);
1953
1954         /* Time to make this channel block... */
1955         CHECK_BLOCKING(chan);
1956
1957         if (*ms > 0)
1958                 start = ast_tvnow();
1959
1960         /* We don't have to add any file descriptors... they are already added, we just have to wait! */
1961         res = epoll_wait(chan->epfd, ev, 1, rms);
1962
1963         /* Stop blocking */
1964         ast_clear_flag(chan, AST_FLAG_BLOCKING);
1965
1966         /* Simulate a timeout if we were interrupted */
1967         if (res < 0) {
1968                 if (errno != EINTR)
1969                         *ms = -1;
1970                 return NULL;
1971         }
1972
1973         /* If this channel has a timeout see if it expired */
1974         if (chan->whentohangup) {
1975                 time(&now);
1976                 if (now >= chan->whentohangup) {
1977                         chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1978                         winner = chan;
1979                 }
1980         }
1981
1982         /* No fd ready, reset timeout and be done for now */
1983         if (!res) {
1984                 *ms = 0;
1985                 return winner;
1986         }
1987
1988         /* See what events are pending */
1989         aed = ev[0].data.ptr;
1990         chan->fdno = aed->which;
1991         if (ev[0].events & EPOLLPRI)
1992                 ast_set_flag(chan, AST_FLAG_EXCEPTION);
1993         else
1994                 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
1995
1996         if (*ms > 0) {
1997                 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
1998                 if (*ms < 0)
1999                         *ms = 0;
2000         }
2001
2002         return chan;
2003 }
2004
2005 static struct ast_channel *ast_waitfor_nandfds_complex(struct ast_channel **c, int n, int *ms)
2006 {
2007         struct timeval start = { 0 , 0 };
2008         int res = 0, i;
2009         struct epoll_event ev[25] = { { 0, } };
2010         long whentohangup = 0, diff, rms = *ms;
2011         time_t now;
2012         struct ast_channel *winner = NULL;
2013
2014         for (i = 0; i < n; i++) {
2015                 ast_channel_lock(c[i]);
2016                 if (c[i]->masq && ast_do_masquerade(c[i])) {
2017                         ast_log(LOG_WARNING, "Masquerade failed\n");
2018                         *ms = -1;
2019                         ast_channel_unlock(c[i]);
2020                         return NULL;
2021                 }
2022                 if (c[i]->whentohangup) {
2023                         if (!whentohangup)
2024                                 time(&now);
2025                         if ((diff = c[i]->whentohangup - now) < 1) {
2026                                 c[i]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
2027                                 ast_channel_unlock(c[i]);
2028                                 return c[i];
2029                         }
2030                         if (!whentohangup || (diff < whentohangup))
2031                                 whentohangup = diff;
2032                 }
2033                 ast_channel_unlock(c[i]);
2034                 CHECK_BLOCKING(c[i]);
2035         }
2036
2037         rms = *ms;
2038         if (whentohangup) {
2039                 rms = whentohangup * 1000;
2040                 if (*ms >= 0 && *ms < rms)
2041                         rms = *ms;
2042         }
2043
2044         if (*ms > 0)
2045                 start = ast_tvnow();
2046
2047         res = epoll_wait(c[0]->epfd, ev, 25, rms);
2048
2049         for (i = 0; i < n; i++)
2050                 ast_clear_flag(c[i], AST_FLAG_BLOCKING);
2051
2052         if (res < 0) {
2053                 if (errno != EINTR)
2054                         *ms = -1;
2055                 return NULL;
2056         }
2057
2058         if (whentohangup) {
2059                 time(&now);
2060                 for (i = 0; i < n; i++) {
2061                         if (c[i]->whentohangup && now >= c[i]->whentohangup) {
2062                                 c[i]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
2063                                 if (!winner)
2064                                         winner = c[i];
2065                         }
2066                 }
2067         }
2068
2069         if (!res) {
2070                 *ms = 0;
2071                 return winner;
2072         }
2073
2074         for (i = 0; i < res; i++) {
2075                 struct ast_epoll_data *aed = ev[i].data.ptr;
2076
2077                 if (!ev[i].events || !aed)
2078                         continue;
2079
2080                 winner = aed->chan;
2081                 if (ev[i].events & EPOLLPRI)
2082                         ast_set_flag(winner, AST_FLAG_EXCEPTION);
2083                 else
2084                         ast_clear_flag(winner, AST_FLAG_EXCEPTION);
2085                 winner->fdno = aed->which;
2086         }
2087
2088         if (*ms > 0) {
2089                 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
2090                 if (*ms < 0)
2091                         *ms = 0;
2092         }
2093
2094         return winner;
2095 }
2096
2097 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
2098                                         int *exception, int *outfd, int *ms)
2099 {
2100         /* Clear all provided values in one place. */
2101         if (outfd)
2102                 *outfd = -99999;
2103         if (exception)
2104                 *exception = 0;
2105
2106         /* If no epoll file descriptor is available resort to classic nandfds */
2107         if (!n || nfds || c[0]->epfd == -1)
2108                 return ast_waitfor_nandfds_classic(c, n, fds, nfds, exception, outfd, ms);
2109         else if (!nfds && n == 1)
2110                 return ast_waitfor_nandfds_simple(c[0], ms);
2111         else
2112                 return ast_waitfor_nandfds_complex(c, n, ms);
2113 }
2114 #endif
2115
2116 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
2117 {
2118         return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
2119 }
2120
2121 int ast_waitfor(struct ast_channel *c, int ms)
2122 {
2123         int oldms = ms; /* -1 if no timeout */
2124
2125         ast_waitfor_nandfds(&c, 1, NULL, 0, NULL, NULL, &ms);
2126         if ((ms < 0) && (oldms < 0))
2127                 ms = 0;
2128         return ms;
2129 }
2130
2131 /* XXX never to be called with ms = -1 */
2132 int ast_waitfordigit(struct ast_channel *c, int ms)
2133 {
2134         return ast_waitfordigit_full(c, ms, -1, -1);
2135 }
2136
2137 int ast_settimeout(struct ast_channel *c, int samples, int (*func)(const void *data), void *data)
2138 {
2139         int res = -1;
2140 #ifdef HAVE_ZAPTEL
2141         if (c->timingfd > -1) {
2142                 if (!func) {
2143                         samples = 0;
2144                         data = 0;
2145                 }
2146                 ast_debug(1, "Scheduling timer at %d sample intervals\n", samples);
2147                 res = ioctl(c->timingfd, ZT_TIMERCONFIG, &samples);
2148                 c->timingfunc = func;
2149                 c->timingdata = data;
2150         }
2151 #endif  
2152         return res;
2153 }
2154
2155 int ast_waitfordigit_full(struct ast_channel *c, int ms, int audiofd, int cmdfd)
2156 {
2157         /* Stop if we're a zombie or need a soft hangup */
2158         if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
2159                 return -1;
2160
2161         /* Only look for the end of DTMF, don't bother with the beginning and don't emulate things */
2162         ast_set_flag(c, AST_FLAG_END_DTMF_ONLY);
2163
2164         /* Wait for a digit, no more than ms milliseconds total. */
2165         
2166         while (ms) {
2167                 struct ast_channel *rchan;
2168                 int outfd=-1;
2169
2170                 errno = 0;
2171                 rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
2172                 
2173                 if (!rchan && outfd < 0 && ms) {
2174                         if (errno == 0 || errno == EINTR)
2175                                 continue;
2176                         ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
2177                         ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2178                         return -1;
2179                 } else if (outfd > -1) {
2180                         /* The FD we were watching has something waiting */
2181                         ast_log(LOG_WARNING, "The FD we were waiting for has something waiting. Waitfordigit returning numeric 1\n");
2182                         ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2183                         return 1;
2184                 } else if (rchan) {
2185                         int res;
2186                         struct ast_frame *f = ast_read(c);
2187                         if (!f)
2188                                 return -1;
2189
2190                         switch (f->frametype) {
2191                         case AST_FRAME_DTMF_BEGIN:
2192                                 break;
2193                         case AST_FRAME_DTMF_END:
2194                                 res = f->subclass;
2195                                 ast_frfree(f);
2196                                 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2197                                 return res;
2198                         case AST_FRAME_CONTROL:
2199                                 switch (f->subclass) {
2200                                 case AST_CONTROL_HANGUP:
2201                                         ast_frfree(f);
2202                                         ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2203                                         return -1;
2204                                 case AST_CONTROL_RINGING:
2205                                 case AST_CONTROL_ANSWER:
2206                                 case AST_CONTROL_SRCUPDATE:
2207                                         /* Unimportant */
2208                                         break;
2209                                 default:
2210                                         ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", f->subclass);
2211                                         break;
2212                                 }
2213                                 break;
2214                         case AST_FRAME_VOICE:
2215                                 /* Write audio if appropriate */
2216                                 if (audiofd > -1)
2217                                         write(audiofd, f->data, f->datalen);
2218                         default:
2219                                 /* Ignore */
2220                                 break;
2221                         }
2222                         ast_frfree(f);
2223                 }
2224         }
2225
2226         ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2227
2228         return 0; /* Time is up */
2229 }
2230
2231 static void send_dtmf_event(const struct ast_channel *chan, const char *direction, const char digit, const char *begin, const char *end)
2232 {
2233         manager_event(EVENT_FLAG_DTMF,
2234                         "DTMF",
2235                         "Channel: %s\r\n"
2236                         "Uniqueid: %s\r\n"
2237                         "Digit: %c\r\n"
2238                         "Direction: %s\r\n"
2239                         "Begin: %s\r\n"
2240                         "End: %s\r\n",
2241                         chan->name, chan->uniqueid, digit, direction, begin, end);
2242 }
2243
2244 static void ast_read_generator_actions(struct ast_channel *chan, struct ast_frame *f)
2245 {
2246         if (chan->generatordata &&  !ast_internal_timing_enabled(chan)) {
2247                 void *tmp = chan->generatordata;
2248                 int res;
2249
2250                 if (chan->timingfunc) {
2251                         if (option_debug > 1)
2252                                 ast_log(LOG_DEBUG, "Generator got voice, switching to phase locked mode\n");
2253                         ast_settimeout(chan, 0, NULL, NULL);
2254                 }
2255
2256                 chan->generatordata = NULL;     /* reset, to let writes go through */
2257                 res = chan->generator->generate(chan, tmp, f->datalen, f->samples);
2258                 chan->generatordata = tmp;
2259                 if (res) {
2260                         if (option_debug > 1)
2261                                 ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
2262                         ast_deactivate_generator(chan);
2263                 }
2264
2265         } else if (f->frametype == AST_FRAME_CNG) {
2266                 if (chan->generator && !chan->timingfunc && (chan->timingfd > -1)) {
2267                         if (option_debug > 1)
2268                                 ast_log(LOG_DEBUG, "Generator got CNG, switching to timed mode\n");
2269                         ast_settimeout(chan, 160, generator_force, chan);
2270                 }
2271         }
2272 }
2273
2274 static struct ast_frame *__ast_read(struct ast_channel *chan, int dropaudio)
2275 {
2276         struct ast_frame *f = NULL;     /* the return value */
2277         int blah;
2278         int prestate;
2279         int count = 0;
2280
2281         /* this function is very long so make sure there is only one return
2282          * point at the end (there are only two exceptions to this).
2283          */
2284         while(ast_channel_trylock(chan)) {
2285                 if(count++ > 10) 
2286                         /*cannot goto done since the channel is not locked*/
2287                         return &ast_null_frame;
2288                 usleep(1);
2289         }
2290
2291         if (chan->masq) {
2292                 if (ast_do_masquerade(chan))
2293                         ast_log(LOG_WARNING, "Failed to perform masquerade\n");
2294                 else
2295                         f =  &ast_null_frame;
2296                 goto done;
2297         }
2298
2299         /* Stop if we're a zombie or need a soft hangup */
2300         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2301                 if (chan->generator)
2302                         ast_deactivate_generator(chan);
2303                 goto done;
2304         }
2305         prestate = chan->_state;
2306
2307         if (!ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_EMULATE_DTMF | AST_FLAG_IN_DTMF) && 
2308             !ast_strlen_zero(chan->dtmfq) && 
2309                 (ast_tvzero(chan->dtmf_tv) || ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) > AST_MIN_DTMF_GAP) ) {
2310                 /* We have DTMF that has been deferred.  Return it now */
2311                 chan->dtmff.subclass = chan->dtmfq[0];
2312                 /* Drop first digit from the buffer */
2313                 memmove(chan->dtmfq, chan->dtmfq + 1, sizeof(chan->dtmfq) - 1);
2314                 f = &chan->dtmff;
2315                 if (ast_test_flag(chan, AST_FLAG_END_DTMF_ONLY)) {
2316                         ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass, chan->name);
2317                         chan->dtmff.frametype = AST_FRAME_DTMF_END;
2318                 } else {
2319                         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);
2320                         chan->dtmff.frametype = AST_FRAME_DTMF_BEGIN;
2321                         ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
2322                         chan->emulate_dtmf_digit = f->subclass;
2323                         chan->emulate_dtmf_duration = AST_DEFAULT_EMULATE_DTMF_DURATION;
2324                 }
2325                 chan->dtmf_tv = ast_tvnow();
2326                 goto done;
2327         }
2328         
2329         /* Read and ignore anything on the alertpipe, but read only
2330            one sizeof(blah) per frame that we send from it */
2331         if (chan->alertpipe[0] > -1)
2332                 read(chan->alertpipe[0], &blah, sizeof(blah));
2333
2334 #ifdef HAVE_ZAPTEL
2335         if (chan->timingfd > -1 && chan->fdno == AST_TIMING_FD && ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
2336                 int res;
2337
2338                 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
2339                 blah = -1;
2340                 /* IF we can't get event, assume it's an expired as-per the old interface */
2341                 res = ioctl(chan->timingfd, ZT_GETEVENT, &blah);
2342                 if (res)
2343                         blah = ZT_EVENT_TIMER_EXPIRED;
2344
2345                 if (blah == ZT_EVENT_TIMER_PING) {
2346                         if (AST_LIST_EMPTY(&chan->readq) || !AST_LIST_NEXT(AST_LIST_FIRST(&chan->readq), frame_list)) {
2347                                 /* Acknowledge PONG unless we need it again */
2348                                 if (ioctl(chan->timingfd, ZT_TIMERPONG, &blah)) {
2349                                         ast_log(LOG_WARNING, "Failed to pong timer on '%s': %s\n", chan->name, strerror(errno));
2350                                 }
2351                         }
2352                 } else if (blah == ZT_EVENT_TIMER_EXPIRED) {
2353                         ioctl(chan->timingfd, ZT_TIMERACK, &blah);
2354                         if (chan->timingfunc) {
2355                                 /* save a copy of func/data before unlocking the channel */
2356                                 int (*func)(const void *) = chan->timingfunc;
2357                                 void *data = chan->timingdata;
2358                                 ast_channel_unlock(chan);
2359                                 func(data);
2360                         } else {
2361                                 blah = 0;
2362                                 ioctl(chan->timingfd, ZT_TIMERCONFIG, &blah);
2363                                 chan->timingdata = NULL;
2364                                 ast_channel_unlock(chan);
2365                         }
2366                         /* cannot 'goto done' because the channel is already unlocked */
2367                         return &ast_null_frame;
2368                 } else
2369                         ast_log(LOG_NOTICE, "No/unknown event '%d' on timer for '%s'?\n", blah, chan->name);
2370         } else
2371 #endif
2372         if (chan->fds[AST_GENERATOR_FD] > -1 && chan->fdno == AST_GENERATOR_FD) {
2373                 /* if the AST_GENERATOR_FD is set, call the generator with args
2374                  * set to -1 so it can do whatever it needs to.
2375                  */
2376                 void *tmp = chan->generatordata;
2377                 chan->generatordata = NULL;     /* reset to let ast_write get through */
2378                 chan->generator->generate(chan, tmp, -1, -1);
2379                 chan->generatordata = tmp;
2380                 f = &ast_null_frame;
2381                 goto done;
2382         }
2383
2384         /* Check for pending read queue */
2385         if (!AST_LIST_EMPTY(&chan->readq)) {
2386                 f = AST_LIST_REMOVE_HEAD(&chan->readq, frame_list);
2387                 /* Interpret hangup and return NULL */
2388                 /* XXX why not the same for frames from the channel ? */
2389                 if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP) {
2390                         ast_frfree(f);
2391                         f = NULL;
2392                 }
2393         } else {
2394                 chan->blocker = pthread_self();
2395                 if (ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
2396                         if (chan->tech->exception)
2397                                 f = chan->tech->exception(chan);
2398                         else {
2399                                 ast_log(LOG_WARNING, "Exception flag set on '%s', but no exception handler\n", chan->name);
2400                                 f = &ast_null_frame;
2401                         }
2402                         /* Clear the exception flag */
2403                         ast_clear_flag(chan, AST_FLAG_EXCEPTION);
2404                 } else if (chan->tech->read)
2405                         f = chan->tech->read(chan);
2406                 else
2407                         ast_log(LOG_WARNING, "No read routine on channel %s\n", chan->name);
2408         }
2409
2410         if (f) {
2411                 /* if the channel driver returned more than one frame, stuff the excess
2412                    into the readq for the next ast_read call (note that we can safely assume
2413                    that the readq is empty, because otherwise we would not have called into
2414                    the channel driver and f would be only a single frame)
2415                 */
2416                 if (AST_LIST_NEXT(f, frame_list)) {
2417                         AST_LIST_HEAD_SET_NOLOCK(&chan->readq, AST_LIST_NEXT(f, frame_list));
2418                         AST_LIST_NEXT(f, frame_list) = NULL;
2419                 }
2420
2421                 switch (f->frametype) {
2422                 case AST_FRAME_CONTROL:
2423                         if (f->subclass == AST_CONTROL_ANSWER) {
2424                                 if (!ast_test_flag(chan, AST_FLAG_OUTGOING)) {
2425                                         ast_debug(1, "Ignoring answer on an inbound call!\n");
2426                                         ast_frfree(f);
2427                                         f = &ast_null_frame;
2428                                 } else if (prestate == AST_STATE_UP) {
2429                                         ast_debug(1, "Dropping duplicate answer!\n");
2430                                         ast_frfree(f);
2431                                         f = &ast_null_frame;
2432                                 } else {
2433                                         /* Answer the CDR */
2434                                         ast_setstate(chan, AST_STATE_UP);
2435                                         if (!chan->cdr) { /* up till now, this insertion hasn't been done. Therefore,
2436                                                                                  to keep from throwing off the basic order of the universe,
2437                                                                                  we will try to keep this cdr from getting posted. */
2438                                                 chan->cdr = ast_cdr_alloc();
2439                                                 ast_cdr_init(chan->cdr, chan);
2440                                                 ast_cdr_start(chan->cdr);
2441                                         }
2442                                         
2443                                         ast_cdr_answer(chan->cdr);
2444                                 }
2445                         }
2446                         break;
2447                 case AST_FRAME_DTMF_END:
2448                         send_dtmf_event(chan, "Received", f->subclass, "No", "Yes");
2449                         ast_log(LOG_DTMF, "DTMF end '%c' received on %s, duration %ld ms\n", f->subclass, chan->name, f->len);
2450                         /* Queue it up if DTMF is deffered, or if DTMF emulation is forced.
2451                          * However, only let emulation be forced if the other end cares about BEGIN frames */
2452                         if ( ast_test_flag(chan, AST_FLAG_DEFER_DTMF) ||
2453                                 (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !ast_test_flag(chan, AST_FLAG_END_DTMF_ONLY)) ) {
2454                                 if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2) {
2455                                         ast_log(LOG_DTMF, "DTMF end '%c' put into dtmf queue on %s\n", f->subclass, chan->name);
2456                                         chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
2457                                 } else
2458                                         ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
2459                                 ast_frfree(f);
2460                                 f = &ast_null_frame;
2461                         } else if (!ast_test_flag(chan, AST_FLAG_IN_DTMF | AST_FLAG_END_DTMF_ONLY)) {
2462                                 if (!ast_tvzero(chan->dtmf_tv) && 
2463                                     ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) < AST_MIN_DTMF_GAP) {
2464                                         /* If it hasn't been long enough, defer this digit */
2465                                         if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2) {
2466                                                 ast_log(LOG_DTMF, "DTMF end '%c' put into dtmf queue on %s\n", f->subclass, chan->name);
2467                                                 chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
2468                                         } else
2469                                                 ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
2470                                         ast_frfree(f);
2471                                         f = &ast_null_frame;
2472                                 } else {
2473                                         /* There was no begin, turn this into a begin and send the end later */
2474                                         f->frametype = AST_FRAME_DTMF_BEGIN;
2475                                         ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
2476                                         chan->emulate_dtmf_digit = f->subclass;
2477                                         chan->dtmf_tv = ast_tvnow();
2478                                         if (f->len) {
2479                                                 if (f->len > AST_MIN_DTMF_DURATION)
2480                                                         chan->emulate_dtmf_duration = f->len;
2481                                                 else 
2482                                                         chan->emulate_dtmf_duration = AST_MIN_DTMF_DURATION;
2483                                         } else
2484                                                 chan->emulate_dtmf_duration = AST_DEFAULT_EMULATE_DTMF_DURATION;
2485                                         ast_log(LOG_DTMF, "DTMF begin emulation of '%c' with duration %u queued on %s\n", f->subclass, chan->emulate_dtmf_duration, chan->name);
2486                                 }
2487                                 if (chan->audiohooks) {
2488                                         struct ast_frame *old_frame = f;
2489                                         /*!
2490                                          * \todo XXX It is possible to write a digit to the audiohook twice
2491                                          * if the digit was originally read while the channel was in autoservice. */
2492                                         f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
2493                                         if (old_frame != f)
2494                                                 ast_frfree(old_frame);
2495                                 }
2496                         } else {
2497                                 struct timeval now = ast_tvnow();
2498                                 if (ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
2499                                         ast_log(LOG_DTMF, "DTMF end accepted with begin '%c' on %s\n", f->subclass, chan->name);
2500                                         ast_clear_flag(chan, AST_FLAG_IN_DTMF);
2501                                         if (!f->len)
2502                                                 f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
2503                                 } else if (!f->len) {
2504                                         ast_log(LOG_DTMF, "DTMF end accepted without begin '%c' on %s\n", f->subclass, chan->name);
2505                                         f->len = AST_MIN_DTMF_DURATION;
2506                                 }
2507                                 if (f->len < AST_MIN_DTMF_DURATION) {
2508                                         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);
2509                                         ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
2510                                         chan->emulate_dtmf_digit = f->subclass;
2511                                         chan->emulate_dtmf_duration = AST_MIN_DTMF_DURATION - f->len;
2512                                         ast_frfree(f);
2513                                         f = &ast_null_frame;
2514                                 } else {
2515                                         ast_log(LOG_DTMF, "DTMF end passthrough '%c' on %s\n", f->subclass, chan->name);
2516                                         chan->dtmf_tv = now;
2517                                 }
2518                                 if (chan->audiohooks) {
2519                                         struct ast_frame *old_frame = f;
2520                                         f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
2521                                         if (old_frame != f)
2522                                                 ast_frfree(old_frame);
2523                                 }
2524                         }
2525                         break;
2526                 case AST_FRAME_DTMF_BEGIN:
2527                         send_dtmf_event(chan, "Received", f->subclass, "Yes", "No");
2528                         ast_log(LOG_DTMF, "DTMF begin '%c' received on %s\n", f->subclass, chan->name);
2529                         if ( ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_END_DTMF_ONLY | AST_FLAG_EMULATE_DTMF) || 
2530                             (!ast_tvzero(chan->dtmf_tv) && 
2531                               ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) < AST_MIN_DTMF_GAP) ) {
2532                                 ast_log(LOG_DTMF, "DTMF begin ignored '%c' on %s\n", f->subclass, chan->name);
2533                                 ast_frfree(f);
2534                                 f = &ast_null_frame;
2535                         } else {
2536                                 ast_set_flag(chan, AST_FLAG_IN_DTMF);
2537                                 chan->dtmf_tv = ast_tvnow();
2538                                 ast_log(LOG_DTMF, "DTMF begin passthrough '%c' on %s\n", f->subclass, chan->name);
2539                         }
2540                         break;
2541                 case AST_FRAME_NULL:
2542                         /* The EMULATE_DTMF flag must be cleared here as opposed to when the duration
2543                          * is reached , because we want to make sure we pass at least one
2544                          * voice frame through before starting the next digit, to ensure a gap
2545                          * between DTMF digits. */
2546                         if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF)) {
2547                                 struct timeval now = ast_tvnow();
2548                                 if (!chan->emulate_dtmf_duration) {
2549                                         ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
2550                                         chan->emulate_dtmf_digit = 0;
2551                                 } else if (ast_tvdiff_ms(now, chan->dtmf_tv) >= chan->emulate_dtmf_duration) {
2552                                         chan->emulate_dtmf_duration = 0;
2553                                         ast_frfree(f);
2554                                         f = &chan->dtmff;
2555                                         f->frametype = AST_FRAME_DTMF_END;
2556                                         f->subclass = chan->emulate_dtmf_digit;
2557                                         f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
2558                                         chan->dtmf_tv = now;
2559                                         ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
2560                                         chan->emulate_dtmf_digit = 0;
2561                                         ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass, chan->name);
2562                                 }
2563                         }
2564                         break;
2565                 case AST_FRAME_VOICE:
2566                         /* The EMULATE_DTMF flag must be cleared here as opposed to when the duration
2567                          * is reached , because we want to make sure we pass at least one
2568                          * voice frame through before starting the next digit, to ensure a gap
2569                          * between DTMF digits. */
2570                         if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !chan->emulate_dtmf_duration) {
2571                                 ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
2572                                 chan->emulate_dtmf_digit = 0;
2573                         }
2574
2575                         if (dropaudio || ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
2576                                 if (dropaudio)
2577                                         ast_read_generator_actions(chan, f);
2578                                 ast_frfree(f);
2579                                 f = &ast_null_frame;
2580                         }
2581
2582                         if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
2583                                 struct timeval now = ast_tvnow();
2584                                 if (ast_tvdiff_ms(now, chan->dtmf_tv) >= chan->emulate_dtmf_duration) {
2585                                         chan->emulate_dtmf_duration = 0;
2586                                         ast_frfree(f);
2587                                         f = &chan->dtmff;
2588                                         f->frametype = AST_FRAME_DTMF_END;
2589                                         f->subclass = chan->emulate_dtmf_digit;
2590                                         f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
2591                                         chan->dtmf_tv = now;
2592                                         if (chan->audiohooks) {
2593                                                 struct ast_frame *old_frame = f;
2594                                                 f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
2595                                                 if (old_frame != f)
2596                                                         ast_frfree(old_frame);
2597                                         }
2598                                         ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass, chan->name);
2599                                 } else {
2600                                         /* Drop voice frames while we're still in the middle of the digit */
2601                                         ast_frfree(f);
2602                                         f = &ast_null_frame;
2603                                 }
2604                         } else if ((f->frametype == AST_FRAME_VOICE) && !(f->subclass & chan->nativeformats)) {
2605                                 /* This frame can't be from the current native formats -- drop it on the
2606                                    floor */
2607                                 ast_log(LOG_NOTICE, "Dropping incompatible voice frame on %s of format %s since our native format has changed to %s\n",
2608                                         chan->name, ast_getformatname(f->subclass), ast_getformatname(chan->nativeformats));
2609                                 ast_frfree(f);
2610                                 f = &ast_null_frame;
2611                         } else if ((f->frametype == AST_FRAME_VOICE)) {
2612                                 /* Send frame to audiohooks if present */
2613                                 if (chan->audiohooks) {
2614                                         struct ast_frame *old_frame = f;
2615                                         f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
2616                                         if (old_frame != f)
2617                                                 ast_frfree(old_frame);
2618                                 }
2619                                 if (chan->monitor && chan->monitor->read_stream ) {
2620                                         /* XXX what does this do ? */
2621 #ifndef MONITOR_CONSTANT_DELAY
2622                                         int jump = chan->outsmpl - chan->insmpl - 4 * f->samples;
2623                                         if (jump >= 0) {
2624                                                 jump = chan->outsmpl - chan->insmpl;
2625                                                 if (ast_seekstream(chan->monitor->read_stream, jump, SEEK_FORCECUR) == -1)
2626                                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
2627                                                 chan->insmpl += jump + f->samples;
2628                                         } else
2629                                                 chan->insmpl+= f->samples;
2630 #else
2631                                         int jump = chan->outsmpl - chan->insmpl;
2632                                         if (jump - MONITOR_DELAY >= 0) {
2633                                                 if (ast_seekstream(chan->monitor->read_stream, jump - f->samples, SEEK_FORCECUR) == -1)
2634                                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
2635                                                 chan->insmpl += jump;
2636                                         } else
2637                                                 chan->insmpl += f->samples;
2638 #endif
2639                                         if (chan->monitor->state == AST_MONITOR_RUNNING) {
2640                                                 if (ast_writestream(chan->monitor->read_stream, f) < 0)
2641                                                         ast_log(LOG_WARNING, "Failed to write data to channel monitor read stream\n");
2642                                         }
2643                                 }
2644
2645                                 if (chan->readtrans && (f = ast_translate(chan->readtrans, f, 1)) == NULL)
2646                                         f = &ast_null_frame;
2647                                 else
2648                                         /* Run generator sitting on the line if timing device not available
2649                                          * and synchronous generation of outgoing frames is necessary       */
2650                                         ast_read_generator_actions(chan, f);
2651                         }
2652                 default:
2653                         /* Just pass it on! */
2654                         break;
2655                 }
2656         } else {
2657                 /* Make sure we always return NULL in the future */
2658                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
2659                 if (chan->generator)
2660                         ast_deactivate_generator(chan);
2661                 /* End the CDR if appropriate */
2662                 if (chan->cdr)
2663                         ast_cdr_end(chan->cdr);
2664         }
2665
2666         /* High bit prints debugging */
2667         if (chan->fin & DEBUGCHAN_FLAG)
2668                 ast_frame_dump(chan->name, f, "<<");
2669         chan->fin = FRAMECOUNT_INC(chan->fin);
2670
2671 done:
2672         if (chan->music_state && chan->generator && chan->generator->digit && f && f->frametype == AST_FRAME_DTMF_END)
2673                 chan->generator->digit(chan, f->subclass);
2674
2675         ast_channel_unlock(chan);
2676         return f;
2677 }
2678
2679 int ast_internal_timing_enabled(struct ast_channel *chan)
2680 {
2681         int ret = ast_opt_internal_timing && chan->timingfd > -1;
2682         ast_debug(5, "Internal timing is %s (option_internal_timing=%d chan->timingfd=%d)\n", ret? "enabled": "disabled", ast_opt_internal_timing, chan->timingfd);
2683         return ret;
2684 }
2685
2686 struct ast_frame *ast_read(struct ast_channel *chan)
2687 {
2688         return __ast_read(chan, 0);
2689 }
2690
2691 struct ast_frame *ast_read_noaudio(struct ast_channel *chan)
2692 {
2693         return __ast_read(chan, 1);
2694 }
2695
2696 int ast_indicate(struct ast_channel *chan, int condition)
2697 {
2698         return ast_indicate_data(chan, condition, NULL, 0);
2699 }
2700
2701 int ast_indicate_data(struct ast_channel *chan, int condition, const void *data, size_t datalen)
2702 {
2703         int res = -1;
2704
2705         ast_channel_lock(chan);
2706         /* Stop if we're a zombie or need a soft hangup */
2707         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2708                 ast_channel_unlock(chan);
2709                 return -1;
2710         }
2711         if (chan->tech->indicate)
2712                 res = chan->tech->indicate(chan, condition, data, datalen);
2713         ast_channel_unlock(chan);
2714         if (!chan->tech->indicate || res) {
2715                 /*
2716                  * Device does not support (that) indication, lets fake
2717                  * it by doing our own tone generation. (PM2002)
2718                  */
2719                 if (condition < 0)
2720                         ast_playtones_stop(chan);
2721                 else {
2722                         const struct ind_tone_zone_sound *ts = NULL;
2723                         switch (condition) {
2724                         case AST_CONTROL_RINGING:
2725                                 ts = ast_get_indication_tone(chan->zone, "ring");
2726                                 break;
2727                         case AST_CONTROL_BUSY:
2728                                 ts = ast_get_indication_tone(chan->zone, "busy");
2729                                 break;
2730                         case AST_CONTROL_CONGESTION:
2731                                 ts = ast_get_indication_tone(chan->zone, "congestion");
2732                                 break;
2733                         }
2734                         if (ts && ts->data[0]) {
2735                                 ast_debug(1, "Driver for channel '%s' does not support indication %d, emulating it\n", chan->name, condition);
2736                                 ast_playtones_start(chan,0,ts->data, 1);
2737                                 res = 0;
2738                                 chan->visible_indication = condition;
2739                         } else if (condition == AST_CONTROL_PROGRESS) {
2740                                 /* ast_playtones_stop(chan); */
2741                         } else if (condition == AST_CONTROL_PROCEEDING) {
2742                                 /* Do nothing, really */
2743                         } else if (condition == AST_CONTROL_HOLD) {
2744                                 /* Do nothing.... */
2745                         } else if (condition == AST_CONTROL_UNHOLD) {
2746                                 /* Do nothing.... */
2747                         } else if (condition == AST_CONTROL_VIDUPDATE) {
2748                                 /* Do nothing.... */
2749                         } else if (condition == AST_CONTROL_SRCUPDATE) {
2750                                 /* Do nothing... */
2751                         } else {
2752                                 /* not handled */
2753                                 ast_log(LOG_WARNING, "Unable to handle indication %d for '%s'\n", condition, chan->name);
2754                                 res = -1;
2755                         }
2756                 }
2757         } else
2758                 chan->visible_indication = condition;
2759
2760         return res;
2761 }
2762
2763 int ast_recvchar(struct ast_channel *chan, int timeout)
2764 {
2765         int c;
2766         char *buf = ast_recvtext(chan, timeout);
2767         if (buf == NULL)
2768                 return -1;      /* error or timeout */
2769         c = *(unsigned char *)buf;
2770         ast_free(buf);
2771         return c;
2772 }
2773
2774 char *ast_recvtext(struct ast_channel *chan, int timeout)
2775 {
2776         int res, done = 0;
2777         char *buf = NULL;
2778         
2779         while (!done) {
2780                 struct ast_frame *f;
2781                 if (ast_check_hangup(chan))
2782                         break;
2783                 res = ast_waitfor(chan, timeout);
2784                 if (res <= 0) /* timeout or error */
2785                         break;
2786                 timeout = res;  /* update timeout */
2787                 f = ast_read(chan);
2788                 if (f == NULL)
2789                         break; /* no frame */
2790                 if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP)
2791                         done = 1;       /* force a break */
2792                 else if (f->frametype == AST_FRAME_TEXT) {              /* what we want */
2793                         buf = ast_strndup((char *) f->data, f->datalen);        /* dup and break */
2794                         done = 1;
2795                 }
2796                 ast_frfree(f);
2797         }
2798         return buf;
2799 }
2800
2801 int ast_sendtext(struct ast_channel *chan, const char *text)
2802 {
2803         int res = 0;
2804         /* Stop if we're a zombie or need a soft hangup */
2805         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
2806                 return -1;
2807         CHECK_BLOCKING(chan);
2808         if (chan->tech->send_text)
2809                 res = chan->tech->send_text(chan, text);
2810         ast_clear_flag(chan, AST_FLAG_BLOCKING);
2811         return res;
2812 }
2813
2814 int ast_senddigit_begin(struct ast_channel *chan, char digit)
2815 {
2816         /* Device does not support DTMF tones, lets fake
2817          * it by doing our own generation. */
2818         static const char* dtmf_tones[] = {
2819                 "941+1336", /* 0 */
2820                 "697+1209", /* 1 */
2821                 "697+1336", /* 2 */
2822                 "697+1477", /* 3 */
2823                 "770+1209", /* 4 */
2824                 "770+1336", /* 5 */
2825                 "770+1477", /* 6 */
2826                 "852+1209", /* 7 */
2827                 "852+1336", /* 8 */
2828                 "852+1477", /* 9 */
2829                 "697+1633", /* A */
2830                 "770+1633", /* B */
2831                 "852+1633", /* C */
2832                 "941+1633", /* D */
2833                 "941+1209", /* * */
2834                 "941+1477"  /* # */
2835         };
2836
2837         if (!chan->tech->send_digit_begin)
2838                 return 0;
2839
2840         if (!chan->tech->send_digit_begin(chan, digit))
2841                 return 0;
2842
2843         if (digit >= '0' && digit <='9')
2844                 ast_playtones_start(chan, 0, dtmf_tones[digit-'0'], 0);
2845         else if (digit >= 'A' && digit <= 'D')
2846                 ast_playtones_start(chan, 0, dtmf_tones[digit-'A'+10], 0);
2847         else if (digit == '*')
2848                 ast_playtones_start(chan, 0, dtmf_tones[14], 0);
2849         else if (digit == '#')
2850                 ast_playtones_start(chan, 0, dtmf_tones[15], 0);
2851         else {
2852                 /* not handled */
2853                 ast_debug(1, "Unable to generate DTMF tone '%c' for '%s'\n", digit, chan->name);
2854         }
2855
2856         return 0;
2857 }
2858
2859 int ast_senddigit_end(struct ast_channel *chan, char digit, unsigned int duration)
2860 {
2861         int res = -1;
2862
2863         if (chan->tech->send_digit_end)
2864                 res = chan->tech->send_digit_end(chan, digit, duration);
2865
2866         if (res && chan->generator)
2867                 ast_playtones_stop(chan);
2868         
2869         return 0;
2870 }
2871
2872 int ast_senddigit(struct ast_channel *chan, char digit, unsigned int duration)
2873 {
2874         if (chan->tech->send_digit_begin) {
2875                 ast_senddigit_begin(chan, digit);
2876                 ast_safe_sleep(chan, (duration >= AST_DEFAULT_EMULATE_DTMF_DURATION ? duration : AST_DEFAULT_EMULATE_DTMF_DURATION));
2877         }
2878         
2879         return ast_senddigit_end(chan, digit, (duration >= AST_DEFAULT_EMULATE_DTMF_DURATION ? duration : AST_DEFAULT_EMULATE_DTMF_DURATION));
2880 }
2881
2882 int ast_prod(struct ast_channel *chan)
2883 {
2884         struct ast_frame a = { AST_FRAME_VOICE };
2885         char nothing[128];
2886
2887         /* Send an empty audio frame to get things moving */
2888         if (chan->_state != AST_STATE_UP) {
2889                 ast_debug(1, "Prodding channel '%s'\n", chan->name);
2890                 a.subclass = chan->rawwriteformat;
2891                 a.data = nothing + AST_FRIENDLY_OFFSET;
2892                 a.src = "ast_prod";
2893                 if (ast_write(chan, &a))
2894                         ast_log(LOG_WARNING, "Prodding channel '%s' failed\n", chan->name);
2895         }
2896         return 0;
2897 }
2898
2899 int ast_write_video(struct ast_channel *chan, struct ast_frame *fr)
2900 {
2901         int res;
2902         if (!chan->tech->write_video)
2903                 return 0;
2904         res = ast_write(chan, fr);
2905         if (!res)
2906                 res = 1;
2907         return res;
2908 }
2909
2910 int ast_write(struct ast_channel *chan, struct ast_frame *fr)
2911 {
2912         int res = -1;
2913         struct ast_frame *f = NULL, *f2 = NULL;
2914         int count = 0;
2915
2916         /*Deadlock avoidance*/
2917         while(ast_channel_trylock(chan)) {
2918                 /*cannot goto done since the channel is not locked*/
2919                 if(count++ > 10) {
2920                         ast_debug(1, "Deadlock avoided for write to channel '%s'\n", chan->name);
2921                         return 0;
2922                 }
2923                 usleep(1);
2924         }
2925         /* Stop if we're a zombie or need a soft hangup */
2926         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
2927                 goto done;
2928
2929         /* Handle any pending masquerades */
2930         if (chan->masq && ast_do_masquerade(chan)) {
2931                 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
2932                 goto done;
2933         }
2934         if (chan->masqr) {
2935                 res = 0;        /* XXX explain, why 0 ? */
2936                 goto done;
2937         }
2938         if (chan->generatordata) {
2939                 if (ast_test_flag(chan, AST_FLAG_WRITE_INT))
2940                         ast_deactivate_generator(chan);
2941                 else {
2942                         if (fr->frametype == AST_FRAME_DTMF_END) {
2943                                 /* There is a generator running while we're in the middle of a digit.
2944                                  * It's probably inband DTMF, so go ahead and pass it so it can
2945                                  * stop the generator */
2946                                 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2947                                 ast_channel_unlock(chan);
2948                                 res = ast_senddigit_end(chan, fr->subclass, fr->len);
2949                                 ast_channel_lock(chan);
2950                                 CHECK_BLOCKING(chan);
2951                         } else if (fr->frametype == AST_FRAME_CONTROL && fr->subclass == AST_CONTROL_UNHOLD) {
2952                                 /* This is a side case where Echo is basically being called and the person put themselves on hold and took themselves off hold */
2953                                 res = (chan->tech->indicate == NULL) ? 0 :
2954                                         chan->tech->indicate(chan, fr->subclass, fr->data, fr->datalen);
2955                         }
2956                         res = 0;        /* XXX explain, why 0 ? */
2957                         goto done;
2958                 }
2959         }
2960         /* High bit prints debugging */
2961         if (chan->fout & DEBUGCHAN_FLAG)
2962                 ast_frame_dump(chan->name, fr, ">>");
2963         CHECK_BLOCKING(chan);
2964         switch (fr->frametype) {
2965         case AST_FRAME_CONTROL:
2966                 res = (chan->tech->indicate == NULL) ? 0 :
2967                         chan->tech->indicate(chan, fr->subclass, fr->data, fr->datalen);
2968                 break;
2969         case AST_FRAME_DTMF_BEGIN:
2970                 if (chan->audiohooks) {
2971                         struct ast_frame *old_frame = fr;
2972                         fr = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_WRITE, fr);
2973                         if (old_frame != fr)
2974                                 f = fr;
2975                 }
2976                 send_dtmf_event(chan, "Sent", fr->subclass, "Yes", "No");
2977                 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2978                 ast_channel_unlock(chan);
2979                 res = ast_senddigit_begin(chan, fr->subclass);
2980                 ast_channel_lock(chan);
2981                 CHECK_BLOCKING(chan);
2982                 break;
2983         case AST_FRAME_DTMF_END:
2984                 if (chan->audiohooks) {
2985                         struct ast_frame *old_frame = fr;
2986                         fr = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_WRITE, fr);
2987                         if (old_frame != fr)
2988                                 f = fr;
2989                 }
2990                 send_dtmf_event(chan, "Sent", fr->subclass, "No", "Yes");
2991                 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2992                 ast_channel_unlock(chan);
2993                 res = ast_senddigit_end(chan, fr->subclass, fr->len);
2994                 ast_channel_lock(chan);
2995                 CHECK_BLOCKING(chan);
2996                 break;
2997         case AST_FRAME_TEXT:
2998                 if (fr->subclass == AST_FORMAT_T140) {
2999                         res = (chan->tech->write_text == NULL) ? 0 :
3000                                 chan->tech->write_text(chan, fr);
3001                 } else {
3002                         res = (chan->tech->send_text == NULL) ? 0 :
3003                                 chan->tech->send_text(chan, (char *) fr->data);
3004                 }
3005                 break;
3006         case AST_FRAME_HTML:
3007                 res = (chan->tech->send_html == NULL) ? 0 :
3008                         chan->tech->send_html(chan, fr->subclass, (char *) fr->data, fr->datalen);
3009                 break;
3010         case AST_FRAME_VIDEO:
3011                 /* XXX Handle translation of video codecs one day XXX */
3012                 res = (chan->tech->write_video == NULL) ? 0 :
3013                         chan->tech->write_video(chan, fr);
3014                 break;
3015         case AST_FRAME_MODEM:
3016                 res = (chan->tech->write == NULL) ? 0 :
3017                         chan->tech->write(chan, fr);
3018                 break;
3019         case AST_FRAME_VOICE:
3020                 if (chan->tech->write == NULL)
3021                         break;  /*! \todo XXX should return 0 maybe ? */
3022
3023                 /* If audiohooks are present, write the frame out */
3024                 if (chan->audiohooks) {
3025                         struct ast_frame *old_frame = fr;
3026                         fr = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_WRITE, fr);
3027                         if (old_frame != fr)
3028                                 f2 = fr;
3029                 }
3030
3031                 /* If the frame is in the raw write format, then it's easy... just use the frame - otherwise we will have to translate */
3032                 if (fr->subclass == chan->rawwriteformat)
3033                         f = fr;
3034                 else
3035                         f = (chan->writetrans) ? ast_translate(chan->writetrans, fr, 0) : fr;
3036
3037                 if (!f) {
3038                         res = 0;
3039                         break;
3040                 }
3041
3042                 /* If Monitor is running on this channel, then we have to write frames out there too */
3043                 if (chan->monitor && chan->monitor->write_stream) {
3044                         /* XXX must explain this code */
3045 #ifndef MONITOR_CONSTANT_DELAY
3046                         int jump = chan->insmpl - chan->outsmpl - 4 * f->samples;
3047                         if (jump >= 0) {
3048                                 jump = chan->insmpl - chan->outsmpl;
3049                                 if (ast_seekstream(chan->monitor->write_stream, jump, SEEK_FORCECUR) == -1)
3050                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
3051                                 chan->outsmpl += jump + f->samples;
3052                         } else
3053                                 chan->outsmpl += f->samples;
3054 #else
3055                         int jump = chan->insmpl - chan->outsmpl;
3056                         if (jump - MONITOR_DELAY >= 0) {
3057                                 if (ast_seekstream(chan->monitor->write_stream, jump - f->samples, SEEK_FORCECUR) == -1)
3058                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
3059                                 chan->outsmpl += jump;
3060                         } else
3061                                 chan->outsmpl += f->samples;
3062 #endif
3063                         if (chan->monitor->state == AST_MONITOR_RUNNING) {
3064                                 if (ast_writestream(chan->monitor->write_stream, f) < 0)
3065                                         ast_log(LOG_WARNING, "Failed to write data to channel monitor write stream\n");
3066                         }
3067                 }
3068
3069                 if (f) 
3070                         res = chan->tech->write(chan,f);
3071                 else
3072                         res = 0;
3073                 break;
3074         case AST_FRAME_NULL:
3075         case AST_FRAME_IAX:
3076                 /* Ignore these */
3077                 res = 0;
3078                 break;
3079         default:
3080                 /* At this point, fr is the incoming frame and f is NULL.  Channels do
3081                  * not expect to get NULL as a frame pointer and will segfault.  Hence,
3082