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