Context tracing for channels
[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;
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;
1786
1787         sz = n * AST_MAX_FDS + nfds;
1788         pfds = alloca(sizeof(*pfds) * sz);
1789         fdmap = alloca(sizeof(*fdmap) * sz);
1790
1791         if (outfd)
1792                 *outfd = -99999;
1793         if (exception)
1794                 *exception = 0;
1795         
1796         /* Perform any pending masquerades */
1797         for (x = 0; x < n; x++) {
1798                 ast_channel_lock(c[x]);
1799                 if (c[x]->masq && ast_do_masquerade(c[x])) {
1800                         ast_log(LOG_WARNING, "Masquerade failed\n");
1801                         *ms = -1;
1802                         ast_channel_unlock(c[x]);
1803                         return NULL;
1804                 }
1805                 if (c[x]->whentohangup) {
1806                         if (!whentohangup)
1807                                 time(&now);
1808                         diff = c[x]->whentohangup - now;
1809                         if (diff < 1) {
1810                                 /* Should already be hungup */
1811                                 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1812                                 ast_channel_unlock(c[x]);
1813                                 return c[x];
1814                         }
1815                         if (!whentohangup || (diff < whentohangup))
1816                                 whentohangup = diff;
1817                 }
1818                 ast_channel_unlock(c[x]);
1819         }
1820         /* Wait full interval */
1821         rms = *ms;
1822         if (whentohangup) {
1823                 rms = whentohangup * 1000;              /* timeout in milliseconds */
1824                 if (*ms >= 0 && *ms < rms)              /* original *ms still smaller */
1825                         rms =  *ms;
1826         }
1827         /*
1828          * Build the pollfd array, putting the channels' fds first,
1829          * followed by individual fds. Order is important because
1830          * individual fd's must have priority over channel fds.
1831          */
1832         max = 0;
1833         for (x = 0; x < n; x++) {
1834                 for (y = 0; y < AST_MAX_FDS; y++) {
1835                         fdmap[max].fdno = y;  /* fd y is linked to this pfds */
1836                         fdmap[max].chan = x;  /* channel x is linked to this pfds */
1837                         max += ast_add_fd(&pfds[max], c[x]->fds[y]);
1838                 }
1839                 CHECK_BLOCKING(c[x]);
1840         }
1841         /* Add the individual fds */
1842         for (x = 0; x < nfds; x++) {
1843                 fdmap[max].chan = -1;
1844                 max += ast_add_fd(&pfds[max], fds[x]);
1845         }
1846
1847         if (*ms > 0)
1848                 start = ast_tvnow();
1849         
1850         if (sizeof(int) == 4) { /* XXX fix timeout > 600000 on linux x86-32 */
1851                 do {
1852                         int kbrms = rms;
1853                         if (kbrms > 600000)
1854                                 kbrms = 600000;
1855                         res = poll(pfds, max, kbrms);
1856                         if (!res)
1857                                 rms -= kbrms;
1858                 } while (!res && (rms > 0));
1859         } else {
1860                 res = poll(pfds, max, rms);
1861         }
1862         for (x = 0; x < n; x++)
1863                 ast_clear_flag(c[x], AST_FLAG_BLOCKING);
1864         if (res < 0) { /* Simulate a timeout if we were interrupted */
1865                 if (errno != EINTR)
1866                         *ms = -1;
1867                 return NULL;
1868         }
1869         if (whentohangup) {   /* if we have a timeout, check who expired */
1870                 time(&now);
1871                 for (x = 0; x < n; x++) {
1872                         if (c[x]->whentohangup && now >= c[x]->whentohangup) {
1873                                 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1874                                 if (winner == NULL)
1875                                         winner = c[x];
1876                         }
1877                 }
1878         }
1879         if (res == 0) { /* no fd ready, reset timeout and done */
1880                 *ms = 0;        /* XXX use 0 since we may not have an exact timeout. */
1881                 return winner;
1882         }
1883         /*
1884          * Then check if any channel or fd has a pending event.
1885          * Remember to check channels first and fds last, as they
1886          * must have priority on setting 'winner'
1887          */
1888         for (x = 0; x < max; x++) {
1889                 res = pfds[x].revents;
1890                 if (res == 0)
1891                         continue;
1892                 if (fdmap[x].chan >= 0) {       /* this is a channel */
1893                         winner = c[fdmap[x].chan];      /* override previous winners */
1894                         if (res & POLLPRI)
1895                                 ast_set_flag(winner, AST_FLAG_EXCEPTION);
1896                         else
1897                                 ast_clear_flag(winner, AST_FLAG_EXCEPTION);
1898                         winner->fdno = fdmap[x].fdno;
1899                 } else {                        /* this is an fd */
1900                         if (outfd)
1901                                 *outfd = pfds[x].fd;
1902                         if (exception)
1903                                 *exception = (res & POLLPRI) ? -1 : 0;
1904                         winner = NULL;
1905                 }
1906         }
1907         if (*ms > 0) {
1908                 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
1909                 if (*ms < 0)
1910                         *ms = 0;
1911         }
1912         return winner;
1913 }
1914
1915 #ifdef HAVE_EPOLL
1916 static struct ast_channel *ast_waitfor_nandfds_simple(struct ast_channel *chan, int *ms)
1917 {
1918         struct timeval start = { 0 , 0 };
1919         int res = 0;
1920         struct epoll_event ev[1];
1921         long whentohangup = 0, rms = *ms;
1922         time_t now;
1923         struct ast_channel *winner = NULL;
1924         struct ast_epoll_data *aed = NULL;
1925
1926         ast_channel_lock(chan);
1927
1928         /* See if this channel needs to be masqueraded */
1929         if (chan->masq && ast_do_masquerade(chan)) {
1930                 ast_log(LOG_WARNING, "Failed to perform masquerade on %s\n", chan->name);
1931                 *ms = -1;
1932                 ast_channel_unlock(chan);
1933                 return NULL;
1934         }
1935
1936         /* Figure out their timeout */
1937         if (chan->whentohangup) {
1938                 time(&now);
1939                 if ((whentohangup = chan->whentohangup - now) < 1) {
1940                         /* They should already be hungup! */
1941                         chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1942                         ast_channel_unlock(chan);
1943                         return NULL;
1944                 }
1945                 /* If this value is smaller then the current one... make it priority */
1946                 whentohangup *= 1000;
1947                 if (rms > whentohangup)
1948                         rms = whentohangup;
1949         }
1950
1951         ast_channel_unlock(chan);
1952
1953         /* Time to make this channel block... */
1954         CHECK_BLOCKING(chan);
1955
1956         if (*ms > 0)
1957                 start = ast_tvnow();
1958
1959         /* We don't have to add any file descriptors... they are already added, we just have to wait! */
1960         res = epoll_wait(chan->epfd, ev, 1, rms);
1961
1962         /* Stop blocking */
1963         ast_clear_flag(chan, AST_FLAG_BLOCKING);
1964
1965         /* Simulate a timeout if we were interrupted */
1966         if (res < 0) {
1967                 if (errno != EINTR)
1968                         *ms = -1;
1969                 return NULL;
1970         }
1971
1972         /* If this channel has a timeout see if it expired */
1973         if (chan->whentohangup) {
1974                 time(&now);
1975                 if (now >= chan->whentohangup) {
1976                         chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1977                         winner = chan;
1978                 }
1979         }
1980
1981         /* No fd ready, reset timeout and be done for now */
1982         if (!res) {
1983                 *ms = 0;
1984                 return winner;
1985         }
1986
1987         /* See what events are pending */
1988         aed = ev[0].data.ptr;
1989         chan->fdno = aed->which;
1990         if (ev[0].events & EPOLLPRI)
1991                 ast_set_flag(chan, AST_FLAG_EXCEPTION);
1992         else
1993                 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
1994
1995         if (*ms > 0) {
1996                 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
1997                 if (*ms < 0)
1998                         *ms = 0;
1999         }
2000
2001         return chan;
2002 }
2003
2004 static struct ast_channel *ast_waitfor_nandfds_complex(struct ast_channel **c, int n, int *ms)
2005 {
2006         struct timeval start = { 0 , 0 };
2007         int res = 0, i;
2008         struct epoll_event ev[25] = { { 0, } };
2009         long whentohangup = 0, diff, rms = *ms;
2010         time_t now;
2011         struct ast_channel *winner = NULL;
2012
2013         for (i = 0; i < n; i++) {
2014                 ast_channel_lock(c[i]);
2015                 if (c[i]->masq && ast_do_masquerade(c[i])) {
2016                         ast_log(LOG_WARNING, "Masquerade failed\n");
2017                         *ms = -1;
2018                         ast_channel_unlock(c[i]);
2019                         return NULL;
2020                 }
2021                 if (c[i]->whentohangup) {
2022                         if (!whentohangup)
2023                                 time(&now);
2024                         if ((diff = c[i]->whentohangup - now) < 1) {
2025                                 c[i]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
2026                                 ast_channel_unlock(c[i]);
2027                                 return c[i];
2028                         }
2029                         if (!whentohangup || (diff < whentohangup))
2030                                 whentohangup = diff;
2031                 }
2032                 ast_channel_unlock(c[i]);
2033                 CHECK_BLOCKING(c[i]);
2034         }
2035
2036         rms = *ms;
2037         if (whentohangup) {
2038                 rms = whentohangup * 1000;
2039                 if (*ms >= 0 && *ms < rms)
2040                         rms = *ms;
2041         }
2042
2043         if (*ms > 0)
2044                 start = ast_tvnow();
2045
2046         res = epoll_wait(c[0]->epfd, ev, 25, rms);
2047
2048         for (i = 0; i < n; i++)
2049                 ast_clear_flag(c[i], AST_FLAG_BLOCKING);
2050
2051         if (res < 0) {
2052                 if (errno != EINTR)
2053                         *ms = -1;
2054                 return NULL;
2055         }
2056
2057         if (whentohangup) {
2058                 time(&now);
2059                 for (i = 0; i < n; i++) {
2060                         if (c[i]->whentohangup && now >= c[i]->whentohangup) {
2061                                 c[i]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
2062                                 if (!winner)
2063                                         winner = c[i];
2064                         }
2065                 }
2066         }
2067
2068         if (!res) {
2069                 *ms = 0;
2070                 return winner;
2071         }
2072
2073         for (i = 0; i < res; i++) {
2074                 struct ast_epoll_data *aed = ev[i].data.ptr;
2075
2076                 if (!ev[i].events || !aed)
2077                         continue;
2078
2079                 winner = aed->chan;
2080                 if (ev[i].events & EPOLLPRI)
2081                         ast_set_flag(winner, AST_FLAG_EXCEPTION);
2082                 else
2083                         ast_clear_flag(winner, AST_FLAG_EXCEPTION);
2084                 winner->fdno = aed->which;
2085         }
2086
2087         if (*ms > 0) {
2088                 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
2089                 if (*ms < 0)
2090                         *ms = 0;
2091         }
2092
2093         return winner;
2094 }
2095
2096 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
2097                                         int *exception, int *outfd, int *ms)
2098 {
2099         /* Clear all provided values in one place. */
2100         if (outfd)
2101                 *outfd = -99999;
2102         if (exception)
2103                 *exception = 0;
2104
2105         /* If no epoll file descriptor is available resort to classic nandfds */
2106         if (!n || nfds || c[0]->epfd == -1)
2107                 return ast_waitfor_nandfds_classic(c, n, fds, nfds, exception, outfd, ms);
2108         else if (!nfds && n == 1)
2109                 return ast_waitfor_nandfds_simple(c[0], ms);
2110         else
2111                 return ast_waitfor_nandfds_complex(c, n, ms);
2112 }
2113 #endif
2114
2115 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
2116 {
2117         return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
2118 }
2119
2120 int ast_waitfor(struct ast_channel *c, int ms)
2121 {
2122         int oldms = ms; /* -1 if no timeout */
2123
2124         ast_waitfor_nandfds(&c, 1, NULL, 0, NULL, NULL, &ms);
2125         if ((ms < 0) && (oldms < 0))
2126                 ms = 0;
2127         return ms;
2128 }
2129
2130 /* XXX never to be called with ms = -1 */
2131 int ast_waitfordigit(struct ast_channel *c, int ms)
2132 {
2133         return ast_waitfordigit_full(c, ms, -1, -1);
2134 }
2135
2136 int ast_settimeout(struct ast_channel *c, int samples, int (*func)(const void *data), void *data)
2137 {
2138         int res = -1;
2139 #ifdef HAVE_ZAPTEL
2140         if (c->timingfd > -1) {
2141                 if (!func) {
2142                         samples = 0;
2143                         data = 0;
2144                 }
2145                 ast_debug(1, "Scheduling timer at %d sample intervals\n", samples);
2146                 res = ioctl(c->timingfd, ZT_TIMERCONFIG, &samples);
2147                 c->timingfunc = func;
2148                 c->timingdata = data;
2149         }
2150 #endif  
2151         return res;
2152 }
2153
2154 int ast_waitfordigit_full(struct ast_channel *c, int ms, int audiofd, int cmdfd)
2155 {
2156         /* Stop if we're a zombie or need a soft hangup */
2157         if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
2158                 return -1;
2159
2160         /* Only look for the end of DTMF, don't bother with the beginning and don't emulate things */
2161         ast_set_flag(c, AST_FLAG_END_DTMF_ONLY);
2162
2163         /* Wait for a digit, no more than ms milliseconds total. */
2164         
2165         while (ms) {
2166                 struct ast_channel *rchan;
2167                 int outfd=-1;
2168
2169                 errno = 0;
2170                 rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
2171                 
2172                 if (!rchan && outfd < 0 && ms) {
2173                         if (errno == 0 || errno == EINTR)
2174                                 continue;
2175                         ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
2176                         ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2177                         return -1;
2178                 } else if (outfd > -1) {
2179                         /* The FD we were watching has something waiting */
2180                         ast_log(LOG_WARNING, "The FD we were waiting for has something waiting. Waitfordigit returning numeric 1\n");
2181                         ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2182                         return 1;
2183                 } else if (rchan) {
2184                         int res;
2185                         struct ast_frame *f = ast_read(c);
2186                         if (!f)
2187                                 return -1;
2188
2189                         switch (f->frametype) {
2190                         case AST_FRAME_DTMF_BEGIN:
2191                                 break;
2192                         case AST_FRAME_DTMF_END:
2193                                 res = f->subclass;
2194                                 ast_frfree(f);
2195                                 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2196                                 return res;
2197                         case AST_FRAME_CONTROL:
2198                                 switch (f->subclass) {
2199                                 case AST_CONTROL_HANGUP:
2200                                         ast_frfree(f);
2201                                         ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2202                                         return -1;
2203                                 case AST_CONTROL_RINGING:
2204                                 case AST_CONTROL_ANSWER:
2205                                         /* Unimportant */
2206                                         break;
2207                                 default:
2208                                         ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", f->subclass);
2209                                         break;
2210                                 }
2211                                 break;
2212                         case AST_FRAME_VOICE:
2213                                 /* Write audio if appropriate */
2214                                 if (audiofd > -1)
2215                                         write(audiofd, f->data, f->datalen);
2216                         default:
2217                                 /* Ignore */
2218                                 break;
2219                         }
2220                         ast_frfree(f);
2221                 }
2222         }
2223
2224         ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
2225
2226         return 0; /* Time is up */
2227 }
2228
2229 static void send_dtmf_event(const struct ast_channel *chan, const char *direction, const char digit, const char *begin, const char *end)
2230 {
2231         manager_event(EVENT_FLAG_DTMF,
2232                         "DTMF",
2233                         "Channel: %s\r\n"
2234                         "Uniqueid: %s\r\n"
2235                         "Digit: %c\r\n"
2236                         "Direction: %s\r\n"
2237                         "Begin: %s\r\n"
2238                         "End: %s\r\n",
2239                         chan->name, chan->uniqueid, digit, direction, begin, end);
2240 }
2241
2242 static void ast_read_generator_actions(struct ast_channel *chan, struct ast_frame *f)
2243 {
2244         if (chan->generatordata &&  !ast_internal_timing_enabled(chan)) {
2245                 void *tmp = chan->generatordata;
2246                 int res;
2247
2248                 if (chan->timingfunc) {
2249                         if (option_debug > 1)
2250                                 ast_log(LOG_DEBUG, "Generator got voice, switching to phase locked mode\n");
2251                         ast_settimeout(chan, 0, NULL, NULL);
2252                 }
2253
2254                 chan->generatordata = NULL;     /* reset, to let writes go through */
2255                 res = chan->generator->generate(chan, tmp, f->datalen, f->samples);
2256                 chan->generatordata = tmp;
2257                 if (res) {
2258                         if (option_debug > 1)
2259                                 ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
2260                         ast_deactivate_generator(chan);
2261                 }
2262
2263         } else if (f->frametype == AST_FRAME_CNG) {
2264                 if (chan->generator && !chan->timingfunc && (chan->timingfd > -1)) {
2265                         if (option_debug > 1)
2266                                 ast_log(LOG_DEBUG, "Generator got CNG, switching to timed mode\n");
2267                         ast_settimeout(chan, 160, generator_force, chan);
2268                 }
2269         }
2270 }
2271
2272 static struct ast_frame *__ast_read(struct ast_channel *chan, int dropaudio)
2273 {
2274         struct ast_frame *f = NULL;     /* the return value */
2275         int blah;
2276         int prestate;
2277         int count = 0;
2278
2279         /* this function is very long so make sure there is only one return
2280          * point at the end (there are only two exceptions to this).
2281          */
2282         while(ast_channel_trylock(chan)) {
2283                 if(count++ > 10) 
2284                         /*cannot goto done since the channel is not locked*/
2285                         return &ast_null_frame;
2286                 usleep(1);
2287         }
2288
2289         if (chan->masq) {
2290                 if (ast_do_masquerade(chan))
2291                         ast_log(LOG_WARNING, "Failed to perform masquerade\n");
2292                 else
2293                         f =  &ast_null_frame;
2294                 goto done;
2295         }
2296
2297         /* Stop if we're a zombie or need a soft hangup */
2298         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2299                 if (chan->generator)
2300                         ast_deactivate_generator(chan);
2301                 goto done;
2302         }
2303         prestate = chan->_state;
2304
2305         if (!ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_EMULATE_DTMF | AST_FLAG_IN_DTMF) && 
2306             !ast_strlen_zero(chan->dtmfq) && 
2307                 (ast_tvzero(chan->dtmf_tv) || ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) > AST_MIN_DTMF_GAP) ) {
2308                 /* We have DTMF that has been deferred.  Return it now */
2309                 chan->dtmff.subclass = chan->dtmfq[0];
2310                 /* Drop first digit from the buffer */
2311                 memmove(chan->dtmfq, chan->dtmfq + 1, sizeof(chan->dtmfq) - 1);
2312                 f = &chan->dtmff;
2313                 if (ast_test_flag(chan, AST_FLAG_END_DTMF_ONLY)) {
2314                         ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass, chan->name);
2315                         chan->dtmff.frametype = AST_FRAME_DTMF_END;
2316                 } else {
2317                         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);
2318                         chan->dtmff.frametype = AST_FRAME_DTMF_BEGIN;
2319                         ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
2320                         chan->emulate_dtmf_digit = f->subclass;
2321                         chan->emulate_dtmf_duration = AST_DEFAULT_EMULATE_DTMF_DURATION;
2322                 }
2323                 chan->dtmf_tv = ast_tvnow();
2324                 goto done;
2325         }
2326         
2327         /* Read and ignore anything on the alertpipe, but read only
2328            one sizeof(blah) per frame that we send from it */
2329         if (chan->alertpipe[0] > -1)
2330                 read(chan->alertpipe[0], &blah, sizeof(blah));
2331
2332 #ifdef HAVE_ZAPTEL
2333         if (chan->timingfd > -1 && chan->fdno == AST_TIMING_FD && ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
2334                 int res;
2335
2336                 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
2337                 blah = -1;
2338                 /* IF we can't get event, assume it's an expired as-per the old interface */
2339                 res = ioctl(chan->timingfd, ZT_GETEVENT, &blah);
2340                 if (res)
2341                         blah = ZT_EVENT_TIMER_EXPIRED;
2342
2343                 if (blah == ZT_EVENT_TIMER_PING) {
2344                         if (AST_LIST_EMPTY(&chan->readq) || !AST_LIST_NEXT(AST_LIST_FIRST(&chan->readq), frame_list)) {
2345                                 /* Acknowledge PONG unless we need it again */
2346                                 if (ioctl(chan->timingfd, ZT_TIMERPONG, &blah)) {
2347                                         ast_log(LOG_WARNING, "Failed to pong timer on '%s': %s\n", chan->name, strerror(errno));
2348                                 }
2349                         }
2350                 } else if (blah == ZT_EVENT_TIMER_EXPIRED) {
2351                         ioctl(chan->timingfd, ZT_TIMERACK, &blah);
2352                         if (chan->timingfunc) {
2353                                 /* save a copy of func/data before unlocking the channel */
2354                                 int (*func)(const void *) = chan->timingfunc;
2355                                 void *data = chan->timingdata;
2356                                 ast_channel_unlock(chan);
2357                                 func(data);
2358                         } else {
2359                                 blah = 0;
2360                                 ioctl(chan->timingfd, ZT_TIMERCONFIG, &blah);
2361                                 chan->timingdata = NULL;
2362                                 ast_channel_unlock(chan);
2363                         }
2364                         /* cannot 'goto done' because the channel is already unlocked */
2365                         return &ast_null_frame;
2366                 } else
2367                         ast_log(LOG_NOTICE, "No/unknown event '%d' on timer for '%s'?\n", blah, chan->name);
2368         } else
2369 #endif
2370         if (chan->fds[AST_GENERATOR_FD] > -1 && chan->fdno == AST_GENERATOR_FD) {
2371                 /* if the AST_GENERATOR_FD is set, call the generator with args
2372                  * set to -1 so it can do whatever it needs to.
2373                  */
2374                 void *tmp = chan->generatordata;
2375                 chan->generatordata = NULL;     /* reset to let ast_write get through */
2376                 chan->generator->generate(chan, tmp, -1, -1);
2377                 chan->generatordata = tmp;
2378                 f = &ast_null_frame;
2379                 goto done;
2380         }
2381
2382         /* Check for pending read queue */
2383         if (!AST_LIST_EMPTY(&chan->readq)) {
2384                 f = AST_LIST_REMOVE_HEAD(&chan->readq, frame_list);
2385                 /* Interpret hangup and return NULL */
2386                 /* XXX why not the same for frames from the channel ? */
2387                 if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP) {
2388                         ast_frfree(f);
2389                         f = NULL;
2390                 }
2391         } else {
2392                 chan->blocker = pthread_self();
2393                 if (ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
2394                         if (chan->tech->exception)
2395                                 f = chan->tech->exception(chan);
2396                         else {
2397                                 ast_log(LOG_WARNING, "Exception flag set on '%s', but no exception handler\n", chan->name);
2398                                 f = &ast_null_frame;
2399                         }
2400                         /* Clear the exception flag */
2401                         ast_clear_flag(chan, AST_FLAG_EXCEPTION);
2402                 } else if (chan->tech->read)
2403                         f = chan->tech->read(chan);
2404                 else
2405                         ast_log(LOG_WARNING, "No read routine on channel %s\n", chan->name);
2406         }
2407
2408         if (f) {
2409                 /* if the channel driver returned more than one frame, stuff the excess
2410                    into the readq for the next ast_read call (note that we can safely assume
2411                    that the readq is empty, because otherwise we would not have called into
2412                    the channel driver and f would be only a single frame)
2413                 */
2414                 if (AST_LIST_NEXT(f, frame_list)) {
2415                         AST_LIST_HEAD_SET_NOLOCK(&chan->readq, AST_LIST_NEXT(f, frame_list));
2416                         AST_LIST_NEXT(f, frame_list) = NULL;
2417                 }
2418
2419                 switch (f->frametype) {
2420                 case AST_FRAME_CONTROL:
2421                         if (f->subclass == AST_CONTROL_ANSWER) {
2422                                 if (!ast_test_flag(chan, AST_FLAG_OUTGOING)) {
2423                                         ast_debug(1, "Ignoring answer on an inbound call!\n");
2424                                         ast_frfree(f);
2425                                         f = &ast_null_frame;
2426                                 } else if (prestate == AST_STATE_UP) {
2427                                         ast_debug(1, "Dropping duplicate answer!\n");
2428                                         ast_frfree(f);
2429                                         f = &ast_null_frame;
2430                                 } else {
2431                                         /* Answer the CDR */
2432                                         ast_setstate(chan, AST_STATE_UP);
2433                                         if (!chan->cdr) { /* up till now, this insertion hasn't been done. Therefore,
2434                                                                                  to keep from throwing off the basic order of the universe,
2435                                                                                  we will try to keep this cdr from getting posted. */
2436                                                 chan->cdr = ast_cdr_alloc();
2437                                                 ast_cdr_init(chan->cdr, chan);
2438                                                 ast_cdr_start(chan->cdr);
2439                                         }
2440                                         
2441                                         ast_cdr_answer(chan->cdr);
2442                                 }
2443                         }
2444                         break;
2445                 case AST_FRAME_DTMF_END:
2446                         send_dtmf_event(chan, "Received", f->subclass, "No", "Yes");
2447                         ast_log(LOG_DTMF, "DTMF end '%c' received on %s, duration %ld ms\n", f->subclass, chan->name, f->len);
2448                         /* Queue it up if DTMF is deffered, or if DTMF emulation is forced.
2449                          * However, only let emulation be forced if the other end cares about BEGIN frames */
2450                         if ( ast_test_flag(chan, AST_FLAG_DEFER_DTMF) ||
2451                                 (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !ast_test_flag(chan, AST_FLAG_END_DTMF_ONLY)) ) {
2452                                 if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2) {
2453                                         ast_log(LOG_DTMF, "DTMF end '%c' put into dtmf queue on %s\n", f->subclass, chan->name);
2454                                         chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
2455                                 } else
2456                                         ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
2457                                 ast_frfree(f);
2458                                 f = &ast_null_frame;
2459                         } else if (!ast_test_flag(chan, AST_FLAG_IN_DTMF | AST_FLAG_END_DTMF_ONLY)) {
2460                                 if (!ast_tvzero(chan->dtmf_tv) && 
2461                                     ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) < AST_MIN_DTMF_GAP) {
2462                                         /* If it hasn't been long enough, defer this digit */
2463                                         if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2) {
2464                                                 ast_log(LOG_DTMF, "DTMF end '%c' put into dtmf queue on %s\n", f->subclass, chan->name);
2465                                                 chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
2466                                         } else
2467                                                 ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
2468                                         ast_frfree(f);
2469                                         f = &ast_null_frame;
2470                                 } else {
2471                                         /* There was no begin, turn this into a begin and send the end later */
2472                                         f->frametype = AST_FRAME_DTMF_BEGIN;
2473                                         ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
2474                                         chan->emulate_dtmf_digit = f->subclass;
2475                                         chan->dtmf_tv = ast_tvnow();
2476                                         if (f->len) {
2477                                                 if (f->len > AST_MIN_DTMF_DURATION)
2478                                                         chan->emulate_dtmf_duration = f->len;
2479                                                 else 
2480                                                         chan->emulate_dtmf_duration = AST_MIN_DTMF_DURATION;
2481                                         } else
2482                                                 chan->emulate_dtmf_duration = AST_DEFAULT_EMULATE_DTMF_DURATION;
2483                                         ast_log(LOG_DTMF, "DTMF begin emulation of '%c' with duration %u queued on %s\n", f->subclass, chan->emulate_dtmf_duration, chan->name);
2484                                 }
2485                                 if (chan->audiohooks) {
2486                                         struct ast_frame *old_frame = f;
2487                                         /*!
2488                                          * \todo XXX It is possible to write a digit to the audiohook twice
2489                                          * if the digit was originally read while the channel was in autoservice. */
2490                                         f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
2491                                         if (old_frame != f)
2492                                                 ast_frfree(old_frame);
2493                                 }
2494                         } else {
2495                                 struct timeval now = ast_tvnow();
2496                                 if (ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
2497                                         ast_log(LOG_DTMF, "DTMF end accepted with begin '%c' on %s\n", f->subclass, chan->name);
2498                                         ast_clear_flag(chan, AST_FLAG_IN_DTMF);
2499                                         if (!f->len)
2500                                                 f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
2501                                 } else if (!f->len) {
2502                                         ast_log(LOG_DTMF, "DTMF end accepted without begin '%c' on %s\n", f->subclass, chan->name);
2503                                         f->len = AST_MIN_DTMF_DURATION;
2504                                 }
2505                                 if (f->len < AST_MIN_DTMF_DURATION) {
2506                                         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);
2507                                         ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
2508                                         chan->emulate_dtmf_digit = f->subclass;
2509                                         chan->emulate_dtmf_duration = AST_MIN_DTMF_DURATION - f->len;
2510                                         ast_frfree(f);
2511                                         f = &ast_null_frame;
2512                                 } else {
2513                                         ast_log(LOG_DTMF, "DTMF end passthrough '%c' on %s\n", f->subclass, chan->name);
2514                                         chan->dtmf_tv = now;
2515                                 }
2516                                 if (chan->audiohooks) {
2517                                         struct ast_frame *old_frame = f;
2518                                         f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
2519                                         if (old_frame != f)
2520                                                 ast_frfree(old_frame);
2521                                 }
2522                         }
2523                         break;
2524                 case AST_FRAME_DTMF_BEGIN:
2525                         send_dtmf_event(chan, "Received", f->subclass, "Yes", "No");
2526                         ast_log(LOG_DTMF, "DTMF begin '%c' received on %s\n", f->subclass, chan->name);
2527                         if ( ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_END_DTMF_ONLY) || 
2528                             (!ast_tvzero(chan->dtmf_tv) && 
2529                               ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) < AST_MIN_DTMF_GAP) ) {
2530                                 ast_log(LOG_DTMF, "DTMF begin ignored '%c' on %s\n", f->subclass, chan->name);
2531                                 ast_frfree(f);
2532                                 f = &ast_null_frame;
2533                         } else {
2534                                 ast_set_flag(chan, AST_FLAG_IN_DTMF);
2535                                 chan->dtmf_tv = ast_tvnow();
2536                                 ast_log(LOG_DTMF, "DTMF begin passthrough '%c' on %s\n", f->subclass, chan->name);
2537                         }
2538                         break;
2539                 case AST_FRAME_NULL:
2540                         if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF)) {
2541                                 struct timeval now = ast_tvnow();
2542                                 if (ast_tvdiff_ms(now, chan->dtmf_tv) >= chan->emulate_dtmf_duration) {
2543                                         chan->emulate_dtmf_duration = 0;
2544                                         ast_frfree(f);
2545                                         f = &chan->dtmff;
2546                                         f->frametype = AST_FRAME_DTMF_END;
2547                                         f->subclass = chan->emulate_dtmf_digit;
2548                                         f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
2549                                         chan->dtmf_tv = now;
2550                                         ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
2551                                         chan->emulate_dtmf_digit = 0;
2552                                         ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass, chan->name);
2553                                 }
2554                         }
2555                         break;
2556                 case AST_FRAME_VOICE:
2557                         /* The EMULATE_DTMF flag must be cleared here as opposed to when the duration
2558                          * is reached , because we want to make sure we pass at least one
2559                          * voice frame through before starting the next digit, to ensure a gap
2560                          * between DTMF digits. */
2561                         if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !chan->emulate_dtmf_duration) {
2562                                 ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
2563                                 chan->emulate_dtmf_digit = 0;
2564                         }
2565
2566                         if (dropaudio || ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
2567                                 if (dropaudio)
2568                                         ast_read_generator_actions(chan, f);
2569                                 ast_frfree(f);
2570                                 f = &ast_null_frame;
2571                         }
2572
2573                         if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
2574                                 struct timeval now = ast_tvnow();
2575                                 if (ast_tvdiff_ms(now, chan->dtmf_tv) >= chan->emulate_dtmf_duration) {
2576                                         chan->emulate_dtmf_duration = 0;
2577                                         ast_frfree(f);
2578                                         f = &chan->dtmff;
2579                                         f->frametype = AST_FRAME_DTMF_END;
2580                                         f->subclass = chan->emulate_dtmf_digit;
2581                                         f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
2582                                         chan->dtmf_tv = now;
2583                                         if (chan->audiohooks) {
2584                                                 struct ast_frame *old_frame = f;
2585                                                 f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
2586                                                 if (old_frame != f)
2587                                                         ast_frfree(old_frame);
2588                                         }
2589                                         ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass, chan->name);
2590                                 } else {
2591                                         /* Drop voice frames while we're still in the middle of the digit */
2592                                         ast_frfree(f);
2593                                         f = &ast_null_frame;
2594                                 }
2595                         } else if ((f->frametype == AST_FRAME_VOICE) && !(f->subclass & chan->nativeformats)) {
2596                                 /* This frame can't be from the current native formats -- drop it on the
2597                                    floor */
2598                                 ast_log(LOG_NOTICE, "Dropping incompatible voice frame on %s of format %s since our native format has changed to %s\n",
2599                                         chan->name, ast_getformatname(f->subclass), ast_getformatname(chan->nativeformats));
2600                                 ast_frfree(f);
2601                                 f = &ast_null_frame;
2602                         } else if ((f->frametype == AST_FRAME_VOICE)) {
2603                                 /* Send frame to audiohooks if present */
2604                                 if (chan->audiohooks) {
2605                                         struct ast_frame *old_frame = f;
2606                                         f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
2607                                         if (old_frame != f)
2608                                                 ast_frfree(old_frame);
2609                                 }
2610                                 if (chan->monitor && chan->monitor->read_stream ) {
2611                                         /* XXX what does this do ? */
2612 #ifndef MONITOR_CONSTANT_DELAY
2613                                         int jump = chan->outsmpl - chan->insmpl - 4 * f->samples;
2614                                         if (jump >= 0) {
2615                                                 jump = chan->outsmpl - chan->insmpl;
2616                                                 if (ast_seekstream(chan->monitor->read_stream, jump, SEEK_FORCECUR) == -1)
2617                                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
2618                                                 chan->insmpl += jump + f->samples;
2619                                         } else
2620                                                 chan->insmpl+= f->samples;
2621 #else
2622                                         int jump = chan->outsmpl - chan->insmpl;
2623                                         if (jump - MONITOR_DELAY >= 0) {
2624                                                 if (ast_seekstream(chan->monitor->read_stream, jump - f->samples, SEEK_FORCECUR) == -1)
2625                                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
2626                                                 chan->insmpl += jump;
2627                                         } else
2628                                                 chan->insmpl += f->samples;
2629 #endif
2630                                         if (chan->monitor->state == AST_MONITOR_RUNNING) {
2631                                                 if (ast_writestream(chan->monitor->read_stream, f) < 0)
2632                                                         ast_log(LOG_WARNING, "Failed to write data to channel monitor read stream\n");
2633                                         }
2634                                 }
2635
2636                                 if (chan->readtrans && (f = ast_translate(chan->readtrans, f, 1)) == NULL)
2637                                         f = &ast_null_frame;
2638                                 else
2639                                         /* Run generator sitting on the line if timing device not available
2640                                          * and synchronous generation of outgoing frames is necessary       */
2641                                         ast_read_generator_actions(chan, f);
2642                         }
2643                 default:
2644                         /* Just pass it on! */
2645                         break;
2646                 }
2647         } else {
2648                 /* Make sure we always return NULL in the future */
2649                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
2650                 if (chan->generator)
2651                         ast_deactivate_generator(chan);
2652                 /* End the CDR if appropriate */
2653                 if (chan->cdr)
2654                         ast_cdr_end(chan->cdr);
2655         }
2656
2657         /* High bit prints debugging */
2658         if (chan->fin & DEBUGCHAN_FLAG)
2659                 ast_frame_dump(chan->name, f, "<<");
2660         chan->fin = FRAMECOUNT_INC(chan->fin);
2661
2662 done:
2663         if (chan->music_state && chan->generator && chan->generator->digit && f && f->frametype == AST_FRAME_DTMF_END)
2664                 chan->generator->digit(chan, f->subclass);
2665
2666         ast_channel_unlock(chan);
2667         return f;
2668 }
2669
2670 int ast_internal_timing_enabled(struct ast_channel *chan)
2671 {
2672         int ret = ast_opt_internal_timing && chan->timingfd > -1;
2673         ast_debug(5, "Internal timing is %s (option_internal_timing=%d chan->timingfd=%d)\n", ret? "enabled": "disabled", ast_opt_internal_timing, chan->timingfd);
2674         return ret;
2675 }
2676
2677 struct ast_frame *ast_read(struct ast_channel *chan)
2678 {
2679         return __ast_read(chan, 0);
2680 }
2681
2682 struct ast_frame *ast_read_noaudio(struct ast_channel *chan)
2683 {
2684         return __ast_read(chan, 1);
2685 }
2686
2687 int ast_indicate(struct ast_channel *chan, int condition)
2688 {
2689         return ast_indicate_data(chan, condition, NULL, 0);
2690 }
2691
2692 int ast_indicate_data(struct ast_channel *chan, int condition, const void *data, size_t datalen)
2693 {
2694         int res = -1;
2695
2696         ast_channel_lock(chan);
2697         /* Stop if we're a zombie or need a soft hangup */
2698         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2699                 ast_channel_unlock(chan);
2700                 return -1;
2701         }
2702         if (chan->tech->indicate)
2703                 res = chan->tech->indicate(chan, condition, data, datalen);
2704         ast_channel_unlock(chan);
2705         if (!chan->tech->indicate || res) {
2706                 /*
2707                  * Device does not support (that) indication, lets fake
2708                  * it by doing our own tone generation. (PM2002)
2709                  */
2710                 if (condition < 0)
2711                         ast_playtones_stop(chan);
2712                 else {
2713                         const struct ind_tone_zone_sound *ts = NULL;
2714                         switch (condition) {
2715                         case AST_CONTROL_RINGING:
2716                                 ts = ast_get_indication_tone(chan->zone, "ring");
2717                                 break;
2718                         case AST_CONTROL_BUSY:
2719                                 ts = ast_get_indication_tone(chan->zone, "busy");
2720                                 break;
2721                         case AST_CONTROL_CONGESTION:
2722                                 ts = ast_get_indication_tone(chan->zone, "congestion");
2723                                 break;
2724                         }
2725                         if (ts && ts->data[0]) {
2726                                 ast_debug(1, "Driver for channel '%s' does not support indication %d, emulating it\n", chan->name, condition);
2727                                 ast_playtones_start(chan,0,ts->data, 1);
2728                                 res = 0;
2729                                 chan->visible_indication = condition;
2730                         } else if (condition == AST_CONTROL_PROGRESS) {
2731                                 /* ast_playtones_stop(chan); */
2732                         } else if (condition == AST_CONTROL_PROCEEDING) {
2733                                 /* Do nothing, really */
2734                         } else if (condition == AST_CONTROL_HOLD) {
2735                                 /* Do nothing.... */
2736                         } else if (condition == AST_CONTROL_UNHOLD) {
2737                                 /* Do nothing.... */
2738                         } else if (condition == AST_CONTROL_VIDUPDATE) {
2739                                 /* Do nothing.... */
2740                         } else {
2741                                 /* not handled */
2742                                 ast_log(LOG_WARNING, "Unable to handle indication %d for '%s'\n", condition, chan->name);
2743                                 res = -1;
2744                         }
2745                 }
2746         } else
2747                 chan->visible_indication = condition;
2748
2749         return res;
2750 }
2751
2752 int ast_recvchar(struct ast_channel *chan, int timeout)
2753 {
2754         int c;
2755         char *buf = ast_recvtext(chan, timeout);
2756         if (buf == NULL)
2757                 return -1;      /* error or timeout */
2758         c = *(unsigned char *)buf;
2759         ast_free(buf);
2760         return c;
2761 }
2762
2763 char *ast_recvtext(struct ast_channel *chan, int timeout)
2764 {
2765         int res, done = 0;
2766         char *buf = NULL;
2767         
2768         while (!done) {
2769                 struct ast_frame *f;
2770                 if (ast_check_hangup(chan))
2771                         break;
2772                 res = ast_waitfor(chan, timeout);
2773                 if (res <= 0) /* timeout or error */
2774                         break;
2775                 timeout = res;  /* update timeout */
2776                 f = ast_read(chan);
2777                 if (f == NULL)
2778                         break; /* no frame */
2779                 if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP)
2780                         done = 1;       /* force a break */
2781                 else if (f->frametype == AST_FRAME_TEXT) {              /* what we want */
2782                         buf = ast_strndup((char *) f->data, f->datalen);        /* dup and break */
2783                         done = 1;
2784                 }
2785                 ast_frfree(f);
2786         }
2787         return buf;
2788 }
2789
2790 int ast_sendtext(struct ast_channel *chan, const char *text)
2791 {
2792         int res = 0;
2793         /* Stop if we're a zombie or need a soft hangup */
2794         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
2795                 return -1;
2796         CHECK_BLOCKING(chan);
2797         if (chan->tech->send_text)
2798                 res = chan->tech->send_text(chan, text);
2799         ast_clear_flag(chan, AST_FLAG_BLOCKING);
2800         return res;
2801 }
2802
2803 int ast_senddigit_begin(struct ast_channel *chan, char digit)
2804 {
2805         /* Device does not support DTMF tones, lets fake
2806          * it by doing our own generation. */
2807         static const char* dtmf_tones[] = {
2808                 "941+1336", /* 0 */
2809                 "697+1209", /* 1 */
2810                 "697+1336", /* 2 */
2811                 "697+1477", /* 3 */
2812                 "770+1209", /* 4 */
2813                 "770+1336", /* 5 */
2814                 "770+1477", /* 6 */
2815                 "852+1209", /* 7 */
2816                 "852+1336", /* 8 */
2817                 "852+1477", /* 9 */
2818                 "697+1633", /* A */
2819                 "770+1633", /* B */
2820                 "852+1633", /* C */
2821                 "941+1633", /* D */
2822                 "941+1209", /* * */
2823                 "941+1477"  /* # */
2824         };
2825
2826         if (!chan->tech->send_digit_begin)
2827                 return 0;
2828
2829         if (!chan->tech->send_digit_begin(chan, digit))
2830                 return 0;
2831
2832         if (digit >= '0' && digit <='9')
2833                 ast_playtones_start(chan, 0, dtmf_tones[digit-'0'], 0);
2834         else if (digit >= 'A' && digit <= 'D')
2835                 ast_playtones_start(chan, 0, dtmf_tones[digit-'A'+10], 0);
2836         else if (digit == '*')
2837                 ast_playtones_start(chan, 0, dtmf_tones[14], 0);
2838         else if (digit == '#')
2839                 ast_playtones_start(chan, 0, dtmf_tones[15], 0);
2840         else {
2841                 /* not handled */
2842                 ast_debug(1, "Unable to generate DTMF tone '%c' for '%s'\n", digit, chan->name);
2843         }
2844
2845         return 0;
2846 }
2847
2848 int ast_senddigit_end(struct ast_channel *chan, char digit, unsigned int duration)
2849 {
2850         int res = -1;
2851
2852         if (chan->tech->send_digit_end)
2853                 res = chan->tech->send_digit_end(chan, digit, duration);
2854
2855         if (res && chan->generator)
2856                 ast_playtones_stop(chan);
2857         
2858         return 0;
2859 }
2860
2861 int ast_senddigit(struct ast_channel *chan, char digit, unsigned int duration)
2862 {
2863         if (chan->tech->send_digit_begin) {
2864                 ast_senddigit_begin(chan, digit);
2865                 ast_safe_sleep(chan, (duration >= AST_DEFAULT_EMULATE_DTMF_DURATION ? duration : AST_DEFAULT_EMULATE_DTMF_DURATION));
2866         }
2867         
2868         return ast_senddigit_end(chan, digit, (duration >= AST_DEFAULT_EMULATE_DTMF_DURATION ? duration : AST_DEFAULT_EMULATE_DTMF_DURATION));
2869 }
2870
2871 int ast_prod(struct ast_channel *chan)
2872 {
2873         struct ast_frame a = { AST_FRAME_VOICE };
2874         char nothing[128];
2875
2876         /* Send an empty audio frame to get things moving */
2877         if (chan->_state != AST_STATE_UP) {
2878                 ast_debug(1, "Prodding channel '%s'\n", chan->name);
2879                 a.subclass = chan->rawwriteformat;
2880                 a.data = nothing + AST_FRIENDLY_OFFSET;
2881                 a.src = "ast_prod";
2882                 if (ast_write(chan, &a))
2883                         ast_log(LOG_WARNING, "Prodding channel '%s' failed\n", chan->name);
2884         }
2885         return 0;
2886 }
2887
2888 int ast_write_video(struct ast_channel *chan, struct ast_frame *fr)
2889 {
2890         int res;
2891         if (!chan->tech->write_video)
2892                 return 0;
2893         res = ast_write(chan, fr);
2894         if (!res)
2895                 res = 1;
2896         return res;
2897 }
2898
2899 int ast_write(struct ast_channel *chan, struct ast_frame *fr)
2900 {
2901         int res = -1;
2902         struct ast_frame *f = NULL, *f2 = NULL;
2903         int count = 0;
2904
2905         /*Deadlock avoidance*/
2906         while(ast_channel_trylock(chan)) {
2907                 /*cannot goto done since the channel is not locked*/
2908                 if(count++ > 10) {
2909                         ast_debug(1, "Deadlock avoided for write to channel '%s'\n", chan->name);
2910                         return 0;
2911                 }
2912                 usleep(1);
2913         }
2914         /* Stop if we're a zombie or need a soft hangup */
2915         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
2916                 goto done;
2917
2918         /* Handle any pending masquerades */
2919         if (chan->masq && ast_do_masquerade(chan)) {
2920                 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
2921                 goto done;
2922         }
2923         if (chan->masqr) {
2924                 res = 0;        /* XXX explain, why 0 ? */
2925                 goto done;
2926         }
2927         if (chan->generatordata) {
2928                 if (ast_test_flag(chan, AST_FLAG_WRITE_INT))
2929                         ast_deactivate_generator(chan);
2930                 else {
2931                         if (fr->frametype == AST_FRAME_DTMF_END) {
2932                                 /* There is a generator running while we're in the middle of a digit.
2933                                  * It's probably inband DTMF, so go ahead and pass it so it can
2934                                  * stop the generator */
2935                                 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2936                                 ast_channel_unlock(chan);
2937                                 res = ast_senddigit_end(chan, fr->subclass, fr->len);
2938                                 ast_channel_lock(chan);
2939                                 CHECK_BLOCKING(chan);
2940                         } else if (fr->frametype == AST_FRAME_CONTROL && fr->subclass == AST_CONTROL_UNHOLD) {
2941                                 /* This is a side case where Echo is basically being called and the person put themselves on hold and took themselves off hold */
2942                                 res = (chan->tech->indicate == NULL) ? 0 :
2943                                         chan->tech->indicate(chan, fr->subclass, fr->data, fr->datalen);
2944                         }
2945                         res = 0;        /* XXX explain, why 0 ? */
2946                         goto done;
2947                 }
2948         }
2949         /* High bit prints debugging */
2950         if (chan->fout & DEBUGCHAN_FLAG)
2951                 ast_frame_dump(chan->name, fr, ">>");
2952         CHECK_BLOCKING(chan);
2953         switch (fr->frametype) {
2954         case AST_FRAME_CONTROL:
2955                 res = (chan->tech->indicate == NULL) ? 0 :
2956                         chan->tech->indicate(chan, fr->subclass, fr->data, fr->datalen);
2957                 break;
2958         case AST_FRAME_DTMF_BEGIN:
2959                 if (chan->audiohooks) {
2960                         struct ast_frame *old_frame = fr;
2961                         fr = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_WRITE, fr);
2962                         if (old_frame != fr)
2963                                 f = fr;
2964                 }
2965                 send_dtmf_event(chan, "Sent", fr->subclass, "Yes", "No");
2966                 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2967                 ast_channel_unlock(chan);
2968                 res = ast_senddigit_begin(chan, fr->subclass);
2969                 ast_channel_lock(chan);
2970                 CHECK_BLOCKING(chan);
2971                 break;
2972         case AST_FRAME_DTMF_END:
2973                 if (chan->audiohooks) {
2974                         struct ast_frame *old_frame = fr;
2975                         fr = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_WRITE, fr);
2976                         if (old_frame != fr)
2977                                 f = fr;
2978                 }
2979                 send_dtmf_event(chan, "Sent", fr->subclass, "No", "Yes");
2980                 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2981                 ast_channel_unlock(chan);
2982                 res = ast_senddigit_end(chan, fr->subclass, fr->len);
2983                 ast_channel_lock(chan);
2984                 CHECK_BLOCKING(chan);
2985                 break;
2986         case AST_FRAME_TEXT:
2987                 if (fr->subclass == AST_FORMAT_T140) {
2988                         res = (chan->tech->write_text == NULL) ? 0 :
2989                                 chan->tech->write_text(chan, fr);
2990                 } else {
2991                         res = (chan->tech->send_text == NULL) ? 0 :
2992                                 chan->tech->send_text(chan, (char *) fr->data);
2993                 }
2994                 break;
2995         case AST_FRAME_HTML:
2996                 res = (chan->tech->send_html == NULL) ? 0 :
2997                         chan->tech->send_html(chan, fr->subclass, (char *) fr->data, fr->datalen);
2998                 break;
2999         case AST_FRAME_VIDEO:
3000                 /* XXX Handle translation of video codecs one day XXX */
3001                 res = (chan->tech->write_video == NULL) ? 0 :
3002                         chan->tech->write_video(chan, fr);
3003                 break;
3004         case AST_FRAME_MODEM:
3005                 res = (chan->tech->write == NULL) ? 0 :
3006                         chan->tech->write(chan, fr);
3007                 break;
3008         case AST_FRAME_VOICE:
3009                 if (chan->tech->write == NULL)
3010                         break;  /*! \todo XXX should return 0 maybe ? */
3011
3012                 /* If audiohooks are present, write the frame out */
3013                 if (chan->audiohooks) {
3014                         struct ast_frame *old_frame = fr;
3015                         fr = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_WRITE, fr);
3016                         if (old_frame != fr)
3017                                 f2 = fr;
3018                 }
3019
3020                 /* If the frame is in the raw write format, then it's easy... just use the frame - otherwise we will have to translate */
3021                 if (fr->subclass == chan->rawwriteformat)
3022                         f = fr;
3023                 else
3024                         f = (chan->writetrans) ? ast_translate(chan->writetrans, fr, 0) : fr;
3025
3026                 if (!f) {
3027                         res = 0;
3028                         break;
3029                 }
3030
3031                 /* If Monitor is running on this channel, then we have to write frames out there too */
3032                 if (chan->monitor && chan->monitor->write_stream) {
3033                         /* XXX must explain this code */
3034 #ifndef MONITOR_CONSTANT_DELAY
3035                         int jump = chan->insmpl - chan->outsmpl - 4 * f->samples;
3036                         if (jump >= 0) {
3037                                 jump = chan->insmpl - chan->outsmpl;
3038                                 if (ast_seekstream(chan->monitor->write_stream, jump, SEEK_FORCECUR) == -1)
3039                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
3040                                 chan->outsmpl += jump + f->samples;
3041                         } else
3042                                 chan->outsmpl += f->samples;
3043 #else
3044                         int jump = chan->insmpl - chan->outsmpl;
3045                         if (jump - MONITOR_DELAY >= 0) {
3046                                 if (ast_seekstream(chan->monitor->write_stream, jump - f->samples, SEEK_FORCECUR) == -1)
3047                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
3048                                 chan->outsmpl += jump;
3049                         } else
3050                                 chan->outsmpl += f->samples;
3051 #endif
3052                         if (chan->monitor->state == AST_MONITOR_RUNNING) {
3053                                 if (ast_writestream(chan->monitor->write_stream, f) < 0)
3054                                         ast_log(LOG_WARNING, "Failed to write data to channel monitor write stream\n");
3055                         }
3056                 }
3057
3058                 if (f) 
3059                         res = chan->tech->write(chan,f);
3060                 else
3061                         res = 0;
3062                 break;
3063         case AST_FRAME_NULL:
3064         case AST_FRAME_IAX:
3065                 /* Ignore these */
3066                 res = 0;
3067                 break;
3068         default:
3069                 /* At this point, fr is the incoming frame and f is NULL.  Channels do
3070                  * not expect to get NULL as a frame pointer and will segfault.  Hence,
3071                  * we output the original frame passed in. */
3072                 res = chan->tech->write(chan, fr);
3073                 break;
3074         }
3075
3076         if (f && f != fr)
3077                 ast_frfree(f);
3078         if (f2)
3079                 ast_frfree(f2);
3080         ast_clear_flag(chan, AST_FLAG_BLOCKING);
3081         /* Consider a write failure to force a soft hangup */
3082         if (res < 0)
3083                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
3084         else {
3085                 chan->fout = FRAMECOUNT_INC(chan->fout);
3086         }
3087 done:
3088<