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