Merged revisions 77460 via svnmerge from
[asterisk/asterisk.git] / main / channel.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2006, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*! \file
20  *
21  * \brief Channel Management
22  *
23  * \author Mark Spencer <markster@digium.com>
24  */
25
26 #include "asterisk.h"
27
28 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
29
30 #include <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         ast_verb(2, "Registered channel type '%s' (%s)\n", chan->tech->type, chan->tech->description);
439
440         AST_RWLIST_UNLOCK(&channels);
441         return 0;
442 }
443
444 /*! \brief Unregister channel driver */
445 void ast_channel_unregister(const struct ast_channel_tech *tech)
446 {
447         struct chanlist *chan;
448
449         ast_debug(1, "Unregistering channel type '%s'\n", tech->type);
450
451         AST_RWLIST_WRLOCK(&channels);
452
453         AST_LIST_TRAVERSE_SAFE_BEGIN(&backends, chan, list) {
454                 if (chan->tech == tech) {
455                         AST_LIST_REMOVE_CURRENT(&backends, list);
456                         ast_free(chan);
457                         ast_verb(2, "Unregistered channel type '%s'\n", tech->type);
458                         break;  
459                 }
460         }
461         AST_LIST_TRAVERSE_SAFE_END
462
463         AST_RWLIST_UNLOCK(&channels);
464 }
465
466 /*! \brief Get handle to channel driver based on name */
467 const struct ast_channel_tech *ast_get_channel_tech(const char *name)
468 {
469         struct chanlist *chanls;
470         const struct ast_channel_tech *ret = NULL;
471
472         if (AST_RWLIST_RDLOCK(&channels)) {
473                 ast_log(LOG_WARNING, "Unable to lock channel tech list\n");
474                 return NULL;
475         }
476
477         AST_LIST_TRAVERSE(&backends, chanls, list) {
478                 if (!strcasecmp(name, chanls->tech->type)) {
479                         ret = chanls->tech;
480                         break;
481                 }
482         }
483
484         AST_RWLIST_UNLOCK(&channels);
485         
486         return ret;
487 }
488
489 /*! \brief Gives the string form of a given hangup cause */
490 const char *ast_cause2str(int cause)
491 {
492         int x;
493
494         for (x=0; x < sizeof(causes) / sizeof(causes[0]); x++) {
495                 if (causes[x].cause == cause)
496                         return causes[x].desc;
497         }
498
499         return "Unknown";
500 }
501
502 /*! \brief Convert a symbolic hangup cause to number */
503 int ast_str2cause(const char *name)
504 {
505         int x;
506
507         for (x = 0; x < sizeof(causes) / sizeof(causes[0]); x++)
508                 if (strncasecmp(causes[x].name, name, strlen(causes[x].name)) == 0)
509                         return causes[x].cause;
510
511         return -1;
512 }
513
514 /*! \brief Gives the string form of a given channel state.
515         \note This function is not reentrant.
516  */
517 const char *ast_state2str(enum ast_channel_state state)
518 {
519         char *buf;
520
521         switch (state) {
522         case AST_STATE_DOWN:
523                 return "Down";
524         case AST_STATE_RESERVED:
525                 return "Rsrvd";
526         case AST_STATE_OFFHOOK:
527                 return "OffHook";
528         case AST_STATE_DIALING:
529                 return "Dialing";
530         case AST_STATE_RING:
531                 return "Ring";
532         case AST_STATE_RINGING:
533                 return "Ringing";
534         case AST_STATE_UP:
535                 return "Up";
536         case AST_STATE_BUSY:
537                 return "Busy";
538         case AST_STATE_DIALING_OFFHOOK:
539                 return "Dialing Offhook";
540         case AST_STATE_PRERING:
541                 return "Pre-ring";
542         default:
543                 if (!(buf = ast_threadstorage_get(&state2str_threadbuf, STATE2STR_BUFSIZE)))
544                         return "Unknown";
545                 snprintf(buf, STATE2STR_BUFSIZE, "Unknown (%d)", state);
546                 return buf;
547         }
548 }
549
550 /*! \brief Gives the string form of a given transfer capability */
551 char *ast_transfercapability2str(int transfercapability)
552 {
553         switch (transfercapability) {
554         case AST_TRANS_CAP_SPEECH:
555                 return "SPEECH";
556         case AST_TRANS_CAP_DIGITAL:
557                 return "DIGITAL";
558         case AST_TRANS_CAP_RESTRICTED_DIGITAL:
559                 return "RESTRICTED_DIGITAL";
560         case AST_TRANS_CAP_3_1K_AUDIO:
561                 return "3K1AUDIO";
562         case AST_TRANS_CAP_DIGITAL_W_TONES:
563                 return "DIGITAL_W_TONES";
564         case AST_TRANS_CAP_VIDEO:
565                 return "VIDEO";
566         default:
567                 return "UNKNOWN";
568         }
569 }
570
571 /*! \brief Pick the best audio codec */
572 int ast_best_codec(int fmts)
573 {
574         /* This just our opinion, expressed in code.  We are asked to choose
575            the best codec to use, given no information */
576         int x;
577         static const int prefs[] =
578         {
579                 /*! Okay, ulaw is used by all telephony equipment, so start with it */
580                 AST_FORMAT_ULAW,
581                 /*! Unless of course, you're a silly European, so then prefer ALAW */
582                 AST_FORMAT_ALAW,
583                 /*! G.722 is better then all below, but not as common as the above... so give ulaw and alaw priority */
584                 AST_FORMAT_G722,
585                 /*! Okay, well, signed linear is easy to translate into other stuff */
586                 AST_FORMAT_SLINEAR,
587                 /*! G.726 is standard ADPCM, in RFC3551 packing order */
588                 AST_FORMAT_G726,
589                 /*! G.726 is standard ADPCM, in AAL2 packing order */
590                 AST_FORMAT_G726_AAL2,
591                 /*! ADPCM has great sound quality and is still pretty easy to translate */
592                 AST_FORMAT_ADPCM,
593                 /*! Okay, we're down to vocoders now, so pick GSM because it's small and easier to
594                     translate and sounds pretty good */
595                 AST_FORMAT_GSM,
596                 /*! iLBC is not too bad */
597                 AST_FORMAT_ILBC,
598                 /*! Speex is free, but computationally more expensive than GSM */
599                 AST_FORMAT_SPEEX,
600                 /*! Ick, LPC10 sounds terrible, but at least we have code for it, if you're tacky enough
601                     to use it */
602                 AST_FORMAT_LPC10,
603                 /*! G.729a is faster than 723 and slightly less expensive */
604                 AST_FORMAT_G729A,
605                 /*! Down to G.723.1 which is proprietary but at least designed for voice */
606                 AST_FORMAT_G723_1,
607         };
608
609         /* Strip out video */
610         fmts &= AST_FORMAT_AUDIO_MASK;
611         
612         /* Find the first preferred codec in the format given */
613         for (x=0; x < (sizeof(prefs) / sizeof(prefs[0]) ); x++)
614                 if (fmts & prefs[x])
615                         return prefs[x];
616         ast_log(LOG_WARNING, "Don't know any of 0x%x formats\n", fmts);
617         return 0;
618 }
619
620 static const struct ast_channel_tech null_tech = {
621         .type = "NULL",
622         .description = "Null channel (should not see this)",
623 };
624
625 /*! \brief Create a new channel structure */
626 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, ...)
627 {
628         struct ast_channel *tmp;
629         int x;
630         int flags;
631         struct varshead *headp;
632         va_list ap1, ap2;
633
634         /* If shutting down, don't allocate any new channels */
635         if (shutting_down) {
636                 ast_log(LOG_WARNING, "Channel allocation failed: Refusing due to active shutdown\n");
637                 return NULL;
638         }
639
640         if (!(tmp = ast_calloc(1, sizeof(*tmp))))
641                 return NULL;
642
643         if (!(tmp->sched = sched_context_create())) {
644                 ast_log(LOG_WARNING, "Channel allocation failed: Unable to create schedule context\n");
645                 ast_free(tmp);
646                 return NULL;
647         }
648         
649         if ((ast_string_field_init(tmp, 128))) {
650                 sched_context_destroy(tmp->sched);
651                 ast_free(tmp);
652                 return NULL;
653         }
654
655         /* Don't bother initializing the last two FD here, because they
656            will *always* be set just a few lines down (AST_TIMING_FD,
657            AST_ALERT_FD). */
658         for (x = 0; x < AST_MAX_FDS - 2; x++)
659                 tmp->fds[x] = -1;
660
661 #ifdef HAVE_ZAPTEL
662         tmp->timingfd = open("/dev/zap/timer", O_RDWR);
663         if (tmp->timingfd > -1) {
664                 /* Check if timing interface supports new
665                    ping/pong scheme */
666                 flags = 1;
667                 if (!ioctl(tmp->timingfd, ZT_TIMERPONG, &flags))
668                         needqueue = 0;
669         }
670 #else
671         tmp->timingfd = -1;                                     
672 #endif                                  
673
674         if (needqueue) {
675                 if (pipe(tmp->alertpipe)) {
676                         ast_log(LOG_WARNING, "Channel allocation failed: Can't create alert pipe!\n");
677                         ast_string_field_free_pools(tmp);
678                         ast_free(tmp);
679                         return NULL;
680                 } else {
681                         flags = fcntl(tmp->alertpipe[0], F_GETFL);
682                         fcntl(tmp->alertpipe[0], F_SETFL, flags | O_NONBLOCK);
683                         flags = fcntl(tmp->alertpipe[1], F_GETFL);
684                         fcntl(tmp->alertpipe[1], F_SETFL, flags | O_NONBLOCK);
685                 }
686         } else  /* Make sure we've got it done right if they don't */
687                 tmp->alertpipe[0] = tmp->alertpipe[1] = -1;
688
689         /* Always watch the alertpipe */
690         tmp->fds[AST_ALERT_FD] = tmp->alertpipe[0];
691         /* And timing pipe */
692         tmp->fds[AST_TIMING_FD] = tmp->timingfd;
693         ast_string_field_set(tmp, name, "**Unknown**");
694
695         /* Initial state */
696         tmp->_state = state;
697
698         tmp->streamid = -1;
699         
700         tmp->fin = global_fin;
701         tmp->fout = global_fout;
702
703         if (ast_strlen_zero(ast_config_AST_SYSTEM_NAME)) {
704                 ast_string_field_build(tmp, uniqueid, "%li.%d", (long) time(NULL), 
705                                        ast_atomic_fetchadd_int(&uniqueint, 1));
706         } else {
707                 ast_string_field_build(tmp, uniqueid, "%s-%li.%d", ast_config_AST_SYSTEM_NAME, 
708                                        (long) time(NULL), ast_atomic_fetchadd_int(&uniqueint, 1));
709         }
710
711         tmp->cid.cid_name = ast_strdup(cid_name);
712         tmp->cid.cid_num = ast_strdup(cid_num);
713         
714         if (!ast_strlen_zero(name_fmt)) {
715                 /* Almost every channel is calling this function, and setting the name via the ast_string_field_build() call.
716                  * And they all use slightly different formats for their name string.
717                  * This means, to set the name here, we have to accept variable args, and call the string_field_build from here.
718                  * This means, that the stringfields must have a routine that takes the va_lists directly, and 
719                  * uses them to build the string, instead of forming the va_lists internally from the vararg ... list.
720                  * This new function was written so this can be accomplished.
721                  */
722                 va_start(ap1, name_fmt);
723                 va_start(ap2, name_fmt);
724                 ast_string_field_build_va(tmp, name, name_fmt, ap1, ap2);
725                 va_end(ap1);
726                 va_end(ap2);
727
728                 /* and now, since the channel structure is built, and has its name, let's call the
729                  * manager event generator with this Newchannel event. This is the proper and correct
730                  * place to make this call, but you sure do have to pass a lot of data into this func
731                  * to do it here!
732                  */
733                 manager_event(EVENT_FLAG_CALL, "Newchannel",
734                               "Channel: %s\r\n"
735                               "State: %s\r\n"
736                               "CallerIDNum: %s\r\n"
737                               "CallerIDName: %s\r\n"
738                               "Uniqueid: %s\r\n",
739                               tmp->name, ast_state2str(state),
740                               S_OR(cid_num, "<unknown>"),
741                               S_OR(cid_name, "<unknown>"),
742                               tmp->uniqueid);
743         }
744
745         /* Reminder for the future: under what conditions do we NOT want to track cdrs on channels? */
746
747         /* These 4 variables need to be set up for the cdr_init() to work right */
748         if (amaflag)
749                 tmp->amaflags = amaflag;
750         else
751                 tmp->amaflags = ast_default_amaflags;
752         
753         if (!ast_strlen_zero(acctcode))
754                 ast_string_field_set(tmp, accountcode, acctcode);
755         else
756                 ast_string_field_set(tmp, accountcode, ast_default_accountcode);
757                 
758         if (!ast_strlen_zero(context))
759                 ast_copy_string(tmp->context, context, sizeof(tmp->context));
760         else
761                 strcpy(tmp->context, "default");
762
763         if (!ast_strlen_zero(exten))
764                 ast_copy_string(tmp->exten, exten, sizeof(tmp->exten));
765         else
766                 strcpy(tmp->exten, "s");
767
768         tmp->priority = 1;
769                 
770         tmp->cdr = ast_cdr_alloc();
771         ast_cdr_init(tmp->cdr, tmp);
772         ast_cdr_start(tmp->cdr);
773         
774         headp = &tmp->varshead;
775         AST_LIST_HEAD_INIT_NOLOCK(headp);
776         
777         ast_mutex_init(&tmp->lock);
778         
779         AST_LIST_HEAD_INIT_NOLOCK(&tmp->datastores);
780         
781         ast_string_field_set(tmp, language, defaultlanguage);
782
783         tmp->tech = &null_tech;
784
785         AST_RWLIST_WRLOCK(&channels);
786         AST_RWLIST_INSERT_HEAD(&channels, tmp, chan_list);
787         AST_RWLIST_UNLOCK(&channels);
788
789         return tmp;
790 }
791
792 /*! \brief Queue an outgoing media frame */
793 int ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin)
794 {
795         struct ast_frame *f;
796         struct ast_frame *cur;
797         int blah = 1;
798         int qlen = 0;
799
800         /* Build us a copy and free the original one */
801         if (!(f = ast_frdup(fin))) {
802                 ast_log(LOG_WARNING, "Unable to duplicate frame\n");
803                 return -1;
804         }
805         ast_channel_lock(chan);
806
807         /* See if the last frame on the queue is a hangup, if so don't queue anything */
808         if ((cur = AST_LIST_LAST(&chan->readq)) && (cur->frametype == AST_FRAME_CONTROL) && (cur->subclass == AST_CONTROL_HANGUP)) {
809                 ast_frfree(f);
810                 ast_channel_unlock(chan);
811                 return 0;
812         }
813
814         /* Count how many frames exist on the queue */
815         AST_LIST_TRAVERSE(&chan->readq, cur, frame_list) {
816                 qlen++;
817         }
818
819         /* Allow up to 96 voice frames outstanding, and up to 128 total frames */
820         if (((fin->frametype == AST_FRAME_VOICE) && (qlen > 96)) || (qlen  > 128)) {
821                 if (fin->frametype != AST_FRAME_VOICE) {
822                         ast_log(LOG_WARNING, "Exceptionally long queue length queuing to %s\n", chan->name);
823                         CRASH;
824                 } else {
825                         ast_debug(1, "Dropping voice to exceptionally long queue on %s\n", chan->name);
826                         ast_frfree(f);
827                         ast_channel_unlock(chan);
828                         return 0;
829                 }
830         }
831         AST_LIST_INSERT_TAIL(&chan->readq, f, frame_list);
832         if (chan->alertpipe[1] > -1) {
833                 if (write(chan->alertpipe[1], &blah, sizeof(blah)) != sizeof(blah))
834                         ast_log(LOG_WARNING, "Unable to write to alert pipe on %s, frametype/subclass %d/%d (qlen = %d): %s!\n",
835                                 chan->name, f->frametype, f->subclass, qlen, strerror(errno));
836 #ifdef HAVE_ZAPTEL
837         } else if (chan->timingfd > -1) {
838                 ioctl(chan->timingfd, ZT_TIMERPING, &blah);
839 #endif                          
840         } else if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
841                 pthread_kill(chan->blocker, SIGURG);
842         }
843         ast_channel_unlock(chan);
844         return 0;
845 }
846
847 /*! \brief Queue a hangup frame for channel */
848 int ast_queue_hangup(struct ast_channel *chan)
849 {
850         struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_HANGUP };
851         /* Yeah, let's not change a lock-critical value without locking */
852         if (!ast_channel_trylock(chan)) {
853                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
854                 ast_channel_unlock(chan);
855         }
856         return ast_queue_frame(chan, &f);
857 }
858
859 /*! \brief Queue a control frame */
860 int ast_queue_control(struct ast_channel *chan, enum ast_control_frame_type control)
861 {
862         struct ast_frame f = { AST_FRAME_CONTROL, };
863
864         f.subclass = control;
865
866         return ast_queue_frame(chan, &f);
867 }
868
869 /*! \brief Queue a control frame with payload */
870 int ast_queue_control_data(struct ast_channel *chan, enum ast_control_frame_type control,
871                            const void *data, size_t datalen)
872 {
873         struct ast_frame f = { AST_FRAME_CONTROL, };
874
875         f.subclass = control;
876         f.data = (void *) data;
877         f.datalen = datalen;
878
879         return ast_queue_frame(chan, &f);
880 }
881
882 /*! \brief Set defer DTMF flag on channel */
883 int ast_channel_defer_dtmf(struct ast_channel *chan)
884 {
885         int pre = 0;
886
887         if (chan) {
888                 pre = ast_test_flag(chan, AST_FLAG_DEFER_DTMF);
889                 ast_set_flag(chan, AST_FLAG_DEFER_DTMF);
890         }
891         return pre;
892 }
893
894 /*! \brief Unset defer DTMF flag on channel */
895 void ast_channel_undefer_dtmf(struct ast_channel *chan)
896 {
897         if (chan)
898                 ast_clear_flag(chan, AST_FLAG_DEFER_DTMF);
899 }
900
901 /*!
902  * \brief Helper function to find channels.
903  *
904  * It supports these modes:
905  *
906  * prev != NULL : get channel next in list after prev
907  * name != NULL : get channel with matching name
908  * name != NULL && namelen != 0 : get channel whose name starts with prefix
909  * exten != NULL : get channel whose exten or macroexten matches
910  * context != NULL && exten != NULL : get channel whose context or macrocontext
911  *
912  * It returns with the channel's lock held. If getting the individual lock fails,
913  * unlock and retry quickly up to 10 times, then give up.
914  *
915  * \note XXX Note that this code has cost O(N) because of the need to verify
916  * that the object is still on the global list.
917  *
918  * \note XXX also note that accessing fields (e.g. c->name in ast_log())
919  * can only be done with the lock held or someone could delete the
920  * object while we work on it. This causes some ugliness in the code.
921  * Note that removing the first ast_log() may be harmful, as it would
922  * shorten the retry period and possibly cause failures.
923  * We should definitely go for a better scheme that is deadlock-free.
924  */
925 static struct ast_channel *channel_find_locked(const struct ast_channel *prev,
926                                                const char *name, const int namelen,
927                                                const char *context, const char *exten)
928 {
929         const char *msg = prev ? "deadlock" : "initial deadlock";
930         int retries;
931         struct ast_channel *c;
932
933         for (retries = 0; retries < 10; retries++) {
934                 int done;
935                 AST_RWLIST_RDLOCK(&channels);
936                 AST_RWLIST_TRAVERSE(&channels, c, chan_list) {
937                         if (prev) {     /* look for next item */
938                                 if (c != prev)  /* not this one */
939                                         continue;
940                                 /* found, prepare to return c->next */
941                                 if ((c = AST_RWLIST_NEXT(c, chan_list)) == NULL) break;
942                                 /* If prev was the last item on the channel list, then we just
943                                  * want to return NULL, instead of trying to deref NULL in the
944                                  * next section.
945                                  */
946                                 prev = NULL;
947                                 /* We want prev to be NULL in case we end up doing more searching through
948                                  * the channel list to find the channel (ie: name searching). If we didn't
949                                  * set this to NULL the logic would just blow up
950                                  */
951                         }
952                         if (name) { /* want match by name */
953                                 if ((!namelen && strcasecmp(c->name, name)) ||
954                                     (namelen && strncasecmp(c->name, name, namelen)))
955                                         continue;       /* name match failed */
956                         } else if (exten) {
957                                 if (context && strcasecmp(c->context, context) &&
958                                     strcasecmp(c->macrocontext, context))
959                                         continue;       /* context match failed */
960                                 if (strcasecmp(c->exten, exten) &&
961                                     strcasecmp(c->macroexten, exten))
962                                         continue;       /* exten match failed */
963                         }
964                         /* if we get here, c points to the desired record */
965                         break;
966                 }
967                 /* exit if chan not found or mutex acquired successfully */
968                 /* this is slightly unsafe, as we _should_ hold the lock to access c->name */
969                 done = c == NULL || ast_channel_trylock(c) == 0;
970                 if (!done) {
971                         ast_debug(1, "Avoiding %s for channel '%p'\n", msg, c);
972                         if (retries == 9) {
973                                 /* We are about to fail due to a deadlock, so report this
974                                  * while we still have the list lock.
975                                  */
976                                 ast_debug(1, "Failure, could not lock '%p' after %d retries!\n", c, retries);
977                                 /* As we have deadlocked, we will skip this channel and
978                                  * see if there is another match.
979                                  * NOTE: No point doing this for a full-name match,
980                                  * as there can be no more matches.
981                                  */
982                                 if (!(name && !namelen)) {
983                                         prev = c;
984                                         retries = -1;
985                                 }
986                         }
987                 }
988                 AST_RWLIST_UNLOCK(&channels);
989                 if (done)
990                         return c;
991                 usleep(1);      /* give other threads a chance before retrying */
992         }
993
994         return NULL;
995 }
996
997 /*! \brief Browse channels in use */
998 struct ast_channel *ast_channel_walk_locked(const struct ast_channel *prev)
999 {
1000         return channel_find_locked(prev, NULL, 0, NULL, NULL);
1001 }
1002
1003 /*! \brief Get channel by name and lock it */
1004 struct ast_channel *ast_get_channel_by_name_locked(const char *name)
1005 {
1006         return channel_find_locked(NULL, name, 0, NULL, NULL);
1007 }
1008
1009 /*! \brief Get channel by name prefix and lock it */
1010 struct ast_channel *ast_get_channel_by_name_prefix_locked(const char *name, const int namelen)
1011 {
1012         return channel_find_locked(NULL, name, namelen, NULL, NULL);
1013 }
1014
1015 /*! \brief Get next channel by name prefix and lock it */
1016 struct ast_channel *ast_walk_channel_by_name_prefix_locked(const struct ast_channel *chan, const char *name,
1017                                                            const int namelen)
1018 {
1019         return channel_find_locked(chan, name, namelen, NULL, NULL);
1020 }
1021
1022 /*! \brief Get channel by exten (and optionally context) and lock it */
1023 struct ast_channel *ast_get_channel_by_exten_locked(const char *exten, const char *context)
1024 {
1025         return channel_find_locked(NULL, NULL, 0, context, exten);
1026 }
1027
1028 /*! \brief Get next channel by exten (and optionally context) and lock it */
1029 struct ast_channel *ast_walk_channel_by_exten_locked(const struct ast_channel *chan, const char *exten,
1030                                                      const char *context)
1031 {
1032         return channel_find_locked(chan, NULL, 0, context, exten);
1033 }
1034
1035 /*! \brief Wait, look for hangups and condition arg */
1036 int ast_safe_sleep_conditional(struct ast_channel *chan, int ms, int (*cond)(void*), void *data)
1037 {
1038         struct ast_frame *f;
1039
1040         while (ms > 0) {
1041                 if (cond && ((*cond)(data) == 0))
1042                         return 0;
1043                 ms = ast_waitfor(chan, ms);
1044                 if (ms < 0)
1045                         return -1;
1046                 if (ms > 0) {
1047                         f = ast_read(chan);
1048                         if (!f)
1049                                 return -1;
1050                         ast_frfree(f);
1051                 }
1052         }
1053         return 0;
1054 }
1055
1056 /*! \brief Wait, look for hangups */
1057 int ast_safe_sleep(struct ast_channel *chan, int ms)
1058 {
1059         return ast_safe_sleep_conditional(chan, ms, NULL, NULL);
1060 }
1061
1062 static void free_cid(struct ast_callerid *cid)
1063 {
1064         if (cid->cid_dnid)
1065                 ast_free(cid->cid_dnid);
1066         if (cid->cid_num)
1067                 ast_free(cid->cid_num); 
1068         if (cid->cid_name)
1069                 ast_free(cid->cid_name);        
1070         if (cid->cid_ani)
1071                 ast_free(cid->cid_ani);
1072         if (cid->cid_rdnis)
1073                 ast_free(cid->cid_rdnis);
1074         cid->cid_dnid = cid->cid_num = cid->cid_name = cid->cid_ani = cid->cid_rdnis = NULL;
1075 }
1076
1077 /*! \brief Free a channel structure */
1078 void ast_channel_free(struct ast_channel *chan)
1079 {
1080         int fd;
1081         struct ast_var_t *vardata;
1082         struct ast_frame *f;
1083         struct varshead *headp;
1084         struct ast_datastore *datastore = NULL;
1085         char name[AST_CHANNEL_NAME];
1086         
1087         headp=&chan->varshead;
1088         
1089         AST_RWLIST_WRLOCK(&channels);
1090         if (!AST_RWLIST_REMOVE(&channels, chan, chan_list)) {
1091                 AST_RWLIST_UNLOCK(&channels);
1092                 ast_log(LOG_ERROR, "Unable to find channel in list to free. Assuming it has already been done.\n");
1093         }
1094         /* Lock and unlock the channel just to be sure nobody
1095            has it locked still */
1096         ast_channel_lock(chan);
1097         ast_channel_unlock(chan);
1098         if (chan->tech_pvt) {
1099                 ast_log(LOG_WARNING, "Channel '%s' may not have been hung up properly\n", chan->name);
1100                 ast_free(chan->tech_pvt);
1101         }
1102
1103         if (chan->sched)
1104                 sched_context_destroy(chan->sched);
1105
1106         ast_copy_string(name, chan->name, sizeof(name));
1107
1108         /* Stop monitoring */
1109         if (chan->monitor)
1110                 chan->monitor->stop( chan, 0 );
1111
1112         /* If there is native format music-on-hold state, free it */
1113         if (chan->music_state)
1114                 ast_moh_cleanup(chan);
1115
1116         /* if someone is whispering on the channel, stop them */
1117         if (chan->whisper)
1118                 ast_channel_whisper_stop(chan);
1119
1120         /* Free translators */
1121         if (chan->readtrans)
1122                 ast_translator_free_path(chan->readtrans);
1123         if (chan->writetrans)
1124                 ast_translator_free_path(chan->writetrans);
1125         if (chan->pbx)
1126                 ast_log(LOG_WARNING, "PBX may not have been terminated properly on '%s'\n", chan->name);
1127         free_cid(&chan->cid);
1128         ast_mutex_destroy(&chan->lock);
1129         /* Close pipes if appropriate */
1130         if ((fd = chan->alertpipe[0]) > -1)
1131                 close(fd);
1132         if ((fd = chan->alertpipe[1]) > -1)
1133                 close(fd);
1134         if ((fd = chan->timingfd) > -1)
1135                 close(fd);
1136         while ((f = AST_LIST_REMOVE_HEAD(&chan->readq, frame_list)))
1137                 ast_frfree(f);
1138         
1139         /* Get rid of each of the data stores on the channel */
1140         while ((datastore = AST_LIST_REMOVE_HEAD(&chan->datastores, entry)))
1141                 /* Free the data store */
1142                 ast_channel_datastore_free(datastore);
1143         AST_LIST_HEAD_INIT_NOLOCK(&chan->datastores);
1144
1145         /* loop over the variables list, freeing all data and deleting list items */
1146         /* no need to lock the list, as the channel is already locked */
1147         
1148         while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
1149                 ast_var_delete(vardata);
1150
1151         ast_app_group_discard(chan);
1152
1153         /* Destroy the jitterbuffer */
1154         ast_jb_destroy(chan);
1155
1156         ast_string_field_free_pools(chan);
1157         ast_free(chan);
1158         AST_RWLIST_UNLOCK(&channels);
1159
1160         ast_device_state_changed_literal(name);
1161 }
1162
1163 struct ast_datastore *ast_channel_datastore_alloc(const struct ast_datastore_info *info, char *uid)
1164 {
1165         struct ast_datastore *datastore = NULL;
1166
1167         /* Make sure we at least have type so we can identify this */
1168         if (!info) {
1169                 return NULL;
1170         }
1171
1172         /* Allocate memory for datastore and clear it */
1173         datastore = ast_calloc(1, sizeof(*datastore));
1174         if (!datastore) {
1175                 return NULL;
1176         }
1177
1178         datastore->info = info;
1179
1180         datastore->uid = ast_strdup(uid);
1181
1182         return datastore;
1183 }
1184
1185 int ast_channel_datastore_free(struct ast_datastore *datastore)
1186 {
1187         int res = 0;
1188
1189         /* Using the destroy function (if present) destroy the data */
1190         if (datastore->info->destroy != NULL && datastore->data != NULL) {
1191                 datastore->info->destroy(datastore->data);
1192                 datastore->data = NULL;
1193         }
1194
1195         /* Free allocated UID memory */
1196         if (datastore->uid != NULL) {
1197                 ast_free(datastore->uid);
1198                 datastore->uid = NULL;
1199         }
1200
1201         /* Finally free memory used by ourselves */
1202         ast_free(datastore);
1203
1204         return res;
1205 }
1206
1207 int ast_channel_datastore_inherit(struct ast_channel *from, struct ast_channel *to)
1208 {
1209         struct ast_datastore *datastore = NULL, *datastore2;
1210
1211         AST_LIST_TRAVERSE(&from->datastores, datastore, entry) {
1212                 if (datastore->inheritance > 0) {
1213                         datastore2 = ast_channel_datastore_alloc(datastore->info, datastore->uid);
1214                         if (datastore2) {
1215                                 datastore2->data = datastore->info->duplicate(datastore->data);
1216                                 datastore2->inheritance = datastore->inheritance == DATASTORE_INHERIT_FOREVER ? DATASTORE_INHERIT_FOREVER : datastore->inheritance - 1;
1217                                 AST_LIST_INSERT_TAIL(&to->datastores, datastore2, entry);
1218                         }
1219                 }
1220         }
1221         return 0;
1222 }
1223
1224 int ast_channel_datastore_add(struct ast_channel *chan, struct ast_datastore *datastore)
1225 {
1226         int res = 0;
1227
1228         AST_LIST_INSERT_HEAD(&chan->datastores, datastore, entry);
1229
1230         return res;
1231 }
1232
1233 int ast_channel_datastore_remove(struct ast_channel *chan, struct ast_datastore *datastore)
1234 {
1235         struct ast_datastore *datastore2 = NULL;
1236         int res = -1;
1237
1238         /* Find our position and remove ourselves */
1239         AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->datastores, datastore2, entry) {
1240                 if (datastore2 == datastore) {
1241                         AST_LIST_REMOVE_CURRENT(&chan->datastores, entry);
1242                         res = 0;
1243                         break;
1244                 }
1245         }
1246         AST_LIST_TRAVERSE_SAFE_END
1247
1248         return res;
1249 }
1250
1251 struct ast_datastore *ast_channel_datastore_find(struct ast_channel *chan, const struct ast_datastore_info *info, char *uid)
1252 {
1253         struct ast_datastore *datastore = NULL;
1254         
1255         if (info == NULL)
1256                 return NULL;
1257
1258         AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->datastores, datastore, entry) {
1259                 if (datastore->info == info) {
1260                         if (uid != NULL && datastore->uid != NULL) {
1261                                 if (!strcasecmp(uid, datastore->uid)) {
1262                                         /* Matched by type AND uid */
1263                                         break;
1264                                 }
1265                         } else {
1266                                 /* Matched by type at least */
1267                                 break;
1268                         }
1269                 }
1270         }
1271         AST_LIST_TRAVERSE_SAFE_END
1272
1273         return datastore;
1274 }
1275
1276 int ast_channel_spy_add(struct ast_channel *chan, struct ast_channel_spy *spy)
1277 {
1278         /* Link the owner channel to the spy */
1279         spy->chan = chan;
1280
1281         if (!ast_test_flag(spy, CHANSPY_FORMAT_AUDIO)) {
1282                 ast_log(LOG_WARNING, "Could not add channel spy '%s' to channel '%s', only audio format spies are supported.\n",
1283                         spy->type, chan->name);
1284                 return -1;
1285         }
1286
1287         if (ast_test_flag(spy, CHANSPY_READ_VOLADJUST) && (spy->read_queue.format != AST_FORMAT_SLINEAR)) {
1288                 ast_log(LOG_WARNING, "Cannot provide volume adjustment on '%s' format spies\n",
1289                         ast_getformatname(spy->read_queue.format));
1290                 return -1;
1291         }
1292
1293         if (ast_test_flag(spy, CHANSPY_WRITE_VOLADJUST) && (spy->write_queue.format != AST_FORMAT_SLINEAR)) {
1294                 ast_log(LOG_WARNING, "Cannot provide volume adjustment on '%s' format spies\n",
1295                         ast_getformatname(spy->write_queue.format));
1296                 return -1;
1297         }
1298
1299         if (ast_test_flag(spy, CHANSPY_MIXAUDIO) &&
1300             ((spy->read_queue.format != AST_FORMAT_SLINEAR) ||
1301              (spy->write_queue.format != AST_FORMAT_SLINEAR))) {
1302                 ast_log(LOG_WARNING, "Cannot provide audio mixing on '%s'-'%s' format spies\n",
1303                         ast_getformatname(spy->read_queue.format), ast_getformatname(spy->write_queue.format));
1304                 return -1;
1305         }
1306
1307         if (!chan->spies) {
1308                 if (!(chan->spies = ast_calloc(1, sizeof(*chan->spies)))) {
1309                         return -1;
1310                 }
1311
1312                 AST_LIST_HEAD_INIT_NOLOCK(&chan->spies->list);
1313                 AST_LIST_INSERT_HEAD(&chan->spies->list, spy, list);
1314         } else {
1315                 AST_LIST_INSERT_TAIL(&chan->spies->list, spy, list);
1316         }
1317
1318         if (ast_test_flag(spy, CHANSPY_TRIGGER_MODE) != CHANSPY_TRIGGER_NONE) {
1319                 ast_cond_init(&spy->trigger, NULL);
1320                 ast_set_flag(spy, CHANSPY_TRIGGER_READ);
1321                 ast_clear_flag(spy, CHANSPY_TRIGGER_WRITE);
1322         }
1323
1324         ast_debug(1, "Spy %s added to channel %s\n",
1325                 spy->type, chan->name);
1326
1327         return 0;
1328 }
1329
1330 /* Clean up a channel's spy information */
1331 static void spy_cleanup(struct ast_channel *chan)
1332 {
1333         if (!AST_LIST_EMPTY(&chan->spies->list))
1334                 return;
1335         if (chan->spies->read_translator.path)
1336                 ast_translator_free_path(chan->spies->read_translator.path);
1337         if (chan->spies->write_translator.path)
1338                 ast_translator_free_path(chan->spies->write_translator.path);
1339         ast_free(chan->spies);
1340         chan->spies = NULL;
1341         return;
1342 }
1343
1344 /* Detach a spy from it's channel */
1345 static void spy_detach(struct ast_channel_spy *spy, struct ast_channel *chan)
1346 {
1347         /* We only need to poke them if they aren't already done */
1348         if (spy->status != CHANSPY_DONE) {
1349                 ast_mutex_lock(&spy->lock);
1350                 /* Indicate to the spy to stop */
1351                 spy->status = CHANSPY_STOP;
1352                 spy->chan = NULL;
1353                 /* Poke the spy if needed */
1354                 if (ast_test_flag(spy, CHANSPY_TRIGGER_MODE) != CHANSPY_TRIGGER_NONE)
1355                         ast_cond_signal(&spy->trigger);
1356                 ast_mutex_unlock(&spy->lock);
1357         }
1358
1359         /* Print it out while we still have a lock so the structure can't go away (if signalled above) */
1360         ast_debug(1, "Spy %s removed from channel %s\n", spy->type, chan->name);
1361
1362         return;
1363 }
1364
1365 void ast_channel_spy_stop_by_type(struct ast_channel *chan, const char *type)
1366 {
1367         struct ast_channel_spy *spy = NULL;
1368         
1369         if (!chan->spies)
1370                 return;
1371
1372         AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->spies->list, spy, list) {
1373                 if ((spy->type == type) && (spy->status == CHANSPY_RUNNING)) {
1374                         AST_LIST_REMOVE_CURRENT(&chan->spies->list, list);
1375                         spy_detach(spy, chan);
1376                 }
1377         }
1378         AST_LIST_TRAVERSE_SAFE_END
1379         spy_cleanup(chan);
1380 }
1381
1382 void ast_channel_spy_trigger_wait(struct ast_channel_spy *spy)
1383 {
1384         struct timeval tv;
1385         struct timespec ts;
1386
1387         tv = ast_tvadd(ast_tvnow(), ast_samp2tv(50000, 1000));
1388         ts.tv_sec = tv.tv_sec;
1389         ts.tv_nsec = tv.tv_usec * 1000;
1390
1391         ast_cond_timedwait(&spy->trigger, &spy->lock, &ts);
1392 }
1393
1394 void ast_channel_spy_remove(struct ast_channel *chan, struct ast_channel_spy *spy)
1395 {
1396         if (!chan->spies)
1397                 return;
1398
1399         AST_LIST_REMOVE(&chan->spies->list, spy, list);
1400         spy_detach(spy, chan);
1401         spy_cleanup(chan);
1402 }
1403
1404 void ast_channel_spy_free(struct ast_channel_spy *spy)
1405 {
1406         struct ast_frame *f = NULL;
1407
1408         if (spy->status == CHANSPY_DONE)
1409                 return;
1410
1411         /* Switch status to done in case we get called twice */
1412         spy->status = CHANSPY_DONE;
1413
1414         /* Drop any frames in the queue */
1415         while ((f = AST_LIST_REMOVE_HEAD(&spy->write_queue.list, frame_list)))
1416                 ast_frfree(f);
1417         while ((f = AST_LIST_REMOVE_HEAD(&spy->read_queue.list, frame_list)))
1418                 ast_frfree(f);
1419
1420         /* Destroy the condition if in use */
1421         if (ast_test_flag(spy, CHANSPY_TRIGGER_MODE) != CHANSPY_TRIGGER_NONE)
1422                 ast_cond_destroy(&spy->trigger);
1423
1424         /* Destroy our mutex since it is no longer in use */
1425         ast_mutex_destroy(&spy->lock);
1426
1427         return;
1428 }
1429
1430 static void detach_spies(struct ast_channel *chan)
1431 {
1432         struct ast_channel_spy *spy = NULL;
1433
1434         if (!chan->spies)
1435                 return;
1436
1437         AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->spies->list, spy, list) {
1438                 AST_LIST_REMOVE_CURRENT(&chan->spies->list, list);
1439                 spy_detach(spy, chan);
1440         }
1441         AST_LIST_TRAVERSE_SAFE_END
1442
1443         spy_cleanup(chan);
1444 }
1445
1446 /*! \brief Softly hangup a channel, don't lock */
1447 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
1448 {
1449         ast_debug(1, "Soft-Hanging up channel '%s'\n", chan->name);
1450         /* Inform channel driver that we need to be hung up, if it cares */
1451         chan->_softhangup |= cause;
1452         ast_queue_frame(chan, &ast_null_frame);
1453         /* Interrupt any poll call or such */
1454         if (ast_test_flag(chan, AST_FLAG_BLOCKING))
1455                 pthread_kill(chan->blocker, SIGURG);
1456         return 0;
1457 }
1458
1459 /*! \brief Softly hangup a channel, lock */
1460 int ast_softhangup(struct ast_channel *chan, int cause)
1461 {
1462         int res;
1463         ast_channel_lock(chan);
1464         res = ast_softhangup_nolock(chan, cause);
1465         ast_channel_unlock(chan);
1466         return res;
1467 }
1468
1469 enum spy_direction {
1470         SPY_READ,
1471         SPY_WRITE,
1472 };
1473
1474 #define SPY_QUEUE_SAMPLE_LIMIT 4000                     /* half of one second */
1475
1476 static void queue_frame_to_spies(struct ast_channel *chan, struct ast_frame *f, enum spy_direction dir)
1477 {
1478         struct ast_frame *translated_frame = NULL;
1479         struct ast_channel_spy *spy;
1480         struct channel_spy_trans *trans;
1481
1482         trans = (dir == SPY_READ) ? &chan->spies->read_translator : &chan->spies->write_translator;
1483
1484         AST_LIST_TRAVERSE(&chan->spies->list, spy, list) {
1485                 struct ast_channel_spy_queue *queue;
1486                 struct ast_frame *duped_fr;
1487
1488                 if (spy->status != CHANSPY_RUNNING)
1489                         continue;
1490
1491                 ast_mutex_lock(&spy->lock);
1492
1493                 queue = (dir == SPY_READ) ? &spy->read_queue : &spy->write_queue;
1494
1495                 if ((queue->format == AST_FORMAT_SLINEAR) && (f->subclass != AST_FORMAT_SLINEAR)) {
1496                         if (!translated_frame) {
1497                                 if (trans->path && (trans->last_format != f->subclass)) {
1498                                         ast_translator_free_path(trans->path);
1499                                         trans->path = NULL;
1500                                 }
1501                                 if (!trans->path) {
1502                                         ast_debug(1, "Building translator from %s to SLINEAR for spies on channel %s\n",
1503                                                         ast_getformatname(f->subclass), chan->name);
1504                                         if ((trans->path = ast_translator_build_path(AST_FORMAT_SLINEAR, f->subclass)) == NULL) {
1505                                                 ast_log(LOG_WARNING, "Cannot build a path from %s to %s\n",
1506                                                         ast_getformatname(f->subclass), ast_getformatname(AST_FORMAT_SLINEAR));
1507                                                 ast_mutex_unlock(&spy->lock);
1508                                                 continue;
1509                                         } else {
1510                                                 trans->last_format = f->subclass;
1511                                         }
1512                                 }
1513                                 if (!(translated_frame = ast_translate(trans->path, f, 0))) {
1514                                         ast_log(LOG_ERROR, "Translation to %s failed, dropping frame for spies\n",
1515                                                 ast_getformatname(AST_FORMAT_SLINEAR));
1516                                         ast_mutex_unlock(&spy->lock);
1517                                         break;
1518                                 }
1519                         }
1520                         duped_fr = ast_frdup(translated_frame);
1521                 } else if (f->subclass != queue->format) {
1522                         ast_log(LOG_WARNING, "Spy '%s' on channel '%s' wants format '%s', but frame is '%s', dropping\n",
1523                                 spy->type, chan->name,
1524                                 ast_getformatname(queue->format), ast_getformatname(f->subclass));
1525                         ast_mutex_unlock(&spy->lock);
1526                         continue;
1527                 } else
1528                         duped_fr = ast_frdup(f);
1529
1530                 AST_LIST_INSERT_TAIL(&queue->list, duped_fr, frame_list);
1531
1532                 queue->samples += f->samples;
1533
1534                 if (queue->samples > SPY_QUEUE_SAMPLE_LIMIT) {
1535                         if (ast_test_flag(spy, CHANSPY_TRIGGER_MODE) != CHANSPY_TRIGGER_NONE) {
1536                                 switch (ast_test_flag(spy, CHANSPY_TRIGGER_MODE)) {
1537                                 case CHANSPY_TRIGGER_READ:
1538                                         if (dir == SPY_WRITE) {
1539                                                 ast_set_flag(spy, CHANSPY_TRIGGER_WRITE);
1540                                                 ast_clear_flag(spy, CHANSPY_TRIGGER_READ);
1541                                                 ast_debug(1, "Switching spy '%s' on '%s' to write-trigger mode\n",
1542                                                         spy->type, chan->name);
1543                                         }
1544                                         break;
1545                                 case CHANSPY_TRIGGER_WRITE:
1546                                         if (dir == SPY_READ) {
1547                                                 ast_set_flag(spy, CHANSPY_TRIGGER_READ);
1548                                                 ast_clear_flag(spy, CHANSPY_TRIGGER_WRITE);
1549                                                 ast_debug(1, "Switching spy '%s' on '%s' to read-trigger mode\n",
1550                                                         spy->type, chan->name);
1551                                         }
1552                                         break;
1553                                 }
1554                                 ast_debug(1, "Triggering queue flush for spy '%s' on '%s'\n",
1555                                         spy->type, chan->name);
1556                                 ast_set_flag(spy, CHANSPY_TRIGGER_FLUSH);
1557                                 ast_cond_signal(&spy->trigger);
1558                         } else {
1559                                 ast_debug(1, "Spy '%s' on channel '%s' %s queue too long, dropping frames\n",
1560                                         spy->type, chan->name, (dir == SPY_READ) ? "read" : "write");
1561                                 while (queue->samples > SPY_QUEUE_SAMPLE_LIMIT) {
1562                                         struct ast_frame *drop = AST_LIST_REMOVE_HEAD(&queue->list, frame_list);
1563                                         queue->samples -= drop->samples;
1564                                         ast_frfree(drop);
1565                                 }
1566                         }
1567                 } else {
1568                         switch (ast_test_flag(spy, CHANSPY_TRIGGER_MODE)) {
1569                         case CHANSPY_TRIGGER_READ:
1570                                 if (dir == SPY_READ)
1571                                         ast_cond_signal(&spy->trigger);
1572                                 break;
1573                         case CHANSPY_TRIGGER_WRITE:
1574                                 if (dir == SPY_WRITE)
1575                                         ast_cond_signal(&spy->trigger);
1576                                 break;
1577                         }
1578                 }
1579
1580                 ast_mutex_unlock(&spy->lock);
1581         }
1582
1583         if (translated_frame)
1584                 ast_frfree(translated_frame);
1585 }
1586
1587 static void free_translation(struct ast_channel *clone)
1588 {
1589         if (clone->writetrans)
1590                 ast_translator_free_path(clone->writetrans);
1591         if (clone->readtrans)
1592                 ast_translator_free_path(clone->readtrans);
1593         clone->writetrans = NULL;
1594         clone->readtrans = NULL;
1595         clone->rawwriteformat = clone->nativeformats;
1596         clone->rawreadformat = clone->nativeformats;
1597 }
1598
1599 /*! \brief Hangup a channel */
1600 int ast_hangup(struct ast_channel *chan)
1601 {
1602         int res = 0;
1603         struct ast_cdr *cdr = NULL;
1604
1605         /* Don't actually hang up a channel that will masquerade as someone else, or
1606            if someone is going to masquerade as us */
1607         ast_channel_lock(chan);
1608
1609         detach_spies(chan);             /* get rid of spies */
1610
1611         if (chan->masq) {
1612                 if (ast_do_masquerade(chan))
1613                         ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1614         }
1615
1616         if (chan->masq) {
1617                 ast_log(LOG_WARNING, "%s getting hung up, but someone is trying to masq into us?!?\n", chan->name);
1618                 ast_channel_unlock(chan);
1619                 return 0;
1620         }
1621         /* If this channel is one which will be masqueraded into something,
1622            mark it as a zombie already, so we know to free it later */
1623         if (chan->masqr) {
1624                 ast_set_flag(chan, AST_FLAG_ZOMBIE);
1625                 ast_channel_unlock(chan);
1626                 return 0;
1627         }
1628         free_translation(chan);
1629         /* Close audio stream */
1630         if (chan->stream) {
1631                 ast_closestream(chan->stream);
1632                 chan->stream = NULL;
1633         }
1634         /* Close video stream */
1635         if (chan->vstream) {
1636                 ast_closestream(chan->vstream);
1637                 chan->vstream = NULL;
1638         }
1639         if (chan->sched) {
1640                 sched_context_destroy(chan->sched);
1641                 chan->sched = NULL;
1642         }
1643         
1644         if (chan->generatordata)        /* Clear any tone stuff remaining */
1645                 if (chan->generator && chan->generator->release)
1646                         chan->generator->release(chan, chan->generatordata);
1647         chan->generatordata = NULL;
1648         chan->generator = NULL;
1649         if (chan->cdr) {                /* End the CDR if it hasn't already */
1650                 ast_cdr_end(chan->cdr);
1651                 cdr = chan->cdr;
1652                 chan->cdr = NULL;
1653         }
1654         if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
1655                 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
1656                                         "is blocked by thread %ld in procedure %s!  Expect a failure\n",
1657                                         (long)pthread_self(), chan->name, (long)chan->blocker, chan->blockproc);
1658                 CRASH;
1659         }
1660         if (!ast_test_flag(chan, AST_FLAG_ZOMBIE)) {
1661                 ast_debug(1, "Hanging up channel '%s'\n", chan->name);
1662                 if (chan->tech->hangup)
1663                         res = chan->tech->hangup(chan);
1664         } else {
1665                 ast_debug(1, "Hanging up zombie '%s'\n", chan->name);
1666         }
1667                         
1668         ast_channel_unlock(chan);
1669         manager_event(EVENT_FLAG_CALL, "Hangup",
1670                         "Channel: %s\r\n"
1671                         "Uniqueid: %s\r\n"
1672                         "Cause: %d\r\n"
1673                         "Cause-txt: %s\r\n",
1674                         chan->name,
1675                         chan->uniqueid,
1676                         chan->hangupcause,
1677                         ast_cause2str(chan->hangupcause)
1678                         );
1679         ast_channel_free(chan);
1680
1681         if (cdr)
1682                 ast_cdr_detach(cdr);
1683
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         int begin_digit = 0;
1993
1994         /* Stop if we're a zombie or need a soft hangup */
1995         if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
1996                 return -1;
1997         /* Wait for a digit, no more than ms milliseconds total. */
1998         while (ms) {
1999                 struct ast_channel *rchan;
2000                 int outfd;
2001
2002                 errno = 0;
2003                 rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
2004                 if (!rchan && outfd < 0 && ms) {
2005                         if (errno == 0 || errno == EINTR)
2006                                 continue;
2007                         ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
2008                         return -1;
2009                 } else if (outfd > -1) {
2010                         /* The FD we were watching has something waiting */
2011                         return 1;
2012                 } else if (rchan) {
2013                         int res;
2014                         struct ast_frame *f = ast_read(c);
2015                         if (!f)
2016                                 return -1;
2017
2018                         switch (f->frametype) {
2019                         case AST_FRAME_DTMF_BEGIN:
2020                                 begin_digit = f->subclass;
2021                                 break;
2022                         case AST_FRAME_DTMF_END:
2023                                 if (begin_digit != f->subclass)
2024                                         break;
2025                                 res = f->subclass;
2026                                 ast_frfree(f);
2027                                 return res;
2028                         case AST_FRAME_CONTROL:
2029                                 switch (f->subclass) {
2030                                 case AST_CONTROL_HANGUP:
2031                                         ast_frfree(f);
2032                                         return -1;
2033                                 case AST_CONTROL_RINGING:
2034                                 case AST_CONTROL_ANSWER:
2035                                         /* Unimportant */
2036                                         break;
2037                                 default:
2038                                         ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", f->subclass);
2039                                         break;
2040                                 }
2041                                 break;
2042                         case AST_FRAME_VOICE:
2043                                 /* Write audio if appropriate */
2044                                 if (audiofd > -1)
2045                                         write(audiofd, f->data, f->datalen);
2046                         default:
2047                                 /* Ignore */
2048                                 break;
2049                         }
2050                         ast_frfree(f);
2051                 }
2052         }
2053         return 0; /* Time is up */
2054 }
2055
2056 static void send_dtmf_event(const struct ast_channel *chan, const char *direction, const char digit, const char *begin, const char *end)
2057 {
2058         manager_event(EVENT_FLAG_DTMF,
2059                         "DTMF",
2060                         "Channel: %s\r\n"
2061                         "Uniqueid: %s\r\n"
2062                         "Digit: %c\r\n"
2063                         "Direction: %s\r\n"
2064                         "Begin: %s\r\n"
2065                         "End: %s\r\n",
2066                         chan->name, chan->uniqueid, digit, direction, begin, end);
2067 }
2068
2069 static void ast_read_generator_actions(struct ast_channel *chan, struct ast_frame *f)
2070 {
2071         if (chan->generatordata &&  !ast_internal_timing_enabled(chan)) {
2072                 void *tmp = chan->generatordata;
2073                 int res;
2074
2075                 if (chan->timingfunc) {
2076                         if (option_debug > 1)
2077                                 ast_log(LOG_DEBUG, "Generator got voice, switching to phase locked mode\n");
2078                         ast_settimeout(chan, 0, NULL, NULL);
2079                 }
2080
2081                 chan->generatordata = NULL;     /* reset, to let writes go through */
2082                 res = chan->generator->generate(chan, tmp, f->datalen, f->samples);
2083                 chan->generatordata = tmp;
2084                 if (res) {
2085                         if (option_debug > 1)
2086                                 ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
2087                         ast_deactivate_generator(chan);
2088                 }
2089
2090         } else if (f->frametype == AST_FRAME_CNG) {
2091                 if (chan->generator && !chan->timingfunc && (chan->timingfd > -1)) {
2092                         if (option_debug > 1)
2093                                 ast_log(LOG_DEBUG, "Generator got CNG, switching to timed mode\n");
2094                         ast_settimeout(chan, 160, generator_force, chan);
2095                 }
2096         }
2097 }
2098
2099 static struct ast_frame *__ast_read(struct ast_channel *chan, int dropaudio)
2100 {
2101         struct ast_frame *f = NULL;     /* the return value */
2102         int blah;
2103         int prestate;
2104
2105         /* this function is very long so make sure there is only one return
2106          * point at the end (there is only one exception to this).
2107          */
2108         ast_channel_lock(chan);
2109         if (chan->masq) {
2110                 if (ast_do_masquerade(chan))
2111                         ast_log(LOG_WARNING, "Failed to perform masquerade\n");
2112                 else
2113                         f =  &ast_null_frame;
2114                 goto done;
2115         }
2116
2117         /* Stop if we're a zombie or need a soft hangup */
2118         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2119                 if (chan->generator)
2120                         ast_deactivate_generator(chan);
2121                 goto done;
2122         }
2123         prestate = chan->_state;
2124
2125         if (!ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_EMULATE_DTMF | AST_FLAG_IN_DTMF) && 
2126             !ast_strlen_zero(chan->dtmfq) && 
2127                 (ast_tvzero(chan->dtmf_tv) || ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) > AST_MIN_DTMF_GAP) ) {
2128                 /* We have DTMF that has been deferred.  Return it now */
2129                 chan->dtmff.subclass = chan->dtmfq[0];
2130                 /* Drop first digit from the buffer */
2131                 memmove(chan->dtmfq, chan->dtmfq + 1, sizeof(chan->dtmfq) - 1);
2132                 f = &chan->dtmff;
2133                 if (ast_test_flag(chan, AST_FLAG_END_DTMF_ONLY)) {
2134                         ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass, chan->name);
2135                         chan->dtmff.frametype = AST_FRAME_DTMF_END;
2136                 } else {
2137                         ast_log(LOG_DTMF, "DTMF begin emulation of '%c' with duration %d queued on %s\n", f->subclass, AST_DEFAULT_EMULATE_DTMF_DURATION, chan->name);
2138                         chan->dtmff.frametype = AST_FRAME_DTMF_BEGIN;
2139                         ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
2140                         chan->emulate_dtmf_digit = f->subclass;
2141                         chan->emulate_dtmf_duration = AST_DEFAULT_EMULATE_DTMF_DURATION;
2142                 }
2143                 chan->dtmf_tv = ast_tvnow();
2144                 goto done;
2145         }
2146         
2147         /* Read and ignore anything on the alertpipe, but read only
2148            one sizeof(blah) per frame that we send from it */
2149         if (chan->alertpipe[0] > -1)
2150                 read(chan->alertpipe[0], &blah, sizeof(blah));
2151
2152 #ifdef HAVE_ZAPTEL
2153         if (chan->timingfd > -1 && chan->fdno == AST_TIMING_FD && ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
2154                 int res;
2155
2156                 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
2157                 blah = -1;
2158                 /* IF we can't get event, assume it's an expired as-per the old interface */
2159                 res = ioctl(chan->timingfd, ZT_GETEVENT, &blah);
2160                 if (res)
2161                         blah = ZT_EVENT_TIMER_EXPIRED;
2162
2163                 if (blah == ZT_EVENT_TIMER_PING) {
2164                         if (AST_LIST_EMPTY(&chan->readq) || !AST_LIST_NEXT(AST_LIST_FIRST(&chan->readq), frame_list)) {
2165                                 /* Acknowledge PONG unless we need it again */
2166                                 if (ioctl(chan->timingfd, ZT_TIMERPONG, &blah)) {
2167                                         ast_log(LOG_WARNING, "Failed to pong timer on '%s': %s\n", chan->name, strerror(errno));
2168                                 }
2169                         }
2170                 } else if (blah == ZT_EVENT_TIMER_EXPIRED) {
2171                         ioctl(chan->timingfd, ZT_TIMERACK, &blah);
2172                         if (chan->timingfunc) {
2173                                 /* save a copy of func/data before unlocking the channel */
2174                                 int (*func)(void *) = chan->timingfunc;
2175                                 void *data = chan->timingdata;
2176                                 ast_channel_unlock(chan);
2177                                 func(data);
2178                         } else {
2179                                 blah = 0;
2180                                 ioctl(chan->timingfd, ZT_TIMERCONFIG, &blah);
2181                                 chan->timingdata = NULL;
2182                                 ast_channel_unlock(chan);
2183                         }
2184                         /* cannot 'goto done' because the channel is already unlocked */
2185                         return &ast_null_frame;
2186                 } else
2187                         ast_log(LOG_NOTICE, "No/unknown event '%d' on timer for '%s'?\n", blah, chan->name);
2188         } else
2189 #endif
2190         if (chan->fds[AST_GENERATOR_FD] > -1 && chan->fdno == AST_GENERATOR_FD) {
2191                 /* if the AST_GENERATOR_FD is set, call the generator with args
2192                  * set to -1 so it can do whatever it needs to.
2193                  */
2194                 void *tmp = chan->generatordata;
2195                 chan->generatordata = NULL;     /* reset to let ast_write get through */
2196                 chan->generator->generate(chan, tmp, -1, -1);
2197                 chan->generatordata = tmp;
2198                 f = &ast_null_frame;
2199                 goto done;
2200         }
2201
2202         /* Check for pending read queue */
2203         if (!AST_LIST_EMPTY(&chan->readq)) {
2204                 f = AST_LIST_REMOVE_HEAD(&chan->readq, frame_list);
2205                 /* Interpret hangup and return NULL */
2206                 /* XXX why not the same for frames from the channel ? */
2207                 if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP) {
2208                         ast_frfree(f);
2209                         f = NULL;
2210                 }
2211         } else {
2212                 chan->blocker = pthread_self();
2213                 if (ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
2214                         if (chan->tech->exception)
2215                                 f = chan->tech->exception(chan);
2216                         else {
2217                                 ast_log(LOG_WARNING, "Exception flag set on '%s', but no exception handler\n", chan->name);
2218                                 f = &ast_null_frame;
2219                         }
2220                         /* Clear the exception flag */
2221                         ast_clear_flag(chan, AST_FLAG_EXCEPTION);
2222                 } else if (chan->tech->read)
2223                         f = chan->tech->read(chan);
2224                 else
2225                         ast_log(LOG_WARNING, "No read routine on channel %s\n", chan->name);
2226         }
2227
2228         if (f) {
2229                 /* if the channel driver returned more than one frame, stuff the excess
2230                    into the readq for the next ast_read call (note that we can safely assume
2231                    that the readq is empty, because otherwise we would not have called into
2232                    the channel driver and f would be only a single frame)
2233                 */
2234                 if (AST_LIST_NEXT(f, frame_list)) {
2235                         AST_LIST_HEAD_SET_NOLOCK(&chan->readq, AST_LIST_NEXT(f, frame_list));
2236                         AST_LIST_NEXT(f, frame_list) = NULL;
2237                 }
2238
2239                 switch (f->frametype) {
2240                 case AST_FRAME_CONTROL:
2241                         if (f->subclass == AST_CONTROL_ANSWER) {
2242                                 if (!ast_test_flag(chan, AST_FLAG_OUTGOING)) {
2243                                         ast_debug(1, "Ignoring answer on an inbound call!\n");
2244                                         ast_frfree(f);
2245                                         f = &ast_null_frame;
2246                                 } else if (prestate == AST_STATE_UP) {
2247                                         ast_debug(1, "Dropping duplicate answer!\n");
2248                                         ast_frfree(f);
2249                                         f = &ast_null_frame;
2250                                 } else {
2251                                         /* Answer the CDR */
2252                                         ast_setstate(chan, AST_STATE_UP);
2253                                         if (!chan->cdr) { /* up till now, this insertion hasn't been done. Therefore,
2254                                                                                  to keep from throwing off the basic order of the universe,
2255                                                                                  we will try to keep this cdr from getting posted. */
2256                                                 chan->cdr = ast_cdr_alloc();
2257                                                 ast_cdr_init(chan->cdr, chan);
2258                                                 ast_cdr_start(chan->cdr);
2259                                         }
2260                                         
2261                                         ast_cdr_answer(chan->cdr);
2262                                 }
2263                         }
2264                         break;
2265                 case AST_FRAME_DTMF_END:
2266                         send_dtmf_event(chan, "Received", f->subclass, "No", "Yes");
2267                         ast_log(LOG_DTMF, "DTMF end '%c' received on %s, duration %ld ms\n", f->subclass, chan->name, f->len);
2268                         /* Queue it up if DTMF is deffered, or if DTMF emulation is forced.
2269                          * However, only let emulation be forced if the other end cares about BEGIN frames */
2270                         if ( ast_test_flag(chan, AST_FLAG_DEFER_DTMF) ||
2271                                 (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !ast_test_flag(chan, AST_FLAG_END_DTMF_ONLY)) ) {
2272                                 if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2)
2273                                         chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
2274                                 else
2275                                         ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
2276                                 ast_frfree(f);
2277                                 f = &ast_null_frame;
2278                         } else if (!ast_test_flag(chan, AST_FLAG_IN_DTMF | AST_FLAG_END_DTMF_ONLY)) {
2279                                 if (!ast_tvzero(chan->dtmf_tv) && 
2280                                     ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) < AST_MIN_DTMF_GAP) {
2281                                         /* If it hasn't been long enough, defer this digit */
2282                                         if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2)
2283                                                 chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
2284                                         else
2285                                                 ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
2286                                         ast_frfree(f);
2287                                         f = &ast_null_frame;
2288                                 } else {
2289                                         /* There was no begin, turn this into a begin and send the end later */
2290                                         f->frametype = AST_FRAME_DTMF_BEGIN;
2291                                         ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
2292                                         chan->emulate_dtmf_digit = f->subclass;
2293                                         chan->dtmf_tv = ast_tvnow();
2294                                         if (f->len) {
2295                                                 if (f->len > AST_MIN_DTMF_DURATION)
2296                                                         chan->emulate_dtmf_duration = f->len;
2297                                                 else 
2298                                                         chan->emulate_dtmf_duration = AST_MIN_DTMF_DURATION;
2299                                         } else
2300                                                 chan->emulate_dtmf_duration = AST_DEFAULT_EMULATE_DTMF_DURATION;
2301                                         ast_log(LOG_DTMF, "DTMF begin emulation of '%c' with duration %u queued on %s\n", f->subclass, chan->emulate_dtmf_duration, chan->name);
2302                                 }
2303                         } else {
2304                                 struct timeval now = ast_tvnow();
2305                                 if (ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
2306                                         ast_clear_flag(chan, AST_FLAG_IN_DTMF);
2307                                         if (!f->len)
2308                                                 f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
2309                                 } else if (!f->len)
2310                                         f->len = AST_MIN_DTMF_DURATION;
2311                                 if (f->len < AST_MIN_DTMF_DURATION) {
2312                                         ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
2313                                         chan->emulate_dtmf_digit = f->subclass;
2314                                         chan->emulate_dtmf_duration = AST_MIN_DTMF_DURATION - f->len;
2315                                         f = &ast_null_frame;
2316                                 } else
2317                                         chan->dtmf_tv = now;
2318                         }
2319                         break;
2320                 case AST_FRAME_DTMF_BEGIN:
2321                         send_dtmf_event(chan, "Received", f->subclass, "Yes", "No");
2322                         ast_log(LOG_DTMF, "DTMF begin '%c' received on %s\n", f->subclass, chan->name);
2323                         if ( ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_END_DTMF_ONLY) || 
2324                             (!ast_tvzero(chan->dtmf_tv) && 
2325                               ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) < AST_MIN_DTMF_GAP) ) {
2326                                 ast_frfree(f);
2327                                 f = &ast_null_frame;
2328                         } else {
2329                                 ast_set_flag(chan, AST_FLAG_IN_DTMF);
2330                                 chan->dtmf_tv = ast_tvnow();
2331                         }
2332                         break;
2333                 case AST_FRAME_NULL:
2334                         if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF)) {
2335                                 struct timeval now = ast_tvnow();
2336                                 if (ast_tvdiff_ms(now, chan->dtmf_tv) >= chan->emulate_dtmf_duration) {
2337                                         chan->emulate_dtmf_duration = 0;
2338                                         ast_frfree(f);
2339                                         f = &chan->dtmff;
2340                                         f->frametype = AST_FRAME_DTMF_END;
2341                                         f->subclass = chan->emulate_dtmf_digit;
2342                                         f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
2343                                         chan->dtmf_tv = now;
2344                                         ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
2345                                         chan->emulate_dtmf_digit = 0;
2346                                         ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass, chan->name);
2347                                 }
2348                         }
2349                         break;
2350                 case AST_FRAME_VOICE:
2351                         /* The EMULATE_DTMF flag must be cleared here as opposed to when the duration
2352                          * is reached , because we want to make sure we pass at least one
2353                          * voice frame through before starting the next digit, to ensure a gap
2354                          * between DTMF digits. */
2355                         if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !chan->emulate_dtmf_duration) {
2356                                 ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
2357                                 chan->emulate_dtmf_digit = 0;
2358                         }
2359
2360                         if (dropaudio || ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
2361                                 if (dropaudio)
2362                                         ast_read_generator_actions(chan, f);
2363                                 ast_frfree(f);
2364                                 f = &ast_null_frame;
2365                         }
2366
2367                         if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
2368                                 struct timeval now = ast_tvnow();
2369                                 if (ast_tvdiff_ms(now, chan->dtmf_tv) >= chan->emulate_dtmf_duration) {
2370                                         chan->emulate_dtmf_duration = 0;
2371                                         ast_frfree(f);
2372                                         f = &chan->dtmff;
2373                                         f->frametype = AST_FRAME_DTMF_END;
2374                                         f->subclass = chan->emulate_dtmf_digit;
2375                                         f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
2376                                         chan->dtmf_tv = now;
2377                                         ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass, chan->name);
2378                                 } else {
2379                                         /* Drop voice frames while we're still in the middle of the digit */
2380                                         ast_frfree(f);
2381                                         f = &ast_null_frame;
2382                                 }
2383                         } else if ((f->frametype == AST_FRAME_VOICE) && !(f->subclass & chan->nativeformats)) {
2384                                 /* This frame can't be from the current native formats -- drop it on the
2385                                    floor */
2386                                 ast_log(LOG_NOTICE, "Dropping incompatible voice frame on %s of format %s since our native format has changed to %s\n",
2387                                         chan->name, ast_getformatname(f->subclass), ast_getformatname(chan->nativeformats));
2388                                 ast_frfree(f);
2389                                 f = &ast_null_frame;
2390                         } else if ((f->frametype == AST_FRAME_VOICE)) {
2391                                 if (chan->spies)
2392                                         queue_frame_to_spies(chan, f, SPY_READ);
2393                                 
2394                                 if (chan->monitor && chan->monitor->read_stream ) {
2395                                         /* XXX what does this do ? */
2396 #ifndef MONITOR_CONSTANT_DELAY
2397                                         int jump = chan->outsmpl - chan->insmpl - 4 * f->samples;
2398                                         if (jump >= 0) {
2399                                                 jump = chan->outsmpl - chan->insmpl;
2400                                                 if (ast_seekstream(chan->monitor->read_stream, jump, SEEK_FORCECUR) == -1)
2401                                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
2402                                                 chan->insmpl += jump + f->samples;
2403                                         } else
2404                                                 chan->insmpl+= f->samples;
2405 #else
2406                                         int jump = chan->outsmpl - chan->insmpl;
2407                                         if (jump - MONITOR_DELAY >= 0) {
2408                                                 if (ast_seekstream(chan->monitor->read_stream, jump - f->samples, SEEK_FORCECUR) == -1)
2409                                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
2410                                                 chan->insmpl += jump;
2411                                         } else
2412                                                 chan->insmpl += f->samples;
2413 #endif
2414                                         if (chan->monitor->state == AST_MONITOR_RUNNING) {
2415                                                 if (ast_writestream(chan->monitor->read_stream, f) < 0)
2416                                                         ast_log(LOG_WARNING, "Failed to write data to channel monitor read stream\n");
2417                                         }
2418                                 }
2419
2420                                 if (chan->readtrans && (f = ast_translate(chan->readtrans, f, 1)) == NULL)
2421                                         f = &ast_null_frame;
2422                                 else
2423                                         /* Run generator sitting on the line if timing device not available
2424                                          * and synchronous generation of outgoing frames is necessary       */
2425                                         ast_read_generator_actions(chan, f);
2426                         }
2427                 default:
2428                         /* Just pass it on! */
2429                         break;
2430                 }
2431         } else {
2432                 /* Make sure we always return NULL in the future */
2433                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
2434                 if (chan->generator)
2435                         ast_deactivate_generator(chan);
2436                 /* End the CDR if appropriate */
2437                 if (chan->cdr)
2438                         ast_cdr_end(chan->cdr);
2439         }
2440
2441         /* High bit prints debugging */
2442         if (chan->fin & DEBUGCHAN_FLAG)
2443                 ast_frame_dump(chan->name, f, "<<");
2444         chan->fin = FRAMECOUNT_INC(chan->fin);
2445
2446 done:
2447         if (chan->music_state && chan->generator && chan->generator->digit && f && f->frametype == AST_FRAME_DTMF_END)
2448                 chan->generator->digit(chan, f->subclass);
2449
2450         ast_channel_unlock(chan);
2451         return f;
2452 }
2453
2454 int ast_internal_timing_enabled(struct ast_channel *chan)
2455 {
2456         int ret = ast_opt_internal_timing && chan->timingfd > -1;
2457         ast_debug(5, "Internal timing is %s (option_internal_timing=%d chan->timingfd=%d)\n", ret? "enabled": "disabled", ast_opt_internal_timing, chan->timingfd);
2458         return ret;
2459 }
2460
2461 struct ast_frame *ast_read(struct ast_channel *chan)
2462 {
2463         return __ast_read(chan, 0);
2464 }
2465
2466 struct ast_frame *ast_read_noaudio(struct ast_channel *chan)
2467 {
2468         return __ast_read(chan, 1);
2469 }
2470
2471 int ast_indicate(struct ast_channel *chan, int condition)
2472 {
2473         return ast_indicate_data(chan, condition, NULL, 0);
2474 }
2475
2476 int ast_indicate_data(struct ast_channel *chan, int condition, const void *data, size_t datalen)
2477 {
2478         int res = -1;
2479
2480         ast_channel_lock(chan);
2481         /* Stop if we're a zombie or need a soft hangup */
2482         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2483                 ast_channel_unlock(chan);
2484                 return -1;
2485         }
2486         if (chan->tech->indicate)
2487                 res = chan->tech->indicate(chan, condition, data, datalen);
2488         ast_channel_unlock(chan);
2489         if (!chan->tech->indicate || res) {
2490                 /*
2491                  * Device does not support (that) indication, lets fake
2492                  * it by doing our own tone generation. (PM2002)
2493                  */
2494                 if (condition < 0)
2495                         ast_playtones_stop(chan);
2496                 else {
2497                         const struct ind_tone_zone_sound *ts = NULL;
2498                         switch (condition) {
2499                         case AST_CONTROL_RINGING:
2500                                 ts = ast_get_indication_tone(chan->zone, "ring");
2501                                 break;
2502                         case AST_CONTROL_BUSY:
2503                                 ts = ast_get_indication_tone(chan->zone, "busy");
2504                                 break;
2505                         case AST_CONTROL_CONGESTION:
2506                                 ts = ast_get_indication_tone(chan->zone, "congestion");
2507                                 break;
2508                         }
2509                         if (ts && ts->data[0]) {
2510                                 ast_debug(1, "Driver for channel '%s' does not support indication %d, emulating it\n", chan->name, condition);
2511                                 ast_playtones_start(chan,0,ts->data, 1);
2512                                 res = 0;
2513                         } else if (condition == AST_CONTROL_PROGRESS) {
2514                                 /* ast_playtones_stop(chan); */
2515                         } else if (condition == AST_CONTROL_PROCEEDING) {
2516                                 /* Do nothing, really */
2517                         } else if (condition == AST_CONTROL_HOLD) {
2518                                 /* Do nothing.... */
2519                         } else if (condition == AST_CONTROL_UNHOLD) {
2520                                 /* Do nothing.... */
2521                         } else if (condition == AST_CONTROL_VIDUPDATE) {
2522                                 /* Do nothing.... */
2523                         } else {
2524                                 /* not handled */
2525                                 ast_log(LOG_WARNING, "Unable to handle indication %d for '%s'\n", condition, chan->name);
2526                                 res = -1;
2527                         }
2528                 }
2529         }
2530         return res;
2531 }
2532
2533 int ast_recvchar(struct ast_channel *chan, int timeout)
2534 {
2535         int c;
2536         char *buf = ast_recvtext(chan, timeout);
2537         if (buf == NULL)
2538                 return -1;      /* error or timeout */
2539         c = *(unsigned char *)buf;
2540         ast_free(buf);
2541         return c;
2542 }
2543
2544 char *ast_recvtext(struct ast_channel *chan, int timeout)
2545 {
2546         int res, done = 0;
2547         char *buf = NULL;
2548         
2549         while (!done) {
2550                 struct ast_frame *f;
2551                 if (ast_check_hangup(chan))
2552                         break;
2553                 res = ast_waitfor(chan, timeout);
2554                 if (res <= 0) /* timeout or error */
2555                         break;
2556                 timeout = res;  /* update timeout */
2557                 f = ast_read(chan);
2558                 if (f == NULL)
2559                         break; /* no frame */
2560                 if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP)
2561                         done = 1;       /* force a break */
2562                 else if (f->frametype == AST_FRAME_TEXT) {              /* what we want */
2563                         buf = ast_strndup((char *) f->data, f->datalen);        /* dup and break */
2564                         done = 1;
2565                 }
2566                 ast_frfree(f);
2567         }
2568         return buf;
2569 }
2570
2571 int ast_sendtext(struct ast_channel *chan, const char *text)
2572 {
2573         int res = 0;
2574         /* Stop if we're a zombie or need a soft hangup */
2575         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
2576                 return -1;
2577         CHECK_BLOCKING(chan);
2578         if (chan->tech->send_text)
2579                 res = chan->tech->send_text(chan, text);
2580         ast_clear_flag(chan, AST_FLAG_BLOCKING);
2581         return res;
2582 }
2583
2584 int ast_senddigit_begin(struct ast_channel *chan, char digit)
2585 {
2586         /* Device does not support DTMF tones, lets fake
2587          * it by doing our own generation. */
2588         static const char* dtmf_tones[] = {
2589                 "941+1336", /* 0 */
2590                 "697+1209", /* 1 */
2591                 "697+1336", /* 2 */
2592                 "697+1477", /* 3 */
2593                 "770+1209", /* 4 */
2594                 "770+1336", /* 5 */
2595                 "770+1477", /* 6 */
2596                 "852+1209", /* 7 */
2597                 "852+1336", /* 8 */
2598                 "852+1477", /* 9 */
2599                 "697+1633", /* A */
2600                 "770+1633", /* B */
2601                 "852+1633", /* C */
2602                 "941+1633", /* D */
2603                 "941+1209", /* * */
2604                 "941+1477"  /* # */
2605         };
2606
2607         if (!chan->tech->send_digit_begin)
2608                 return 0;
2609
2610         if (!chan->tech->send_digit_begin(chan, digit))
2611                 return 0;
2612
2613         if (digit >= '0' && digit <='9')
2614                 ast_playtones_start(chan, 0, dtmf_tones[digit-'0'], 0);
2615         else if (digit >= 'A' && digit <= 'D')
2616                 ast_playtones_start(chan, 0, dtmf_tones[digit-'A'+10], 0);
2617         else if (digit == '*')
2618                 ast_playtones_start(chan, 0, dtmf_tones[14], 0);
2619         else if (digit == '#')
2620                 ast_playtones_start(chan, 0, dtmf_tones[15], 0);
2621         else {
2622                 /* not handled */
2623                 ast_debug(1, "Unable to generate DTMF tone '%c' for '%s'\n", digit, chan->name);
2624         }
2625
2626         return 0;
2627 }
2628
2629 int ast_senddigit_end(struct ast_channel *chan, char digit, unsigned int duration)
2630 {
2631         int res = -1;
2632
2633         if (chan->tech->send_digit_end)
2634                 res = chan->tech->send_digit_end(chan, digit, duration);
2635
2636         if (res && chan->generator)
2637                 ast_playtones_stop(chan);
2638         
2639         return 0;
2640 }
2641
2642 int ast_senddigit(struct ast_channel *chan, char digit)
2643 {
2644         if (chan->tech->send_digit_begin) {
2645                 ast_senddigit_begin(chan, digit);
2646                 ast_safe_sleep(chan, AST_DEFAULT_EMULATE_DTMF_DURATION);
2647         }
2648         
2649         return ast_senddigit_end(chan, digit, AST_DEFAULT_EMULATE_DTMF_DURATION);
2650 }
2651
2652 int ast_prod(struct ast_channel *chan)
2653 {
2654         struct ast_frame a = { AST_FRAME_VOICE };
2655         char nothing[128];
2656
2657         /* Send an empty audio frame to get things moving */
2658         if (chan->_state != AST_STATE_UP) {
2659                 ast_debug(1, "Prodding channel '%s'\n", chan->name);
2660                 a.subclass = chan->rawwriteformat;
2661                 a.data = nothing + AST_FRIENDLY_OFFSET;
2662                 a.src = "ast_prod";
2663                 if (ast_write(chan, &a))
2664                         ast_log(LOG_WARNING, "Prodding channel '%s' failed\n", chan->name);
2665         }
2666         return 0;
2667 }
2668
2669 int ast_write_video(struct ast_channel *chan, struct ast_frame *fr)
2670 {
2671         int res;
2672         if (!chan->tech->write_video)
2673                 return 0;
2674         res = ast_write(chan, fr);
2675         if (!res)
2676                 res = 1;
2677         return res;
2678 }
2679
2680 int ast_write(struct ast_channel *chan, struct ast_frame *fr)
2681 {
2682         int res = -1;
2683         struct ast_frame *f = NULL;
2684
2685         /* Stop if we're a zombie or need a soft hangup */
2686         ast_channel_lock(chan);
2687         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
2688                 goto done;
2689
2690         /* Handle any pending masquerades */
2691         if (chan->masq && ast_do_masquerade(chan)) {
2692                 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
2693                 goto done;
2694         }
2695         if (chan->masqr) {
2696                 res = 0;        /* XXX explain, why 0 ? */
2697                 goto done;
2698         }
2699         if (chan->generatordata) {
2700                 if (ast_test_flag(chan, AST_FLAG_WRITE_INT))
2701                         ast_deactivate_generator(chan);
2702                 else {
2703                         if (fr->frametype == AST_FRAME_DTMF_END) {
2704                                 /* There is a generator running while we're in the middle of a digit.
2705                                  * It's probably inband DTMF, so go ahead and pass it so it can
2706                                  * stop the generator */
2707                                 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2708                                 ast_channel_unlock(chan);
2709                                 res = ast_senddigit_end(chan, fr->subclass, fr->len);
2710                                 ast_channel_lock(chan);
2711                                 CHECK_BLOCKING(chan);
2712                         } else if (fr->frametype == AST_FRAME_CONTROL && fr->subclass == AST_CONTROL_UNHOLD) {
2713                                 /* This is a side case where Echo is basically being called and the person put themselves on hold and took themselves off hold */
2714                                 res = (chan->tech->indicate == NULL) ? 0 :
2715                                         chan->tech->indicate(chan, fr->subclass, fr->data, fr->datalen);
2716                         }
2717                         res = 0;        /* XXX explain, why 0 ? */
2718                         goto done;
2719                 }
2720         }
2721         /* High bit prints debugging */
2722         if (chan->fout & DEBUGCHAN_FLAG)
2723                 ast_frame_dump(chan->name, fr, ">>");
2724         CHECK_BLOCKING(chan);
2725         switch (fr->frametype) {
2726         case AST_FRAME_CONTROL:
2727                 res = (chan->tech->indicate == NULL) ? 0 :
2728                         chan->tech->indicate(chan, fr->subclass, fr->data, fr->datalen);
2729                 break;
2730         case AST_FRAME_DTMF_BEGIN:
2731                 send_dtmf_event(chan, "Sent", fr->subclass, "Yes", "No");
2732                 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2733                 ast_channel_unlock(chan);
2734                 res = ast_senddigit_begin(chan, fr->subclass);
2735                 ast_channel_lock(chan);
2736                 CHECK_BLOCKING(chan);
2737                 break;
2738         case AST_FRAME_DTMF_END:
2739                 send_dtmf_event(chan, "Sent", fr->subclass, "No", "Yes");
2740                 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2741                 ast_channel_unlock(chan);
2742                 res = ast_senddigit_end(chan, fr->subclass, fr->len);
2743                 ast_channel_lock(chan);
2744                 CHECK_BLOCKING(chan);
2745                 break;
2746         case AST_FRAME_TEXT:
2747                 if (fr->subclass == AST_FORMAT_T140) {
2748                         res = (chan->tech->write_text == NULL) ? 0 :
2749                                 chan->tech->write_text(chan, fr);
2750                 } else {
2751                         res = (chan->tech->send_text == NULL) ? 0 :
2752                                 chan->tech->send_text(chan, (char *) fr->data);
2753                 }
2754                 break;
2755         case AST_FRAME_HTML:
2756                 res = (chan->tech->send_html == NULL) ? 0 :
2757                         chan->tech->send_html(chan, fr->subclass, (char *) fr->data, fr->datalen);
2758                 break;
2759         case AST_FRAME_VIDEO:
2760                 /* XXX Handle translation of video codecs one day XXX */
2761                 res = (chan->tech->write_video == NULL) ? 0 :
2762                         chan->tech->write_video(chan, fr);
2763                 break;
2764         case AST_FRAME_MODEM:
2765                 res = (chan->tech->write == NULL) ? 0 :
2766                         chan->tech->write(chan, fr);
2767                 break;
2768         case AST_FRAME_VOICE:
2769                 if (chan->tech->write == NULL)
2770                         break;  /*! \todo XXX should return 0 maybe ? */
2771
2772                 /* If someone is whispering on this channel then we must ensure that we are always getting signed linear frames */
2773                 if (ast_test_flag(chan, AST_FLAG_WHISPER)) {
2774                         if (fr->subclass == AST_FORMAT_SLINEAR)
2775                                 f = fr;
2776                         else {
2777                                 ast_mutex_lock(&chan->whisper->lock);
2778                                 if (chan->writeformat != AST_FORMAT_SLINEAR) {
2779                                         /* Rebuild the translation path and set our write format back to signed linear */
2780                                         chan->whisper->original_format = chan->writeformat;
2781                                         ast_set_write_format(chan, AST_FORMAT_SLINEAR);
2782                                         if (chan->whisper->path)
2783                                                 ast_translator_free_path(chan->whisper->path);
2784                                         chan->whisper->path = ast_translator_build_path(AST_FORMAT_SLINEAR, chan->whisper->original_format);
2785                                 }
2786                                 /* Translate frame using the above translation path */
2787                                 f = (chan->whisper->path) ? ast_translate(chan->whisper->path, fr, 0) : fr;
2788                                 ast_mutex_unlock(&chan->whisper->lock);
2789                         }
2790                 } else {
2791                         /* If the frame is in the raw write format, then it's easy... just use the frame - otherwise we will have to translate */
2792                         if (fr->subclass == chan->rawwriteformat)
2793                                 f = fr;
2794                         else
2795                                 f = (chan->writetrans) ? ast_translate(chan->writetrans, fr, 0) : fr;
2796                 }
2797
2798                 /* If we have no frame of audio, then we have to bail out */
2799                 if (f == NULL) {
2800                         res = 0;
2801                         break;
2802                 }
2803
2804                 /* If spies are on the channel then queue the frame out to them */
2805                 if (chan->spies)
2806                         queue_frame_to_spies(chan, f, SPY_WRITE);
2807
2808                 /* If Monitor is running on this channel, then we have to write frames out there too */
2809                 if (chan->monitor && chan->monitor->write_stream) {
2810                         /* XXX must explain this code */
2811 #ifndef MONITOR_CONSTANT_DELAY
2812                         int jump = chan->insmpl - chan->outsmpl - 4 * f->samples;
2813                         if (jump >= 0) {
2814                                 jump = chan->insmpl - chan->outsmpl;
2815                                 if (ast_seekstream(chan->monitor->write_stream, jump, SEEK_FORCECUR) == -1)
2816                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
2817                                 chan->outsmpl += jump + f->samples;
2818                         } else
2819                                 chan->outsmpl += f->samples;
2820 #else
2821                         int jump = chan->insmpl - chan->outsmpl;
2822                         if (jump - MONITOR_DELAY >= 0) {
2823                                 if (ast_seekstream(chan->monitor->write_stream, jump - f->samples, SEEK_FORCECUR) == -1)
2824                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
2825                                 chan->outsmpl += jump;
2826                         } else
2827                                 chan->outsmpl += f->samples;
2828 #endif
2829                         if (chan->monitor->state == AST_MONITOR_RUNNING) {
2830                                 if (ast_writestream(chan->monitor->write_stream, f) < 0)
2831                                         ast_log(LOG_WARNING, "Failed to write data to channel monitor write stream\n");
2832                         }
2833                 }
2834
2835                 /* Finally the good part! Write this out to the channel */
2836                 if (ast_test_flag(chan, AST_FLAG_WHISPER)) {
2837                         /* frame is assumed to be in SLINEAR, since that is
2838                            required for whisper mode */
2839                         ast_frame_adjust_volume(f, -2);
2840                         if (ast_slinfactory_available(&chan->whisper->sf) >= f->samples) {
2841                                 short buf[f->samples];
2842                                 struct ast_frame whisper = {
2843                                         .frametype = AST_FRAME_VOICE,
2844                                         .subclass = AST_FORMAT_SLINEAR,
2845                                         .data = buf,
2846                                         .datalen = sizeof(buf),
2847                                         .samples = f->samples,
2848                                 };
2849                                 
2850                                 ast_mutex_lock(&chan->whisper->lock);
2851                                 if (ast_slinfactory_read(&chan->whisper->sf, buf, f->samples))
2852                                         ast_frame_slinear_sum(f, &whisper);
2853                                 ast_mutex_unlock(&chan->whisper->lock);
2854                         }
2855                         /* and now put it through the regular translator */
2856                         f = (chan->writetrans) ? ast_translate(chan->writetrans, f, 0) : f;
2857                 }
2858                 res = f ? chan->tech->write(chan, f) : 0;
2859                 break;
2860         case AST_FRAME_NULL:
2861         case AST_FRAME_IAX:
2862                 /* Ignore these */
2863                 res = 0;
2864                 break;
2865         default:
2866                 /* At this point, fr is the incoming frame and f is NULL.  Channels do
2867                  * not expect to get NULL as a frame pointer and will segfault.  Hence,
2868                  * we output the original frame passed in. */
2869                 res = chan->tech->write(chan, fr);
2870                 break;
2871         }
2872
2873         if (f && f != fr)
2874                 ast_frfree(f);
2875         ast_clear_flag(chan, AST_FLAG_BLOCKING);
2876         /* Consider a write failure to force a soft hangup */
2877         if (res < 0)
2878                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
2879         else {
2880                 chan->fout = FRAMECOUNT_INC(chan->fout);
2881         }
2882 done:
2883         ast_channel_unlock(chan);
2884         return res;
2885 }
2886
2887 static int set_format(struct ast_channel *chan, int fmt, int *rawformat, int *format,
2888                       struct ast_trans_pvt **trans, const int direction)
2889 {
2890         int native;
2891         int res;
2892         
2893         /* Make sure we only consider audio */
2894         fmt &= AST_FORMAT_AUDIO_MASK;
2895         
2896         native = chan->nativeformats;
2897         /* Find a translation path from the native format to one of the desired formats */
2898         if (!direction)
2899                 /* reading */
2900                 res = ast_translator_best_choice(&fmt, &native);
2901         else
2902                 /* writing */
2903                 res = ast_translator_best_choice(&native, &fmt);
2904
2905         if (res < 0) {
2906                 ast_log(LOG_WARNING, "Unable to find a codec translation path from %s to %s\n",
2907                         ast_getformatname(native), ast_getformatname(fmt));
2908                 return -1;
2909         }
2910         
2911         /* Now we have a good choice for both. */
2912         ast_channel_lock(chan);
2913
2914         if ((*rawformat == native) && (*format == fmt) && ((*rawformat == *format) || (*trans))) {
2915                 /* the channel is already in these formats, so nothing to do */
2916                 ast_channel_unlock(chan);
2917                 return 0;
2918         }
2919
2920         *rawformat = native;
2921         /* User perspective is fmt */
2922         *format = fmt;
2923         /* Free any read translation we have right now */
2924         if (*trans)
2925                 ast_translator_free_path(*trans);
2926         /* Build a translation path from the raw format to the desired format */
2927         if (!direction)
2928                 /* reading */
2929                 *trans = ast_translator_build_path(*format, *rawformat);
2930         else
2931                 /* writing */
2932                 *trans = ast_translator_build_path(*rawformat, *format);
2933         ast_channel_unlock(chan);
2934         ast_debug(1, "Set channel %s to %s format %s\n", chan->name,
2935                 direction ? "write" : "read", ast_getformatname(fmt));
2936         return 0;
2937 }
2938
2939 int ast_set_read_format(struct ast_channel *chan, int fmt)
2940 {
2941         return set_format(chan, fmt, &chan->rawreadformat, &chan->readformat,
2942                           &chan->readtrans, 0);
2943 }
2944
2945 int ast_set_write_format(struct ast_channel *chan, int fmt)
2946 {
2947         return set_format(chan, fmt, &chan->rawwriteformat, &chan->writeformat,
2948                           &chan->writetrans, 1);
2949 }
2950
2951 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)
2952 {
2953         int dummy_outstate;
2954         int cause = 0;
2955         struct ast_channel *chan;
2956         int res = 0;
2957         
2958         if (outstate)
2959                 *outstate = 0;
2960         else
2961                 outstate = &dummy_outstate;     /* make outstate always a valid pointer */
2962
2963         chan = ast_request(type, format, data, &cause);
2964         if (!chan) {
2965                 ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
2966                 /* compute error and return */
2967                 if (cause == AST_CAUSE_BUSY)
2968                         *outstate = AST_CONTROL_BUSY;
2969                 else if (cause == AST_CAUSE_CONGESTION)
2970                         *outstate = AST_CONTROL_CONGESTION;
2971                 return NULL;
2972         }
2973
2974         if (oh) {
2975                 if (oh->vars)   
2976                         ast_set_variables(chan, oh->vars);
2977                 /* XXX why is this necessary, for the parent_channel perhaps ? */
2978                 if (!ast_strlen_zero(oh->cid_num) && !ast_strlen_zero(oh->cid_name))
2979                         ast_set_callerid(chan, oh->cid_num, oh->cid_name, oh->cid_num);
2980                 if (oh->parent_channel) {
2981                         ast_channel_inherit_variables(oh->parent_channel, chan);
2982                         ast_channel_datastore_inherit(oh->parent_channel, chan);
2983                 }
2984                 if (oh->account)
2985                         ast_cdr_setaccount(chan, oh->account);  
2986         }
2987         ast_set_callerid(chan, cid_num, cid_name, cid_num);
2988
2989         
2990
2991         if (!chan->cdr) { /* up till now, this insertion hasn't been done. Therefore,
2992                                 to keep from throwing off the basic order of the universe,
2993                                 we will try to keep this cdr from getting posted. */
2994                 chan->cdr = ast_cdr_alloc();
2995                 ast_cdr_init(chan->cdr, chan);
2996                 ast_cdr_start(chan->cdr);
2997         }
2998         if (ast_call(chan, data, 0)) {  /* ast_call failed... */
2999                 ast_log(LOG_NOTICE, "Unable to call channel %s/%s\n", type, (char *)data);
3000         } else {
3001                 res = 1;        /* mark success in case chan->_state is already AST_STATE_UP */
3002                 while (timeout && chan->_state != AST_STATE_UP) {
3003                         struct ast_frame *f;
3004                         res = ast_waitfor(chan, timeout);
3005                         if (res <= 0) /* error, timeout, or done */
3006                                 break;
3007                         if (timeout > -1)
3008                                 timeout = res;
3009                         f = ast_read(chan);
3010                         if (!f) {
3011                                 *outstate = AST_CONTROL_HANGUP;
3012                                 res = 0;
3013                                 break;
3014                         }
3015                         if (f->frametype == AST_FRAME_CONTROL) {
3016                                 switch (f->subclass) {
3017                                 case AST_CONTROL_RINGING:       /* record but keep going */
3018                                         *outstate = f->subclass;
3019                                         break;
3020
3021                                 case AST_CONTROL_BUSY:
3022                                 case AST_CONTROL_CONGESTION:
3023                                 case AST_CONTROL_ANSWER:
3024                                         *outstate = f->subclass;
3025                                         timeout = 0;            /* trick to force exit from the while() */
3026                                         break;
3027
3028                                 /* Ignore these */
3029                                 case AST_CONTROL_PROGRESS:
3030                                 case AST_CONTROL_PROCEEDING:
3031                                 case AST_CONTROL_HOLD:
3032                                 case AST_CONTROL_UNHOLD:
3033                                 case AST_CONTROL_VIDUPDATE:
3034                                 case -1:                        /* Ignore -- just stopping indications */
3035                                         break;
3036
3037                                 default:
3038                                         ast_log(LOG_NOTICE, "Don't know what to do with control frame %d\n", f->subclass);
3039                                 }
3040                         }
3041                         ast_frfree(f);
3042                 }
3043         }
3044
3045         /* Final fixups */
3046         if (oh) {
3047                 if (!ast_strlen_zero(oh->context))
3048                         ast_copy_string(chan->context, oh->context, sizeof(chan->context));
3049                 if (!ast_strlen_zero(oh->exten))
3050                         ast_copy_string(chan->exten, oh->exten, sizeof(chan->exten));
3051                 if (oh->priority)       
3052                         chan->priority = oh->priority;
3053         }
3054         if (chan->_state == AST_STATE_UP)
3055                 *outstate = AST_CONTROL_ANSWER;
3056
3057         if (res <= 0) {
3058                 if (!chan->cdr && (chan->cdr = ast_cdr_alloc()))
3059                         ast_cdr_init(chan->cdr, chan);
3060                 if (chan->cdr) {
3061                         char tmp[256];
3062                         snprintf(tmp, sizeof(tmp), "%s/%s", type, (char *)data);
3063                         ast_cdr_setapp(chan->cdr,"Dial",tmp);
3064                         ast_cdr_update(chan);
3065                         ast_cdr_start(chan->cdr);
3066                         ast_cdr_end(chan->cdr);
3067                         /* If the cause wasn't handled properly */
3068                         if (ast_cdr_disposition(chan->cdr,chan->hangupcause))
3069                                 ast_cdr_failed(chan->cdr);
3070                 }
3071                 ast_hangup(chan);
3072                 chan = NULL;
3073         }
3074         return chan;
3075 }
3076
3077 struct ast_channel *ast_request_and_dial(const char *type, int format, void *data, int timeout, int *outstate, const char *cidnum, const char *cidname)
3078 {
3079         return __ast_request_and_dial(type, format, data, timeout, outstate, cidnum, cidname, NULL);
3080 }
3081
3082 struct ast_channel *ast_request(const char *type, int format, void *data, int *cause)
3083 {
3084         struct chanlist *chan;
3085         struct ast_channel *c;
3086         int capabilities;
3087         int fmt;
3088         int res;
3089         int foo;
3090         int videoformat = format & AST_FORMAT_VIDEO_MASK;
3091         int textformat = format & AST_FORMAT_TEXT_MASK;
3092
3093         if (!cause)
3094                 cause = &foo;
3095         *cause = AST_CAUSE_NOTDEFINED;
3096
3097         if (AST_RWLIST_RDLOCK(&channels)) {
3098                 ast_log(LOG_WARNING, "Unable to lock channel list\n");
3099                 return NULL;
3100         }
3101
3102         AST_LIST_TRAVERSE(&backends, chan, list) {
3103                 if (strcasecmp(type, chan->tech->type))
3104                         continue;
3105
3106                 capabilities = chan->tech->capabilities;
3107                 fmt = format & AST_FORMAT_AUDIO_MASK;
3108                 res = ast_translator_best_choice(&fmt, &capabilities);
3109                 if (res < 0) {
3110                         ast_log(LOG_WARNING, "No translator path exists for channel type %s (native %d) to %d\n", type, chan->tech->capabilities, format);
3111                         *cause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
3112                         AST_RWLIST_UNLOCK(&channels);
3113                         return NULL;
3114                 }
3115                 AST_RWLIST_UNLOCK(&channels);
3116                 if (!chan->tech->requester)
3117                         return NULL;
3118                 
3119                 if (!(c = chan->tech->requester(type, capabilities | videoformat | textformat, data, cause)))
3120                         return NULL;
3121                 
3122                 /* no need to generate a Newchannel event here; it is done in the channel_alloc call */
3123                 return c;
3124         }
3125
3126         ast_log(LOG_WARNING, "No channel type registered for '%s'\n", type);
3127         *cause = AST_CAUSE_NOSUCHDRIVER;
3128         AST_RWLIST_UNLOCK(&channels);
3129
3130         return NULL;
3131 }
3132
3133 int ast_call(struct ast_channel *chan, char *addr, int timeout)
3134 {
3135         /* Place an outgoing call, but don't wait any longer than timeout ms before returning.
3136            If the remote end does not answer within the timeout, then do NOT hang up, but
3137            return anyway.  */
3138         int res = -1;
3139         /* Stop if we're a zombie or need a soft hangup */
3140         ast_channel_lock(chan);
3141         if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
3142                 if (chan->tech->call)
3143                         res = chan->tech->call(chan, addr, timeout);
3144                 ast_set_flag(chan, AST_FLAG_OUTGOING);
3145         }
3146         ast_channel_unlock(chan);
3147         return res;
3148 }
3149
3150 /*!
3151   \brief Transfer a call to dest, if the channel supports transfer
3152
3153   Called by:
3154     \arg app_transfer
3155     \arg the manager interface
3156 */
3157 int ast_transfer(struct ast_channel *chan, char *dest)
3158 {
3159         int res = -1;
3160
3161         /* Stop if we're a zombie or need a soft hangup */
3162         ast_channel_lock(chan);
3163         if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
3164                 if (chan->tech->transfer) {
3165                         res = chan->tech->transfer(chan, dest);
3166                         if (!res)
3167                                 res = 1;
3168                 } else
3169                         res = 0;
3170         }
3171         ast_channel_unlock(chan);
3172         return res;
3173 }
3174
3175 int ast_readstring(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders)
3176 {
3177         return ast_readstring_full(c, s, len, timeout, ftimeout, enders, -1, -1);
3178 }
3179
3180 int ast_readstring_full(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders, int audiofd, int ctrlfd)
3181 {
3182         int pos = 0;    /* index in the buffer where we accumulate digits */
3183         int to = ftimeout;
3184
3185         /* Stop if we're a zombie or need a soft hangup */
3186         if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
3187                 return -1;
3188         if (!len)
3189                 return -1;
3190         for (;;) {
3191                 int d;
3192                 if (c->stream) {
3193                         d = ast_waitstream_full(c, AST_DIGIT_ANY, audiofd, ctrlfd);
3194                         ast_stopstream(c);
3195                         usleep(1000);
3196                         if (!d)
3197                                 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
3198                 } else {
3199                         d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
3200                 }
3201                 if (d < 0)
3202                         return -1;
3203                 if (d == 0) {
3204                         s[pos]='\0';
3205                         return 1;
3206                 }
3207                 if (d == 1) {
3208                         s[pos]='\0';
3209                         return 2;
3210                 }
3211                 if (!strchr(enders, d))
3212                         s[pos++] = d;
3213                 if (strchr(enders, d) || (pos >= len)) {
3214                         s[pos]='\0';
3215                         return 0;
3216                 }
3217                 to = timeout;
3218         }
3219         /* Never reached */
3220         return 0;
3221 }
3222
3223 int ast_channel_supports_html(struct ast_channel *chan)
3224 {
3225         return (chan->tech->send_html) ? 1 : 0;
3226 }
3227
3228 int ast_channel_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
3229 {
3230         if (chan->tech->send_html)
3231                 return chan->tech->send_html(chan, subclass, data, datalen);
3232         return -1;
3233 }
3234
3235 int ast_channel_sendurl(struct ast_channel *chan, const char *url)
3236 {
3237         return ast_channel_sendhtml(chan, AST_HTML_URL, url, strlen(url) + 1);
3238 }
3239
3240 /*! \brief Set up translation from one channel to another */
3241 static int ast_channel_make_compatible_helper(struct ast_channel *from, struct ast_channel *to)
3242 {
3243         int src;
3244         int dst;
3245
3246         if (from->readformat == to->writeformat && from->writeformat == to->readformat) {
3247                 /* Already compatible!  Moving on ... */
3248                 return 0;
3249         }
3250
3251         /* Set up translation from the 'from' channel to the 'to' channel */
3252         src = from->nativeformats;
3253         dst = to->nativeformats;
3254         if (ast_translator_best_choice(&dst, &src) < 0) {
3255                 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", from->name, src, to->name, dst);
3256                 return -1;
3257         }
3258
3259         /* if the best path is not 'pass through', then
3260            transcoding is needed; if desired, force transcode path
3261            to use SLINEAR between channels, but only if there is
3262            no direct conversion available */
3263         if ((src != dst) && ast_opt_transcode_via_slin &&
3264             (ast_translate_path_steps(dst, src) != 1))
3265                 dst = AST_FORMAT_SLINEAR;
3266         if (ast_set_read_format(from, dst) < 0) {
3267                 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", from->name, dst);
3268                 return -1;
3269         }
3270         if (ast_set_write_format(to, dst) < 0) {
3271                 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", to->name, dst);
3272                 return -1;
3273         }
3274         return 0;
3275 }
3276
3277 int ast_channel_make_compatible(struct ast_channel *chan, struct ast_channel *peer)
3278 {
3279         /* Some callers do not check return code, and we must try to set all call legs correctly */
3280         int rc = 0;
3281
3282         /* Set up translation from the chan to the peer */
3283         rc = ast_channel_make_compatible_helper(chan, peer);
3284
3285         if (rc < 0)
3286                 return rc;
3287
3288         /* Set up translation from the peer to the chan */
3289         rc = ast_channel_make_compatible_helper(peer, chan);
3290
3291         return rc;
3292 }
3293
3294 int ast_channel_masquerade(struct ast_channel *original, struct ast_channel *clone)
3295 {
3296         int res = -1;
3297         struct ast_channel *final_orig = original, *final_clone = clone;
3298
3299         ast_channel_lock(original);
3300         while (ast_channel_trylock(clone)) {
3301                 ast_channel_unlock(original);
3302                 usleep(1);
3303                 ast_channel_lock(original);
3304         }
3305
3306         /* each of these channels may be sitting behind a channel proxy (i.e. chan_agent)
3307            and if so, we don't really want to masquerade it, but its proxy */
3308         if (original->_bridge && (original->_bridge != ast_bridged_channel(original)) && (original->_bridge->_bridge != original))
3309                 final_orig = original->_bridge;
3310
3311         if (clone->_bridge && (clone->_bridge != ast_bridged_channel(clone)) && (clone->_bridge->_bridge != clone))
3312                 final_clone = clone->_bridge;
3313
3314         if ((final_orig != original) || (final_clone != clone)) {
3315                 ast_channel_lock(final_orig);
3316                 while (ast_channel_trylock(final_clone)) {
3317                         ast_channel_unlock(final_orig);
3318                         usleep(1);
3319                         ast_channel_lock(final_orig);
3320                 }
3321                 ast_channel_unlock(clone);
3322                 ast_channel_unlock(original);
3323                 original = final_orig;
3324                 clone = final_clone;
3325         }
3326
3327         if (original == clone) {
3328                 ast_log(LOG_WARNING, "Can't masquerade channel '%s' into itself!\n", original->name);
3329                 ast_channel_unlock(clone);
3330                 ast_channel_unlock(original);
3331                 return -1;
3332         }
3333
3334         ast_debug(1, "Planning to masquerade channel %s into the structure of %s\n",
3335                 clone->name, original->name);
3336         if (original->masq) {
3337                 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n",
3338                         original->masq->name, original->name);
3339         } else if (clone->masqr) {
3340                 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n",
3341                         clone->name, clone->masqr->name);
3342         } else {
3343                 original->masq = clone;
3344                 clone->masqr = original;
3345                 ast_queue_frame(original, &ast_null_frame);
3346                 ast_queue_frame(clone, &ast_null_frame);
3347                 ast_debug(1, "Done planning to masquerade channel %s into the structure of %s\n", clone->name, original->name);
3348                 res = 0;
3349         }
3350
3351         ast_channel_unlock(clone);
3352         ast_channel_unlock(original);
3353
3354         return res;
3355 }
3356
3357 void ast_change_name(struct ast_channel *chan, char *newname)
3358 {
3359         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", chan->name, newname, chan->uniqueid);
3360         ast_string_field_set(chan, name, newname);
3361 }
3362
3363 void ast_channel_inherit_variables(const struct ast_channel *parent, struct ast_channel *child)
3364 {
3365         struct ast_var_t *current, *newvar;
3366         const char *varname;
3367
3368         AST_LIST_TRAVERSE(&parent->varshead, current, entries) {
3369                 int vartype = 0;
3370
3371                 varname = ast_var_full_name(current);
3372                 if (!varname)
3373                         continue;
3374
3375                 if (varname[0] == '_') {
3376                         vartype = 1;
3377                         if (varname[1] == '_')
3378                                 vartype = 2;
3379                 }
3380
3381                 switch (vartype) {
3382                 case 1:
3383                         newvar = ast_var_assign(&varname[1], ast_var_value(current));
3384                         if (newvar) {
3385                                 AST_LIST_INSERT_TAIL(&child->varshead, newvar, entries);
3386                                 ast_debug(1, "Copying soft-transferable variable %s.\n", ast_var_name(newvar));
3387                         }
3388                         break;
3389                 case 2:
3390                         newvar = ast_var_assign(ast_var_full_name(current), ast_var_value(current));
3391                         if (newvar) {
3392                                 AST_LIST_INSERT_TAIL(&child->varshead, newvar, entries);
3393                                 ast_debug(1, "Copying hard-transferable variable %s.\n", ast_var_name(newvar));
3394                         }
3395                         break;
3396                 default:
3397                         ast_debug(1, "Not copying variable %s.\n", ast_var_name(current));
3398                         break;
3399                 }
3400         }
3401 }
3402
3403 /*!
3404   \brief Clone channel variables from 'clone' channel into 'original' channel
3405
3406   All variables except those related to app_groupcount are cloned.
3407   Variables are actually _removed_ from 'clone' channel, presumably
3408   because it will subsequently be destroyed.
3409
3410   \note Assumes locks will be in place on both channels when called.
3411 */
3412 static void clone_variables(struct ast_channel *original, struct ast_channel *clone)
3413 {
3414         struct ast_var_t *current, *newvar;
3415         /* Append variables from clone channel into original channel */
3416         /* XXX Is this always correct?  We have to in order to keep MACROS working XXX */
3417         if (AST_LIST_FIRST(&clone->varshead))
3418                 AST_LIST_APPEND_LIST(&original->varshead, &clone->varshead, entries);
3419         AST_LIST_HEAD_INIT_NOLOCK(&clone->varshead);
3420
3421         /* then, dup the varshead list into the clone */
3422         
3423         AST_LIST_TRAVERSE(&original->varshead, current, entries) {
3424                 newvar = ast_var_assign(current->name, current->value);
3425                 if (newvar)
3426                         AST_LIST_INSERT_TAIL(&clone->varshead, newvar, entries);
3427         }
3428 }
3429
3430 /*!
3431   \brief Masquerade a channel
3432
3433   \note Assumes channel will be locked when called
3434 */
3435 int ast_do_masquerade(struct ast_channel *original)
3436 {
3437         int x,i;
3438         int res=0;
3439         int origstate;
3440         struct ast_frame *cur;
3441         const struct ast_channel_tech *t;
3442         void *t_pvt;
3443         struct ast_callerid tmpcid;
3444         struct ast_channel *clone = original->masq;
3445         struct ast_channel_spy_list *spy_list = NULL;
3446         struct ast_channel_spy *spy = NULL;
3447         struct ast_cdr *cdr;
3448         int rformat = original->readformat;
3449         int wformat = original->writeformat;
3450         char newn[100];
3451         char orig[100];
3452         char masqn[100];
3453         char zombn[100];
3454
3455         ast_debug(4, "Actually Masquerading %s(%d) into the structure of %s(%d)\n",
3456                 clone->name, clone->_state, original->name, original->_state);
3457
3458         manager_event(EVENT_FLAG_CALL, "Masquerade", "Clone: %s\r\nCloneState: %s\r\nOriginal: %s\r\nOriginalState: %s\r\n",
3459                       clone->name, ast_state2str(clone->_state), original->name, ast_state2str(original->_state));
3460
3461         /* XXX This is a seriously wacked out operation.  We're essentially putting the guts of
3462            the clone channel into the original channel.  Start by killing off the original
3463            channel's backend.   I'm not sure we're going to keep this function, because
3464            while the features are nice, the cost is very high in terms of pure nastiness. XXX */
3465
3466         /* We need the clone's lock, too */
3467         ast_channel_lock(clone);
3468
3469         ast_debug(2, "Got clone lock for masquerade on '%s' at %p\n", clone->name, &clone->lock);
3470
3471         /* Having remembered the original read/write formats, we turn off any translation on either
3472            one */
3473         free_translation(clone);
3474         free_translation(original);
3475
3476
3477         /* Unlink the masquerade */
3478         original->masq = NULL;
3479         clone->masqr = NULL;
3480         
3481         /* Save the original name */
3482         ast_copy_string(orig, original->name, sizeof(orig));
3483         /* Save the new name */
3484         ast_copy_string(newn, clone->name, sizeof(newn));
3485         /* Create the masq name */
3486         snprintf(masqn, sizeof(masqn), "%s<MASQ>", newn);
3487                 
3488         /* Copy the name from the clone channel */
3489         ast_string_field_set(original, name, newn);
3490
3491         /* Mangle the name of the clone channel */
3492         ast_string_field_set(clone, name, masqn);
3493         
3494         /* Notify any managers of the change, first the masq then the other */
3495         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", newn, masqn, clone->uniqueid);
3496         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", orig, newn, original->uniqueid);
3497
3498         /* Swap the technologies */     
3499         t = original->tech;
3500         original->tech = clone->tech;
3501         clone->tech = t;
3502
3503         /* Swap the cdrs */
3504         cdr = original->cdr;
3505         original->cdr = clone->cdr;
3506         clone->cdr = cdr;
3507
3508         t_pvt = original->tech_pvt;
3509         original->tech_pvt = clone->tech_pvt;
3510         clone->tech_pvt = t_pvt;
3511
3512         /* Swap the readq's */
3513         cur = AST_LIST_FIRST(&original->readq);
3514         AST_LIST_HEAD_SET_NOLOCK(&original->readq, AST_LIST_FIRST(&clone->readq));
3515         AST_LIST_HEAD_SET_NOLOCK(&clone->readq, cur);
3516
3517         /* Swap the alertpipes */
3518         for (i = 0; i < 2; i++) {
3519                 x = original->alertpipe[i];
3520            &