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