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