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