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