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