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