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