Don't use ast_frdup() in the AST_LIST_INSERT_TAIL macro directly. That was a
[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 void ast_channel_spy_stop_by_type(struct ast_channel *chan, const char *type)
1207 {
1208         struct ast_channel_spy *spy;
1209         
1210         if (!chan->spies)
1211                 return;
1212
1213         AST_LIST_TRAVERSE(&chan->spies->list, spy, list) {
1214                 ast_mutex_lock(&spy->lock);
1215                 if ((spy->type == type) && (spy->status == CHANSPY_RUNNING)) {
1216                         spy->status = CHANSPY_STOP;
1217                         if (ast_test_flag(spy, CHANSPY_TRIGGER_MODE) != CHANSPY_TRIGGER_NONE)
1218                                 ast_cond_signal(&spy->trigger);
1219                 }
1220                 ast_mutex_unlock(&spy->lock);
1221         }
1222 }
1223
1224 void ast_channel_spy_trigger_wait(struct ast_channel_spy *spy)
1225 {
1226         struct timeval tv;
1227         struct timespec ts;
1228
1229         tv = ast_tvadd(ast_tvnow(), ast_samp2tv(50000, 1000));
1230         ts.tv_sec = tv.tv_sec;
1231         ts.tv_nsec = tv.tv_usec * 1000;
1232
1233         ast_cond_timedwait(&spy->trigger, &spy->lock, &ts);
1234 }
1235
1236 void ast_channel_spy_remove(struct ast_channel *chan, struct ast_channel_spy *spy)
1237 {
1238         struct ast_frame *f;
1239
1240         if (!chan->spies)
1241                 return;
1242
1243         AST_LIST_REMOVE(&chan->spies->list, spy, list);
1244
1245         ast_mutex_lock(&spy->lock);
1246
1247         spy->chan = NULL;
1248
1249         while ((f = AST_LIST_REMOVE_HEAD(&spy->read_queue.list, frame_list)))
1250                 ast_frfree(f);
1251         
1252         while ((f = AST_LIST_REMOVE_HEAD(&spy->write_queue.list, frame_list)))
1253                 ast_frfree(f);
1254
1255         if (ast_test_flag(spy, CHANSPY_TRIGGER_MODE) != CHANSPY_TRIGGER_NONE)
1256                 ast_cond_destroy(&spy->trigger);
1257
1258         ast_mutex_unlock(&spy->lock);
1259
1260         ast_log(LOG_DEBUG, "Spy %s removed from channel %s\n",
1261                 spy->type, chan->name);
1262
1263         if (AST_LIST_EMPTY(&chan->spies->list)) {
1264                 if (chan->spies->read_translator.path)
1265                         ast_translator_free_path(chan->spies->read_translator.path);
1266                 if (chan->spies->write_translator.path)
1267                         ast_translator_free_path(chan->spies->write_translator.path);
1268                 free(chan->spies);
1269                 chan->spies = NULL;
1270         }
1271 }
1272
1273 static void detach_spies(struct ast_channel *chan)
1274 {
1275         struct ast_channel_spy *spy;
1276
1277         if (!chan->spies)
1278                 return;
1279
1280         /* Marking the spies as done is sufficient.  Chanspy or spy users will get the picture. */
1281         AST_LIST_TRAVERSE(&chan->spies->list, spy, list) {
1282                 ast_mutex_lock(&spy->lock);
1283                 spy->chan = NULL;
1284                 if (spy->status == CHANSPY_RUNNING)
1285                         spy->status = CHANSPY_DONE;
1286                 if (ast_test_flag(spy, CHANSPY_TRIGGER_MODE) != CHANSPY_TRIGGER_NONE)
1287                         ast_cond_signal(&spy->trigger);
1288                 ast_mutex_unlock(&spy->lock);
1289         }
1290
1291         AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->spies->list, spy, list)
1292                 ast_channel_spy_remove(chan, spy);
1293         AST_LIST_TRAVERSE_SAFE_END;
1294 }
1295
1296 /*! \brief Softly hangup a channel, don't lock */
1297 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
1298 {
1299         if (option_debug)
1300                 ast_log(LOG_DEBUG, "Soft-Hanging up channel '%s'\n", chan->name);
1301         /* Inform channel driver that we need to be hung up, if it cares */
1302         chan->_softhangup |= cause;
1303         ast_queue_frame(chan, &ast_null_frame);
1304         /* Interrupt any poll call or such */
1305         if (ast_test_flag(chan, AST_FLAG_BLOCKING))
1306                 pthread_kill(chan->blocker, SIGURG);
1307         return 0;
1308 }
1309
1310 /*! \brief Softly hangup a channel, lock */
1311 int ast_softhangup(struct ast_channel *chan, int cause)
1312 {
1313         int res;
1314         ast_channel_lock(chan);
1315         res = ast_softhangup_nolock(chan, cause);
1316         ast_channel_unlock(chan);
1317         return res;
1318 }
1319
1320 enum spy_direction {
1321         SPY_READ,
1322         SPY_WRITE,
1323 };
1324
1325 #define SPY_QUEUE_SAMPLE_LIMIT 4000                     /* half of one second */
1326
1327 static void queue_frame_to_spies(struct ast_channel *chan, struct ast_frame *f, enum spy_direction dir)
1328 {
1329         struct ast_frame *translated_frame = NULL;
1330         struct ast_channel_spy *spy;
1331         struct channel_spy_trans *trans;
1332
1333         trans = (dir == SPY_READ) ? &chan->spies->read_translator : &chan->spies->write_translator;
1334
1335         AST_LIST_TRAVERSE(&chan->spies->list, spy, list) {
1336                 struct ast_channel_spy_queue *queue;
1337                 struct ast_frame *duped_fr;
1338
1339                 ast_mutex_lock(&spy->lock);
1340
1341                 queue = (dir == SPY_READ) ? &spy->read_queue : &spy->write_queue;
1342
1343                 if ((queue->format == AST_FORMAT_SLINEAR) && (f->subclass != AST_FORMAT_SLINEAR)) {
1344                         if (!translated_frame) {
1345                                 if (trans->path && (trans->last_format != f->subclass)) {
1346                                         ast_translator_free_path(trans->path);
1347                                         trans->path = NULL;
1348                                 }
1349                                 if (!trans->path) {
1350                                         ast_log(LOG_DEBUG, "Building translator from %s to SLINEAR for spies on channel %s\n",
1351                                                 ast_getformatname(f->subclass), chan->name);
1352                                         if ((trans->path = ast_translator_build_path(AST_FORMAT_SLINEAR, f->subclass)) == NULL) {
1353                                                 ast_log(LOG_WARNING, "Cannot build a path from %s to %s\n",
1354                                                         ast_getformatname(f->subclass), ast_getformatname(AST_FORMAT_SLINEAR));
1355                                                 ast_mutex_unlock(&spy->lock);
1356                                                 continue;
1357                                         } else {
1358                                                 trans->last_format = f->subclass;
1359                                         }
1360                                 }
1361                                 if (!(translated_frame = ast_translate(trans->path, f, 0))) {
1362                                         ast_log(LOG_ERROR, "Translation to %s failed, dropping frame for spies\n",
1363                                                 ast_getformatname(AST_FORMAT_SLINEAR));
1364                                         ast_mutex_unlock(&spy->lock);
1365                                         break;
1366                                 }
1367                         }
1368                         duped_fr = ast_frdup(translated_frame);
1369                 } else {
1370                         if (f->subclass != queue->format) {
1371                                 ast_log(LOG_WARNING, "Spy '%s' on channel '%s' wants format '%s', but frame is '%s', dropping\n",
1372                                         spy->type, chan->name,
1373                                         ast_getformatname(queue->format), ast_getformatname(f->subclass));
1374                                 ast_mutex_unlock(&spy->lock);
1375                                 continue;
1376                         }
1377                         duped_fr = ast_frdup(f);
1378                 }
1379
1380                 AST_LIST_INSERT_TAIL(&queue->list, duped_fr, frame_list);
1381
1382                 queue->samples += f->samples;
1383
1384                 if (queue->samples > SPY_QUEUE_SAMPLE_LIMIT) {
1385                         if (ast_test_flag(spy, CHANSPY_TRIGGER_MODE) != CHANSPY_TRIGGER_NONE) {
1386                                 switch (ast_test_flag(spy, CHANSPY_TRIGGER_MODE)) {
1387                                 case CHANSPY_TRIGGER_READ:
1388                                         if (dir == SPY_WRITE) {
1389                                                 ast_set_flag(spy, CHANSPY_TRIGGER_WRITE);
1390                                                 ast_clear_flag(spy, CHANSPY_TRIGGER_READ);
1391                                                 if (option_debug)
1392                                                         ast_log(LOG_DEBUG, "Switching spy '%s' on '%s' to write-trigger mode\n",
1393                                                                 spy->type, chan->name);
1394                                         }
1395                                         break;
1396                                 case CHANSPY_TRIGGER_WRITE:
1397                                         if (dir == SPY_READ) {
1398                                                 ast_set_flag(spy, CHANSPY_TRIGGER_READ);
1399                                                 ast_clear_flag(spy, CHANSPY_TRIGGER_WRITE);
1400                                                 if (option_debug)
1401                                                         ast_log(LOG_DEBUG, "Switching spy '%s' on '%s' to read-trigger mode\n",
1402                                                                 spy->type, chan->name);
1403                                         }
1404                                         break;
1405                                 }
1406                                 if (option_debug)
1407                                         ast_log(LOG_DEBUG, "Triggering queue flush for spy '%s' on '%s'\n",
1408                                                 spy->type, chan->name);
1409                                 ast_set_flag(spy, CHANSPY_TRIGGER_FLUSH);
1410                                 ast_cond_signal(&spy->trigger);
1411                         } else {
1412                                 if (option_debug)
1413                                         ast_log(LOG_DEBUG, "Spy '%s' on channel '%s' %s queue too long, dropping frames\n",
1414                                                 spy->type, chan->name, (dir == SPY_READ) ? "read" : "write");
1415                                 while (queue->samples > SPY_QUEUE_SAMPLE_LIMIT) {
1416                                         struct ast_frame *drop = AST_LIST_REMOVE_HEAD(&queue->list, frame_list);
1417                                         queue->samples -= drop->samples;
1418                                         ast_frfree(drop);
1419                                 }
1420                         }
1421                 } else {
1422                         switch (ast_test_flag(spy, CHANSPY_TRIGGER_MODE)) {
1423                         case CHANSPY_TRIGGER_READ:
1424                                 if (dir == SPY_READ)
1425                                         ast_cond_signal(&spy->trigger);
1426                                 break;
1427                         case CHANSPY_TRIGGER_WRITE:
1428                                 if (dir == SPY_WRITE)
1429                                         ast_cond_signal(&spy->trigger);
1430                                 break;
1431                         }
1432                 }
1433
1434                 ast_mutex_unlock(&spy->lock);
1435         }
1436
1437         if (translated_frame)
1438                 ast_frfree(translated_frame);
1439 }
1440
1441 static void free_translation(struct ast_channel *clone)
1442 {
1443         if (clone->writetrans)
1444                 ast_translator_free_path(clone->writetrans);
1445         if (clone->readtrans)
1446                 ast_translator_free_path(clone->readtrans);
1447         clone->writetrans = NULL;
1448         clone->readtrans = NULL;
1449         clone->rawwriteformat = clone->nativeformats;
1450         clone->rawreadformat = clone->nativeformats;
1451 }
1452
1453 /*! \brief Hangup a channel */
1454 int ast_hangup(struct ast_channel *chan)
1455 {
1456         int res = 0;
1457
1458         /* Don't actually hang up a channel that will masquerade as someone else, or
1459            if someone is going to masquerade as us */
1460         ast_channel_lock(chan);
1461
1462         detach_spies(chan);             /* get rid of spies */
1463
1464         if (chan->masq) {
1465                 if (ast_do_masquerade(chan))
1466                         ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1467         }
1468
1469         if (chan->masq) {
1470                 ast_log(LOG_WARNING, "%s getting hung up, but someone is trying to masq into us?!?\n", chan->name);
1471                 ast_channel_unlock(chan);
1472                 return 0;
1473         }
1474         /* If this channel is one which will be masqueraded into something,
1475            mark it as a zombie already, so we know to free it later */
1476         if (chan->masqr) {
1477                 ast_set_flag(chan, AST_FLAG_ZOMBIE);
1478                 ast_channel_unlock(chan);
1479                 return 0;
1480         }
1481         free_translation(chan);
1482         /* Close audio stream */
1483         if (chan->stream) {
1484                 ast_closestream(chan->stream);
1485                 chan->stream = NULL;
1486         }
1487         /* Close video stream */
1488         if (chan->vstream) {
1489                 ast_closestream(chan->vstream);
1490                 chan->vstream = NULL;
1491         }
1492         if (chan->sched) {
1493                 sched_context_destroy(chan->sched);
1494                 chan->sched = NULL;
1495         }
1496         
1497         if (chan->generatordata)        /* Clear any tone stuff remaining */
1498                 chan->generator->release(chan, chan->generatordata);
1499         chan->generatordata = NULL;
1500         chan->generator = NULL;
1501         if (chan->cdr) {                /* End the CDR if it hasn't already */
1502                 ast_cdr_end(chan->cdr);
1503                 ast_cdr_detach(chan->cdr);      /* Post and Free the CDR */
1504                 chan->cdr = NULL;
1505         }
1506         if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
1507                 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
1508                                         "is blocked by thread %ld in procedure %s!  Expect a failure\n",
1509                                         (long)pthread_self(), chan->name, (long)chan->blocker, chan->blockproc);
1510                 CRASH;
1511         }
1512         if (!ast_test_flag(chan, AST_FLAG_ZOMBIE)) {
1513                 if (option_debug)
1514                         ast_log(LOG_DEBUG, "Hanging up channel '%s'\n", chan->name);
1515                 if (chan->tech->hangup)
1516                         res = chan->tech->hangup(chan);
1517         } else {
1518                 if (option_debug)
1519                         ast_log(LOG_DEBUG, "Hanging up zombie '%s'\n", chan->name);
1520         }
1521                         
1522         ast_channel_unlock(chan);
1523         manager_event(EVENT_FLAG_CALL, "Hangup",
1524                         "Channel: %s\r\n"
1525                         "Uniqueid: %s\r\n"
1526                         "Cause: %d\r\n"
1527                         "Cause-txt: %s\r\n",
1528                         chan->name,
1529                         chan->uniqueid,
1530                         chan->hangupcause,
1531                         ast_cause2str(chan->hangupcause)
1532                         );
1533         ast_channel_free(chan);
1534         return res;
1535 }
1536
1537 int ast_answer(struct ast_channel *chan)
1538 {
1539         int res = 0;
1540         ast_channel_lock(chan);
1541         /* You can't answer an outbound call */
1542         if (ast_test_flag(chan, AST_FLAG_OUTGOING)) {
1543                 ast_channel_unlock(chan);
1544                 return 0;
1545         }
1546         /* Stop if we're a zombie or need a soft hangup */
1547         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
1548                 ast_channel_unlock(chan);
1549                 return -1;
1550         }
1551         switch(chan->_state) {
1552         case AST_STATE_RINGING:
1553         case AST_STATE_RING:
1554                 if (chan->tech->answer)
1555                         res = chan->tech->answer(chan);
1556                 ast_setstate(chan, AST_STATE_UP);
1557                 ast_cdr_answer(chan->cdr);
1558                 break;
1559         case AST_STATE_UP:
1560                 ast_cdr_answer(chan->cdr);
1561                 break;
1562         default:
1563                 break;
1564         }
1565         ast_channel_unlock(chan);
1566         return res;
1567 }
1568
1569 void ast_deactivate_generator(struct ast_channel *chan)
1570 {
1571         ast_channel_lock(chan);
1572         if (chan->generatordata) {
1573                 if (chan->generator && chan->generator->release)
1574                         chan->generator->release(chan, chan->generatordata);
1575                 chan->generatordata = NULL;
1576                 chan->generator = NULL;
1577                 chan->fds[AST_GENERATOR_FD] = -1;
1578                 ast_clear_flag(chan, AST_FLAG_WRITE_INT);
1579                 ast_settimeout(chan, 0, NULL, NULL);
1580         }
1581         ast_channel_unlock(chan);
1582 }
1583
1584 static int generator_force(void *data)
1585 {
1586         /* Called if generator doesn't have data */
1587         void *tmp;
1588         int res;
1589         int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples);
1590         struct ast_channel *chan = data;
1591         tmp = chan->generatordata;
1592         chan->generatordata = NULL;
1593         generate = chan->generator->generate;
1594         res = generate(chan, tmp, 0, 160);
1595         chan->generatordata = tmp;
1596         if (res) {
1597                 ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
1598                 ast_deactivate_generator(chan);
1599         }
1600         return 0;
1601 }
1602
1603 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
1604 {
1605         int res = 0;
1606
1607         ast_channel_lock(chan);
1608
1609         if (chan->generatordata) {
1610                 if (chan->generator && chan->generator->release)
1611                         chan->generator->release(chan, chan->generatordata);
1612                 chan->generatordata = NULL;
1613         }
1614
1615         ast_prod(chan);
1616         if (gen->alloc && !(chan->generatordata = gen->alloc(chan, params))) {
1617                 res = -1;
1618         }
1619         
1620         if (!res) {
1621                 ast_settimeout(chan, 160, generator_force, chan);
1622                 chan->generator = gen;
1623         }
1624
1625         ast_channel_unlock(chan);
1626
1627         return res;
1628 }
1629
1630 /*! \brief Wait for x amount of time on a file descriptor to have input.  */
1631 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
1632 {
1633         int winner = -1;
1634         ast_waitfor_nandfds(NULL, 0, fds, n, exception, &winner, ms);
1635         return winner;
1636 }
1637
1638 /*! \brief Wait for x amount of time on a file descriptor to have input.  */
1639 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
1640         int *exception, int *outfd, int *ms)
1641 {
1642         struct timeval start = { 0 , 0 };
1643         struct pollfd *pfds;
1644         int res;
1645         long rms;
1646         int x, y, max;
1647         int sz;
1648         time_t now = 0;
1649         long whentohangup = 0, diff;
1650         struct ast_channel *winner = NULL;
1651         struct fdmap {
1652                 int chan;
1653                 int fdno;
1654         } *fdmap;
1655
1656         sz = n * AST_MAX_FDS + nfds;
1657         pfds = alloca(sizeof(*pfds) * sz);
1658         fdmap = alloca(sizeof(*fdmap) * sz);
1659
1660         if (outfd)
1661                 *outfd = -99999;
1662         if (exception)
1663                 *exception = 0;
1664         
1665         /* Perform any pending masquerades */
1666         for (x=0; x < n; x++) {
1667                 ast_channel_lock(c[x]);
1668                 if (c[x]->masq) {
1669                         if (ast_do_masquerade(c[x])) {
1670                                 ast_log(LOG_WARNING, "Masquerade failed\n");
1671                                 *ms = -1;
1672                                 ast_channel_unlock(c[x]);
1673                                 return NULL;
1674                         }
1675                 }
1676                 if (c[x]->whentohangup) {
1677                         if (!whentohangup)
1678                                 time(&now);
1679                         diff = c[x]->whentohangup - now;
1680                         if (diff < 1) {
1681                                 /* Should already be hungup */
1682                                 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1683                                 ast_channel_unlock(c[x]);
1684                                 return c[x];
1685                         }
1686                         if (!whentohangup || (diff < whentohangup))
1687                                 whentohangup = diff;
1688                 }
1689                 ast_channel_unlock(c[x]);
1690         }
1691         /* Wait full interval */
1692         rms = *ms;
1693         if (whentohangup) {
1694                 rms = (whentohangup - now) * 1000;      /* timeout in milliseconds */
1695                 if (*ms >= 0 && *ms < rms)              /* original *ms still smaller */
1696                         rms =  *ms;
1697         }
1698         /*
1699          * Build the pollfd array, putting the channels' fds first,
1700          * followed by individual fds. Order is important because
1701          * individual fd's must have priority over channel fds.
1702          */
1703         max = 0;
1704         for (x=0; x<n; x++) {
1705                 for (y=0; y<AST_MAX_FDS; y++) {
1706                         fdmap[max].fdno = y;  /* fd y is linked to this pfds */
1707                         fdmap[max].chan = x;  /* channel x is linked to this pfds */
1708                         max += ast_add_fd(&pfds[max], c[x]->fds[y]);
1709                 }
1710                 CHECK_BLOCKING(c[x]);
1711         }
1712         /* Add the individual fds */
1713         for (x=0; x<nfds; x++) {
1714                 fdmap[max].chan = -1;
1715                 max += ast_add_fd(&pfds[max], fds[x]);
1716         }
1717
1718         if (*ms > 0)
1719                 start = ast_tvnow();
1720         
1721         if (sizeof(int) == 4) { /* XXX fix timeout > 600000 on linux x86-32 */
1722                 do {
1723                         int kbrms = rms;
1724                         if (kbrms > 600000)
1725                                 kbrms = 600000;
1726                         res = poll(pfds, max, kbrms);
1727                         if (!res)
1728                                 rms -= kbrms;
1729                 } while (!res && (rms > 0));
1730         } else {
1731                 res = poll(pfds, max, rms);
1732         }
1733         for (x=0; x<n; x++)
1734                 ast_clear_flag(c[x], AST_FLAG_BLOCKING);
1735         if (res < 0) { /* Simulate a timeout if we were interrupted */
1736                 if (errno != EINTR)
1737                         *ms = -1;
1738                 return NULL;
1739         }
1740         if (whentohangup) {   /* if we have a timeout, check who expired */
1741                 time(&now);
1742                 for (x=0; x<n; x++) {
1743                         if (c[x]->whentohangup && now >= c[x]->whentohangup) {
1744                                 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1745                                 if (winner == NULL)
1746                                         winner = c[x];
1747                         }
1748                 }
1749         }
1750         if (res == 0) { /* no fd ready, reset timeout and done */
1751                 *ms = 0;        /* XXX use 0 since we may not have an exact timeout. */
1752                 return winner;
1753         }
1754         /*
1755          * Then check if any channel or fd has a pending event.
1756          * Remember to check channels first and fds last, as they
1757          * must have priority on setting 'winner'
1758          */
1759         for (x = 0; x < max; x++) {
1760                 res = pfds[x].revents;
1761                 if (res == 0)
1762                         continue;
1763                 if (fdmap[x].chan >= 0) {       /* this is a channel */
1764                         winner = c[fdmap[x].chan];      /* override previous winners */
1765                         if (res & POLLPRI)
1766                                 ast_set_flag(winner, AST_FLAG_EXCEPTION);
1767                         else
1768                                 ast_clear_flag(winner, AST_FLAG_EXCEPTION);
1769                         winner->fdno = fdmap[x].fdno;
1770                 } else {                        /* this is an fd */
1771                         if (outfd)
1772                                 *outfd = pfds[x].fd;
1773                         if (exception)
1774                                 *exception = (res & POLLPRI) ? -1 : 0;
1775                         winner = NULL;
1776                 }
1777         }
1778         if (*ms > 0) {
1779                 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
1780                 if (*ms < 0)
1781                         *ms = 0;
1782         }
1783         return winner;
1784 }
1785
1786 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
1787 {
1788         return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
1789 }
1790
1791 int ast_waitfor(struct ast_channel *c, int ms)
1792 {
1793         int oldms = ms; /* -1 if no timeout */
1794
1795         ast_waitfor_nandfds(&c, 1, NULL, 0, NULL, NULL, &ms);
1796         if ((ms < 0) && (oldms < 0))
1797                 ms = 0;
1798         return ms;
1799 }
1800
1801 /* XXX never to be called with ms = -1 */
1802 int ast_waitfordigit(struct ast_channel *c, int ms)
1803 {
1804         return ast_waitfordigit_full(c, ms, -1, -1);
1805 }
1806
1807 int ast_settimeout(struct ast_channel *c, int samples, int (*func)(void *data), void *data)
1808 {
1809         int res = -1;
1810 #ifdef HAVE_ZAPTEL
1811         if (c->timingfd > -1) {
1812                 if (!func) {
1813                         samples = 0;
1814                         data = 0;
1815                 }
1816                 ast_log(LOG_DEBUG, "Scheduling timer at %d sample intervals\n", samples);
1817                 res = ioctl(c->timingfd, ZT_TIMERCONFIG, &samples);
1818                 c->timingfunc = func;
1819                 c->timingdata = data;
1820         }
1821 #endif  
1822         return res;
1823 }
1824
1825 int ast_waitfordigit_full(struct ast_channel *c, int ms, int audiofd, int cmdfd)
1826 {
1827
1828         /* Stop if we're a zombie or need a soft hangup */
1829         if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
1830                 return -1;
1831         /* Wait for a digit, no more than ms milliseconds total. */
1832         while (ms) {
1833                 struct ast_channel *rchan;
1834                 int outfd;
1835
1836                 errno = 0;
1837                 rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
1838                 if (!rchan && outfd < 0 && ms) {
1839                         if (errno == 0 || errno == EINTR)
1840                                 continue;
1841                         ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
1842                         return -1;
1843                 } else if (outfd > -1) {
1844                         /* The FD we were watching has something waiting */
1845                         return 1;
1846                 } else if (rchan) {
1847                         int res;
1848                         struct ast_frame *f = ast_read(c);
1849                         if (!f)
1850                                 return -1;
1851
1852                         switch(f->frametype) {
1853                         case AST_FRAME_DTMF:
1854                                 res = f->subclass;
1855                                 ast_frfree(f);
1856                                 return res;
1857                         case AST_FRAME_CONTROL:
1858                                 switch(f->subclass) {
1859                                 case AST_CONTROL_HANGUP:
1860                                         ast_frfree(f);
1861                                         return -1;
1862                                 case AST_CONTROL_RINGING:
1863                                 case AST_CONTROL_ANSWER:
1864                                         /* Unimportant */
1865                                         break;
1866                                 default:
1867                                         ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", f->subclass);
1868                                         break;
1869                                 }
1870                                 break;
1871                         case AST_FRAME_VOICE:
1872                                 /* Write audio if appropriate */
1873                                 if (audiofd > -1)
1874                                         write(audiofd, f->data, f->datalen);
1875                         default:
1876                                 /* Ignore */
1877                                 break;
1878                         }
1879                         ast_frfree(f);
1880                 }
1881         }
1882         return 0; /* Time is up */
1883 }
1884
1885 static struct ast_frame *__ast_read(struct ast_channel *chan, int dropaudio)
1886 {
1887         struct ast_frame *f = NULL;     /* the return value */
1888         int blah;
1889         int prestate;
1890
1891         /* this function is very long so make sure there is only one return
1892          * point at the end (there is only one exception to this).
1893          */
1894         ast_channel_lock(chan);
1895         if (chan->masq) {
1896                 if (ast_do_masquerade(chan))
1897                         ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1898                 else
1899                         f =  &ast_null_frame;
1900                 goto done;
1901         }
1902
1903         /* Stop if we're a zombie or need a soft hangup */
1904         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
1905                 if (chan->generator)
1906                         ast_deactivate_generator(chan);
1907                 goto done;
1908         }
1909         prestate = chan->_state;
1910
1911         if (!ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_EMULATE_DTMF | AST_FLAG_IN_DTMF) && 
1912             !ast_strlen_zero(chan->dtmfq)) {
1913                 /* We have DTMF that has been deferred.  Return it now */
1914                 chan->dtmff.frametype = AST_FRAME_DTMF_BEGIN;
1915                 chan->dtmff.subclass = chan->dtmfq[0];
1916                 /* Drop first digit from the buffer */
1917                 memmove(chan->dtmfq, chan->dtmfq + 1, sizeof(chan->dtmfq) - 1);
1918                 f = &chan->dtmff;
1919                 ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
1920                 chan->emulate_dtmf_digit = f->subclass;
1921                 chan->emulate_dtmf_samples = AST_DEFAULT_EMULATE_DTMF_SAMPLES;
1922                 goto done;
1923         }
1924         
1925         /* Read and ignore anything on the alertpipe, but read only
1926            one sizeof(blah) per frame that we send from it */
1927         if (chan->alertpipe[0] > -1)
1928                 read(chan->alertpipe[0], &blah, sizeof(blah));
1929
1930 #ifdef HAVE_ZAPTEL
1931         if (chan->timingfd > -1 && chan->fdno == AST_TIMING_FD && ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
1932                 int res;
1933
1934                 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
1935                 blah = -1;
1936                 /* IF we can't get event, assume it's an expired as-per the old interface */
1937                 res = ioctl(chan->timingfd, ZT_GETEVENT, &blah);
1938                 if (res)
1939                         blah = ZT_EVENT_TIMER_EXPIRED;
1940
1941                 if (blah == ZT_EVENT_TIMER_PING) {
1942                         if (AST_LIST_EMPTY(&chan->readq) || !AST_LIST_NEXT(AST_LIST_FIRST(&chan->readq), frame_list)) {
1943                                 /* Acknowledge PONG unless we need it again */
1944                                 if (ioctl(chan->timingfd, ZT_TIMERPONG, &blah)) {
1945                                         ast_log(LOG_WARNING, "Failed to pong timer on '%s': %s\n", chan->name, strerror(errno));
1946                                 }
1947                         }
1948                 } else if (blah == ZT_EVENT_TIMER_EXPIRED) {
1949                         ioctl(chan->timingfd, ZT_TIMERACK, &blah);
1950                         if (chan->timingfunc) {
1951                                 /* save a copy of func/data before unlocking the channel */
1952                                 int (*func)(void *) = chan->timingfunc;
1953                                 void *data = chan->timingdata;
1954                                 ast_channel_unlock(chan);
1955                                 func(data);
1956                         } else {
1957                                 blah = 0;
1958                                 ioctl(chan->timingfd, ZT_TIMERCONFIG, &blah);
1959                                 chan->timingdata = NULL;
1960                                 ast_channel_unlock(chan);
1961                         }
1962                         /* cannot 'goto done' because the channel is already unlocked */
1963                         return &ast_null_frame;
1964                 } else
1965                         ast_log(LOG_NOTICE, "No/unknown event '%d' on timer for '%s'?\n", blah, chan->name);
1966         } else
1967 #endif
1968         if (chan->fds[AST_GENERATOR_FD] > -1 && chan->fdno == AST_GENERATOR_FD) {
1969                 /* if the AST_GENERATOR_FD is set, call the generator with args
1970                  * set to -1 so it can do whatever it needs to.
1971                  */
1972                 void *tmp = chan->generatordata;
1973                 chan->generatordata = NULL;     /* reset to let ast_write get through */
1974                 chan->generator->generate(chan, tmp, -1, -1);
1975                 chan->generatordata = tmp;
1976                 f = &ast_null_frame;
1977                 goto done;
1978         }
1979
1980         /* Check for pending read queue */
1981         if (!AST_LIST_EMPTY(&chan->readq)) {
1982                 f = AST_LIST_REMOVE_HEAD(&chan->readq, frame_list);
1983                 /* Interpret hangup and return NULL */
1984                 /* XXX why not the same for frames from the channel ? */
1985                 if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP) {
1986                         ast_frfree(f);
1987                         f = NULL;
1988                 }
1989         } else {
1990                 chan->blocker = pthread_self();
1991                 if (ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
1992                         if (chan->tech->exception)
1993                                 f = chan->tech->exception(chan);
1994                         else {
1995                                 ast_log(LOG_WARNING, "Exception flag set on '%s', but no exception handler\n", chan->name);
1996                                 f = &ast_null_frame;
1997                         }
1998                         /* Clear the exception flag */
1999                         ast_clear_flag(chan, AST_FLAG_EXCEPTION);
2000                 } else if (chan->tech->read)
2001                         f = chan->tech->read(chan);
2002                 else
2003                         ast_log(LOG_WARNING, "No read routine on channel %s\n", chan->name);
2004         }
2005
2006         if (f) {
2007                 /* if the channel driver returned more than one frame, stuff the excess
2008                    into the readq for the next ast_read call (note that we can safely assume
2009                    that the readq is empty, because otherwise we would not have called into
2010                    the channel driver and f would be only a single frame)
2011                 */
2012                 if (AST_LIST_NEXT(f, frame_list)) {
2013                         AST_LIST_HEAD_SET_NOLOCK(&chan->readq, AST_LIST_NEXT(f, frame_list));
2014                         AST_LIST_NEXT(f, frame_list) = NULL;
2015                 }
2016
2017                 switch (f->frametype) {
2018                 case AST_FRAME_CONTROL:
2019                         if (f->subclass == AST_CONTROL_ANSWER) {
2020                                 if (!ast_test_flag(chan, AST_FLAG_OUTGOING)) {
2021                                         ast_log(LOG_DEBUG, "Ignoring answer on an inbound call!\n");
2022                                         ast_frfree(f);
2023                                         f = &ast_null_frame;
2024                                 } else if (prestate == AST_STATE_UP) {
2025                                         ast_log(LOG_DEBUG, "Dropping duplicate answer!\n");
2026                                         ast_frfree(f);
2027                                         f = &ast_null_frame;
2028                                 } else {
2029                                         /* Answer the CDR */
2030                                         ast_setstate(chan, AST_STATE_UP);
2031                                         ast_cdr_answer(chan->cdr);
2032                                 }
2033                         }
2034                         break;
2035                 case AST_FRAME_DTMF_END:
2036                         ast_log(LOG_DTMF, "DTMF end '%c' received on %s\n", f->subclass, chan->name);
2037                         if (ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_EMULATE_DTMF)) {
2038                                 if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2)
2039                                         chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
2040                                 else
2041                                         ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
2042                                 ast_frfree(f);
2043                                 f = &ast_null_frame;
2044                         } else if (!ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
2045                                 f->frametype = AST_FRAME_DTMF_BEGIN;
2046                                 ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
2047                                 chan->emulate_dtmf_digit = f->subclass;
2048                                 if (f->samples)
2049                                         chan->emulate_dtmf_samples = f->samples;
2050                                 else
2051                                         chan->emulate_dtmf_samples = AST_DEFAULT_EMULATE_DTMF_SAMPLES;
2052                         } else 
2053                                 ast_clear_flag(chan, AST_FLAG_IN_DTMF);
2054                         break;
2055                 case AST_FRAME_DTMF_BEGIN:
2056                         ast_log(LOG_DTMF, "DTMF begin '%c' received on %s\n", f->subclass, chan->name);
2057                         if (ast_test_flag(chan, AST_FLAG_DEFER_DTMF)) {
2058                                 ast_frfree(f);
2059                                 f = &ast_null_frame;
2060                         } else 
2061                                 ast_set_flag(chan, AST_FLAG_IN_DTMF);
2062                         break;
2063                 case AST_FRAME_VOICE:
2064                         /* The EMULATE_DTMF flag must be cleared here as opposed to when the samples
2065                          * first get to zero, because we want to make sure we pass at least one
2066                          * voice frame through before starting the next digit, to ensure a gap
2067                          * between DTMF digits. */
2068                         if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !chan->emulate_dtmf_samples) {
2069                                 ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
2070                                 chan->emulate_dtmf_digit = 0;
2071                         }
2072
2073                         if (dropaudio || ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
2074                                 ast_frfree(f);
2075                                 f = &ast_null_frame;
2076                         } else if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF)) {
2077                                 if (f->samples >= chan->emulate_dtmf_samples) {
2078                                         chan->emulate_dtmf_samples = 0;
2079                                         f->frametype = AST_FRAME_DTMF_END;
2080                                         f->subclass = chan->emulate_dtmf_digit;
2081                                 } else {
2082                                         chan->emulate_dtmf_samples -= f->samples;
2083                                         ast_frfree(f);
2084                                         f = &ast_null_frame;
2085                                 }
2086                         } else if (!(f->subclass & chan->nativeformats)) {
2087                                 /* This frame can't be from the current native formats -- drop it on the
2088                                    floor */
2089                                 ast_log(LOG_NOTICE, "Dropping incompatible voice frame on %s of format %s since our native format has changed to %s\n",
2090                                         chan->name, ast_getformatname(f->subclass), ast_getformatname(chan->nativeformats));
2091                                 ast_frfree(f);
2092                                 f = &ast_null_frame;
2093                         } else {
2094                                 if (chan->spies)
2095                                         queue_frame_to_spies(chan, f, SPY_READ);
2096                                 
2097                                 if (chan->monitor && chan->monitor->read_stream ) {
2098                                         /* XXX what does this do ? */
2099 #ifndef MONITOR_CONSTANT_DELAY
2100                                         int jump = chan->outsmpl - chan->insmpl - 4 * f->samples;
2101                                         if (jump >= 0) {
2102                                                 if (ast_seekstream(chan->monitor->read_stream, jump + f->samples, SEEK_FORCECUR) == -1)
2103                                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
2104                                                 chan->insmpl += jump + 4 * f->samples;
2105                                         } else
2106                                                 chan->insmpl+= f->samples;
2107 #else
2108                                         int jump = chan->outsmpl - chan->insmpl;
2109                                         if (jump - MONITOR_DELAY >= 0) {
2110                                                 if (ast_seekstream(chan->monitor->read_stream, jump - f->samples, SEEK_FORCECUR) == -1)
2111                                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
2112                                                 chan->insmpl += jump;
2113                                         } else
2114                                                 chan->insmpl += f->samples;
2115 #endif
2116                                         if (chan->monitor->state == AST_MONITOR_RUNNING) {
2117                                                 if (ast_writestream(chan->monitor->read_stream, f) < 0)
2118                                                         ast_log(LOG_WARNING, "Failed to write data to channel monitor read stream\n");
2119                                         }
2120                                 }
2121
2122                                 if (chan->readtrans && (f = ast_translate(chan->readtrans, f, 1)) == NULL)
2123                                         f = &ast_null_frame;
2124
2125                                 /* Run generator sitting on the line if timing device not available
2126                                 * and synchronous generation of outgoing frames is necessary       */
2127                                 if (chan->generatordata &&  !ast_internal_timing_enabled(chan)) {
2128                                         void *tmp = chan->generatordata;
2129                                         int res;
2130
2131                                         if (chan->timingfunc) {
2132                                                 if (option_debug > 1)
2133                                                         ast_log(LOG_DEBUG, "Generator got voice, switching to phase locked mode\n");
2134                                                 ast_settimeout(chan, 0, NULL, NULL);
2135                                         }
2136
2137                                         chan->generatordata = NULL;     /* reset, to let writes go through */
2138                                         res = chan->generator->generate(chan, tmp, f->datalen, f->samples);
2139                                         chan->generatordata = tmp;
2140                                         if (res) {
2141                                                 if (option_debug > 1)
2142                                                         ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
2143                                                 ast_deactivate_generator(chan);
2144                                         }
2145
2146                                 } else if (f->frametype == AST_FRAME_CNG) {
2147                                         if (chan->generator && !chan->timingfunc && (chan->timingfd > -1)) {
2148                                                 if (option_debug > 1)
2149                                                         ast_log(LOG_DEBUG, "Generator got CNG, switching to timed mode\n");
2150                                                 ast_settimeout(chan, 160, generator_force, chan);
2151                                         }
2152                                 }
2153                         }
2154                 default:
2155                         /* Just pass it on! */
2156                         break;
2157                 }
2158         } else {
2159                 /* Make sure we always return NULL in the future */
2160                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
2161                 if (chan->generator)
2162                         ast_deactivate_generator(chan);
2163                 /* End the CDR if appropriate */
2164                 if (chan->cdr)
2165                         ast_cdr_end(chan->cdr);
2166         }
2167
2168         /* High bit prints debugging */
2169         if (chan->fin & DEBUGCHAN_FLAG)
2170                 ast_frame_dump(chan->name, f, "<<");
2171         chan->fin = FRAMECOUNT_INC(chan->fin);
2172
2173 done:
2174         ast_channel_unlock(chan);
2175         return f;
2176 }
2177
2178 int ast_internal_timing_enabled(struct ast_channel *chan)
2179 {
2180         int ret = ast_opt_internal_timing && chan->timingfd > -1;
2181         if (option_debug > 4)
2182                 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);
2183         return ret;
2184 }
2185
2186 struct ast_frame *ast_read(struct ast_channel *chan)
2187 {
2188         return __ast_read(chan, 0);
2189 }
2190
2191 struct ast_frame *ast_read_noaudio(struct ast_channel *chan)
2192 {
2193         return __ast_read(chan, 1);
2194 }
2195
2196 int ast_indicate(struct ast_channel *chan, int condition)
2197 {
2198         return ast_indicate_data(chan, condition, NULL, 0);
2199 }
2200
2201 int ast_indicate_data(struct ast_channel *chan, int condition, const void *data, size_t datalen)
2202 {
2203         int res = -1;
2204
2205         ast_channel_lock(chan);
2206         /* Stop if we're a zombie or need a soft hangup */
2207         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2208                 ast_channel_unlock(chan);
2209                 return -1;
2210         }
2211         if (chan->tech->indicate)
2212                 res = chan->tech->indicate(chan, condition, data, datalen);
2213         ast_channel_unlock(chan);
2214         if (!chan->tech->indicate || res) {
2215                 /*
2216                  * Device does not support (that) indication, lets fake
2217                  * it by doing our own tone generation. (PM2002)
2218                  */
2219                 if (condition < 0)
2220                         ast_playtones_stop(chan);
2221                 else {
2222                         const struct tone_zone_sound *ts = NULL;
2223                         switch (condition) {
2224                         case AST_CONTROL_RINGING:
2225                                 ts = ast_get_indication_tone(chan->zone, "ring");
2226                                 break;
2227                         case AST_CONTROL_BUSY:
2228                                 ts = ast_get_indication_tone(chan->zone, "busy");
2229                                 break;
2230                         case AST_CONTROL_CONGESTION:
2231                                 ts = ast_get_indication_tone(chan->zone, "congestion");
2232                                 break;
2233                         }
2234                         if (ts && ts->data[0]) {
2235                                 ast_log(LOG_DEBUG, "Driver for channel '%s' does not support indication %d, emulating it\n", chan->name, condition);
2236                                 ast_playtones_start(chan,0,ts->data, 1);
2237                                 res = 0;
2238                         } else if (condition == AST_CONTROL_PROGRESS) {
2239                                 /* ast_playtones_stop(chan); */
2240                         } else if (condition == AST_CONTROL_PROCEEDING) {
2241                                 /* Do nothing, really */
2242                         } else if (condition == AST_CONTROL_HOLD) {
2243                                 /* Do nothing.... */
2244                         } else if (condition == AST_CONTROL_UNHOLD) {
2245                                 /* Do nothing.... */
2246                         } else if (condition == AST_CONTROL_VIDUPDATE) {
2247                                 /* Do nothing.... */
2248                         } else {
2249                                 /* not handled */
2250                                 ast_log(LOG_WARNING, "Unable to handle indication %d for '%s'\n", condition, chan->name);
2251                                 res = -1;
2252                         }
2253                 }
2254         }
2255         return res;
2256 }
2257
2258 int ast_recvchar(struct ast_channel *chan, int timeout)
2259 {
2260         int c;
2261         char *buf = ast_recvtext(chan, timeout);
2262         if (buf == NULL)
2263                 return -1;      /* error or timeout */
2264         c = *(unsigned char *)buf;
2265         free(buf);
2266         return c;
2267 }
2268
2269 char *ast_recvtext(struct ast_channel *chan, int timeout)
2270 {
2271         int res, done = 0;
2272         char *buf = NULL;
2273         
2274         while (!done) {
2275                 struct ast_frame *f;
2276                 if (ast_check_hangup(chan))
2277                         break;
2278                 res = ast_waitfor(chan, timeout);
2279                 if (res <= 0) /* timeout or error */
2280                         break;
2281                 timeout = res;  /* update timeout */
2282                 f = ast_read(chan);
2283                 if (f == NULL)
2284                         break; /* no frame */
2285                 if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP)
2286                         done = 1;       /* force a break */
2287                 else if (f->frametype == AST_FRAME_TEXT) {              /* what we want */
2288                         buf = ast_strndup((char *) f->data, f->datalen);        /* dup and break */
2289                         done = 1;
2290                 }
2291                 ast_frfree(f);
2292         }
2293         return buf;
2294 }
2295
2296 int ast_sendtext(struct ast_channel *chan, const char *text)
2297 {
2298         int res = 0;
2299         /* Stop if we're a zombie or need a soft hangup */
2300         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
2301                 return -1;
2302         CHECK_BLOCKING(chan);
2303         if (chan->tech->send_text)
2304                 res = chan->tech->send_text(chan, text);
2305         ast_clear_flag(chan, AST_FLAG_BLOCKING);
2306         return res;
2307 }
2308
2309 int ast_senddigit_begin(struct ast_channel *chan, char digit)
2310 {
2311         int res = -1;
2312
2313         if (chan->tech->send_digit_begin)
2314                 res = chan->tech->send_digit_begin(chan, digit);
2315
2316         if (res) {
2317                 /*
2318                  * Device does not support DTMF tones, lets fake
2319                  * it by doing our own generation. (PM2002)
2320                  */
2321                 static const char* dtmf_tones[] = {
2322                         "!941+1336/100,!0/100", /* 0 */
2323                         "!697+1209/100,!0/100", /* 1 */
2324                         "!697+1336/100,!0/100", /* 2 */
2325                         "!697+1477/100,!0/100", /* 3 */
2326                         "!770+1209/100,!0/100", /* 4 */
2327                         "!770+1336/100,!0/100", /* 5 */
2328                         "!770+1477/100,!0/100", /* 6 */
2329                         "!852+1209/100,!0/100", /* 7 */
2330                         "!852+1336/100,!0/100", /* 8 */
2331                         "!852+1477/100,!0/100", /* 9 */
2332                         "!697+1633/100,!0/100", /* A */
2333                         "!770+1633/100,!0/100", /* B */
2334                         "!852+1633/100,!0/100", /* C */
2335                         "!941+1633/100,!0/100", /* D */
2336                         "!941+1209/100,!0/100", /* * */
2337                         "!941+1477/100,!0/100" };       /* # */
2338                 if (digit >= '0' && digit <='9')
2339                         ast_playtones_start(chan, 0, dtmf_tones[digit-'0'], 0);
2340                 else if (digit >= 'A' && digit <= 'D')
2341                         ast_playtones_start(chan, 0, dtmf_tones[digit-'A'+10], 0);
2342                 else if (digit == '*')
2343                         ast_playtones_start(chan, 0, dtmf_tones[14], 0);
2344                 else if (digit == '#')
2345                         ast_playtones_start(chan, 0, dtmf_tones[15], 0);
2346                 else {
2347                         /* not handled */
2348                         ast_log(LOG_DEBUG, "Unable to generate DTMF tone '%c' for '%s'\n", digit, chan->name);
2349                 }
2350         }
2351
2352         return 0;
2353 }
2354
2355 int ast_senddigit_end(struct ast_channel *chan, char digit)
2356 {
2357         int res = -1;
2358
2359         if (chan->tech->send_digit_end)
2360                 res = chan->tech->send_digit_end(chan, digit);
2361
2362         if (res && chan->generator)
2363                 ast_playtones_stop(chan);
2364         
2365         return 0;
2366 }
2367
2368 int ast_senddigit(struct ast_channel *chan, char digit)
2369 {
2370         ast_senddigit_begin(chan, digit);
2371         
2372         ast_safe_sleep(chan, 100); /* XXX 100ms ... probably should be configurable */
2373         
2374         return ast_senddigit_end(chan, digit);
2375 }
2376
2377 int ast_prod(struct ast_channel *chan)
2378 {
2379         struct ast_frame a = { AST_FRAME_VOICE };
2380         char nothing[128];
2381
2382         /* Send an empty audio frame to get things moving */
2383         if (chan->_state != AST_STATE_UP) {
2384                 ast_log(LOG_DEBUG, "Prodding channel '%s'\n", chan->name);
2385                 a.subclass = chan->rawwriteformat;
2386                 a.data = nothing + AST_FRIENDLY_OFFSET;
2387                 a.src = "ast_prod";
2388                 if (ast_write(chan, &a))
2389                         ast_log(LOG_WARNING, "Prodding channel '%s' failed\n", chan->name);
2390         }
2391         return 0;
2392 }
2393
2394 int ast_write_video(struct ast_channel *chan, struct ast_frame *fr)
2395 {
2396         int res;
2397         if (!chan->tech->write_video)
2398                 return 0;
2399         res = ast_write(chan, fr);
2400         if (!res)
2401                 res = 1;
2402         return res;
2403 }
2404
2405 int ast_write(struct ast_channel *chan, struct ast_frame *fr)
2406 {
2407         int res = -1;
2408         struct ast_frame *f = NULL;
2409
2410         /* Stop if we're a zombie or need a soft hangup */
2411         ast_channel_lock(chan);
2412         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
2413                 goto done;
2414
2415         /* Handle any pending masquerades */
2416         if (chan->masq && ast_do_masquerade(chan)) {
2417                 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
2418                 goto done;
2419         }
2420         if (chan->masqr) {
2421                 res = 0;        /* XXX explain, why 0 ? */
2422                 goto done;
2423         }
2424         if (chan->generatordata) {
2425                 if (ast_test_flag(chan, AST_FLAG_WRITE_INT))
2426                         ast_deactivate_generator(chan);
2427                 else {
2428                         res = 0;        /* XXX explain, why 0 ? */
2429                         goto done;
2430                 }
2431         }
2432         /* High bit prints debugging */
2433         if (chan->fout & DEBUGCHAN_FLAG)
2434                 ast_frame_dump(chan->name, fr, ">>");
2435         CHECK_BLOCKING(chan);
2436         switch(fr->frametype) {
2437         case AST_FRAME_CONTROL:
2438                 res = (chan->tech->indicate == NULL) ? 0 :
2439                         chan->tech->indicate(chan, fr->subclass, fr->data, fr->datalen);
2440                 break;
2441         case AST_FRAME_DTMF_BEGIN:
2442                 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2443                 ast_channel_unlock(chan);
2444                 res = ast_senddigit_begin(chan, fr->subclass);
2445                 ast_channel_lock(chan);
2446                 CHECK_BLOCKING(chan);
2447                 break;
2448         case AST_FRAME_DTMF_END:
2449                 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2450                 ast_channel_unlock(chan);
2451                 res = ast_senddigit_end(chan, fr->subclass);
2452                 ast_channel_lock(chan);
2453                 CHECK_BLOCKING(chan);
2454                 break;
2455         case AST_FRAME_TEXT:
2456                 res = (chan->tech->send_text == NULL) ? 0 :
2457                         chan->tech->send_text(chan, (char *) fr->data);
2458                 break;
2459         case AST_FRAME_HTML:
2460                 res = (chan->tech->send_html == NULL) ? 0 :
2461                         chan->tech->send_html(chan, fr->subclass, (char *) fr->data, fr->datalen);
2462                 break;
2463         case AST_FRAME_VIDEO:
2464                 /* XXX Handle translation of video codecs one day XXX */
2465                 res = (chan->tech->write_video == NULL) ? 0 :
2466                         chan->tech->write_video(chan, fr);
2467                 break;
2468         case AST_FRAME_MODEM:
2469                 res = (chan->tech->write == NULL) ? 0 :
2470                         chan->tech->write(chan, fr);
2471                 break;
2472         case AST_FRAME_VOICE:
2473                 if (chan->tech->write == NULL)
2474                         break;  /*! \todo XXX should return 0 maybe ? */
2475
2476                 /* Bypass translator if we're writing format in the raw write format.  This
2477                    allows mixing of native / non-native formats */
2478                 if (fr->subclass == chan->rawwriteformat)
2479                         f = fr;
2480                 else
2481                         f = (chan->writetrans) ? ast_translate(chan->writetrans, fr, 0) : fr;
2482                 if (f == NULL) {
2483                         res = 0;
2484                 } else {
2485                         if (chan->spies)
2486                                 queue_frame_to_spies(chan, f, SPY_WRITE);
2487
2488                         if (chan->monitor && chan->monitor->write_stream) {
2489                                 /* XXX must explain this code */
2490 #ifndef MONITOR_CONSTANT_DELAY
2491                                 int jump = chan->insmpl - chan->outsmpl - 4 * f->samples;
2492                                 if (jump >= 0) {
2493                                         if (ast_seekstream(chan->monitor->write_stream, jump + f->samples, SEEK_FORCECUR) == -1)
2494                                                 ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
2495                                         chan->outsmpl += jump + 4 * f->samples;
2496                                 } else
2497                                         chan->outsmpl += f->samples;
2498 #else
2499                                 int jump = chan->insmpl - chan->outsmpl;
2500                                 if (jump - MONITOR_DELAY >= 0) {
2501                                         if (ast_seekstream(chan->monitor->write_stream, jump - f->samples, SEEK_FORCECUR) == -1)
2502                                                 ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
2503                                         chan->outsmpl += jump;
2504                                 } else
2505                                         chan->outsmpl += f->samples;
2506 #endif
2507                                 if (chan->monitor->state == AST_MONITOR_RUNNING) {
2508                                         if (ast_writestream(chan->monitor->write_stream, f) < 0)
2509                                                 ast_log(LOG_WARNING, "Failed to write data to channel monitor write stream\n");
2510                                 }
2511                         }
2512
2513                         if (ast_test_flag(chan, AST_FLAG_WHISPER)) {
2514                                 /* frame is assumed to be in SLINEAR, since that is
2515                                    required for whisper mode */
2516                                 ast_frame_adjust_volume(f, -2);
2517                                 if (ast_slinfactory_available(&chan->whisper->sf) >= f->samples) {
2518                                         short buf[f->samples];
2519                                         struct ast_frame whisper = {
2520                                                 .frametype = AST_FRAME_VOICE,
2521                                                 .subclass = AST_FORMAT_SLINEAR,
2522                                                 .data = buf,
2523                                                 .datalen = sizeof(buf),
2524                                                 .samples = f->samples,
2525                                         };
2526
2527                                         ast_mutex_lock(&chan->whisper->lock);
2528                                         if (ast_slinfactory_read(&chan->whisper->sf, buf, f->samples))
2529                                                 ast_frame_slinear_sum(f, &whisper);
2530                                         ast_mutex_unlock(&chan->whisper->lock);
2531                                 }
2532                         }
2533
2534                         res = chan->tech->write(chan, f);
2535                 }
2536                 break;
2537         case AST_FRAME_NULL:
2538         case AST_FRAME_IAX:
2539                 /* Ignore these */
2540                 res = 0;
2541                 break;
2542         default:
2543                 res = chan->tech->write(chan, f);
2544                 break;
2545         }
2546
2547         if (f && f != fr)
2548                 ast_frfree(f);
2549         ast_clear_flag(chan, AST_FLAG_BLOCKING);
2550         /* Consider a write failure to force a soft hangup */
2551         if (res < 0)
2552                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
2553         else {
2554                 chan->fout = FRAMECOUNT_INC(chan->fout);
2555         }
2556 done:
2557         ast_channel_unlock(chan);
2558         return res;
2559 }
2560
2561 static int set_format(struct ast_channel *chan, int fmt, int *rawformat, int *format,
2562                       struct ast_trans_pvt **trans, const int direction)
2563 {
2564         int native;
2565         int res;
2566         
2567         /* Make sure we only consider audio */
2568         fmt &= AST_FORMAT_AUDIO_MASK;
2569         
2570         native = chan->nativeformats;
2571         /* Find a translation path from the native format to one of the desired formats */
2572         if (!direction)
2573                 /* reading */
2574                 res = ast_translator_best_choice(&fmt, &native);
2575         else
2576                 /* writing */
2577                 res = ast_translator_best_choice(&native, &fmt);
2578
2579         if (res < 0) {
2580                 ast_log(LOG_WARNING, "Unable to find a codec translation path from %s to %s\n",
2581                         ast_getformatname(native), ast_getformatname(fmt));
2582                 return -1;
2583         }
2584         
2585         /* Now we have a good choice for both. */
2586         ast_channel_lock(chan);
2587
2588         if ((*rawformat == native) && (*format == fmt)) {
2589                 /* the channel is already in these formats, so nothing to do */
2590                 ast_channel_unlock(chan);
2591                 return 0;
2592         }
2593
2594         *rawformat = native;
2595         /* User perspective is fmt */
2596         *format = fmt;
2597         /* Free any read translation we have right now */
2598         if (*trans)
2599                 ast_translator_free_path(*trans);
2600         /* Build a translation path from the raw format to the desired format */
2601         if (!direction)
2602                 /* reading */
2603                 *trans = ast_translator_build_path(*format, *rawformat);
2604         else
2605                 /* writing */
2606                 *trans = ast_translator_build_path(*rawformat, *format);
2607         ast_channel_unlock(chan);
2608         if (option_debug)
2609                 ast_log(LOG_DEBUG, "Set channel %s to %s format %s\n", chan->name,
2610                         direction ? "write" : "read", ast_getformatname(fmt));
2611         return 0;
2612 }
2613
2614 int ast_set_read_format(struct ast_channel *chan, int fmt)
2615 {
2616         return set_format(chan, fmt, &chan->rawreadformat, &chan->readformat,
2617                           &chan->readtrans, 0);
2618 }
2619
2620 int ast_set_write_format(struct ast_channel *chan, int fmt)
2621 {
2622         return set_format(chan, fmt, &chan->rawwriteformat, &chan->writeformat,
2623                           &chan->writetrans, 1);
2624 }
2625
2626 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)
2627 {
2628         int dummy_outstate;
2629         int cause = 0;
2630         struct ast_channel *chan;
2631         int res = 0;
2632         
2633         if (outstate)
2634                 *outstate = 0;
2635         else
2636                 outstate = &dummy_outstate;     /* make outstate always a valid pointer */
2637
2638         chan = ast_request(type, format, data, &cause);
2639         if (!chan) {
2640                 ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
2641                 /* compute error and return */
2642                 if (cause == AST_CAUSE_BUSY)
2643                         *outstate = AST_CONTROL_BUSY;
2644                 else if (cause == AST_CAUSE_CONGESTION)
2645                         *outstate = AST_CONTROL_CONGESTION;
2646                 return NULL;
2647         }
2648
2649         if (oh) {
2650                 if (oh->vars)   
2651                         ast_set_variables(chan, oh->vars);
2652                 /* XXX why is this necessary, for the parent_channel perhaps ? */
2653                 if (!ast_strlen_zero(oh->cid_num) && !ast_strlen_zero(oh->cid_name))
2654                         ast_set_callerid(chan, oh->cid_num, oh->cid_name, oh->cid_num);
2655                 if (oh->parent_channel)
2656                         ast_channel_inherit_variables(oh->parent_channel, chan);
2657                 if (oh->account)
2658                         ast_cdr_setaccount(chan, oh->account);  
2659         }
2660         ast_set_callerid(chan, cid_num, cid_name, cid_num);
2661
2662         if (ast_call(chan, data, 0)) {  /* ast_call failed... */
2663                 ast_log(LOG_NOTICE, "Unable to call channel %s/%s\n", type, (char *)data);
2664         } else {
2665                 res = 1;        /* mark success in case chan->_state is already AST_STATE_UP */
2666                 while (timeout && chan->_state != AST_STATE_UP) {
2667                         struct ast_frame *f;
2668                         res = ast_waitfor(chan, timeout);
2669                         if (res <= 0) /* error, timeout, or done */
2670                                 break;
2671                         if (timeout > -1)
2672                                 timeout = res;
2673                         f = ast_read(chan);
2674                         if (!f) {
2675                                 *outstate = AST_CONTROL_HANGUP;
2676                                 res = 0;
2677                                 break;
2678                         }
2679                         if (f->frametype == AST_FRAME_CONTROL) {
2680                                 switch (f->subclass) {
2681                                 case AST_CONTROL_RINGING:       /* record but keep going */
2682                                         *outstate = f->subclass;
2683                                         break;
2684
2685                                 case AST_CONTROL_BUSY:
2686                                 case AST_CONTROL_CONGESTION:
2687                                 case AST_CONTROL_ANSWER:
2688                                         *outstate = f->subclass;
2689                                         timeout = 0;            /* trick to force exit from the while() */
2690                                         break;
2691
2692                                 /* Ignore these */
2693                                 case AST_CONTROL_PROGRESS:
2694                                 case AST_CONTROL_PROCEEDING:
2695                                 case AST_CONTROL_HOLD:
2696                                 case AST_CONTROL_UNHOLD:
2697                                 case AST_CONTROL_VIDUPDATE:
2698                                 case -1:                        /* Ignore -- just stopping indications */
2699                                         break;
2700
2701                                 default:
2702                                         ast_log(LOG_NOTICE, "Don't know what to do with control frame %d\n", f->subclass);
2703                                 }
2704                         }
2705                         ast_frfree(f);
2706                 }
2707         }
2708
2709         /* Final fixups */
2710         if (oh) {
2711                 if (!ast_strlen_zero(oh->context))
2712                         ast_copy_string(chan->context, oh->context, sizeof(chan->context));
2713                 if (!ast_strlen_zero(oh->exten))
2714                         ast_copy_string(chan->exten, oh->exten, sizeof(chan->exten));
2715                 if (oh->priority)       
2716                         chan->priority = oh->priority;
2717         }
2718         if (chan->_state == AST_STATE_UP)
2719                 *outstate = AST_CONTROL_ANSWER;
2720
2721         if (res <= 0) {
2722                 if (!chan->cdr && (chan->cdr = ast_cdr_alloc()))
2723                         ast_cdr_init(chan->cdr, chan);
2724                 if (chan->cdr) {
2725                         char tmp[256];
2726                         snprintf(tmp, sizeof(tmp), "%s/%s", type, (char *)data);
2727                         ast_cdr_setapp(chan->cdr,"Dial",tmp);
2728                         ast_cdr_update(chan);
2729                         ast_cdr_start(chan->cdr);
2730                         ast_cdr_end(chan->cdr);
2731                         /* If the cause wasn't handled properly */
2732                         if (ast_cdr_disposition(chan->cdr,chan->hangupcause))
2733                                 ast_cdr_failed(chan->cdr);
2734                 }
2735                 ast_hangup(chan);
2736                 chan = NULL;
2737         }
2738         return chan;
2739 }
2740
2741 struct ast_channel *ast_request_and_dial(const char *type, int format, void *data, int timeout, int *outstate, const char *cidnum, const char *cidname)
2742 {
2743         return __ast_request_and_dial(type, format, data, timeout, outstate, cidnum, cidname, NULL);
2744 }
2745
2746 struct ast_channel *ast_request(const char *type, int format, void *data, int *cause)
2747 {
2748         struct chanlist *chan;
2749         struct ast_channel *c;
2750         int capabilities;
2751         int fmt;
2752         int res;
2753         int foo;
2754         int videoformat = format & AST_FORMAT_VIDEO_MASK;
2755
2756         if (!cause)
2757                 cause = &foo;
2758         *cause = AST_CAUSE_NOTDEFINED;
2759
2760         if (AST_LIST_LOCK(&channels)) {
2761                 ast_log(LOG_WARNING, "Unable to lock channel list\n");
2762                 return NULL;
2763         }
2764
2765         AST_LIST_TRAVERSE(&backends, chan, list) {
2766                 if (strcasecmp(type, chan->tech->type))
2767                         continue;
2768
2769                 capabilities = chan->tech->capabilities;
2770                 fmt = format & AST_FORMAT_AUDIO_MASK;
2771                 res = ast_translator_best_choice(&fmt, &capabilities);
2772                 if (res < 0) {
2773                         ast_log(LOG_WARNING, "No translator path exists for channel type %s (native %d) to %d\n", type, chan->tech->capabilities, format);
2774                         AST_LIST_UNLOCK(&channels);
2775                         return NULL;
2776                 }
2777                 AST_LIST_UNLOCK(&channels);
2778                 if (!chan->tech->requester)
2779                         return NULL;
2780                 
2781                 if (!(c = chan->tech->requester(type, capabilities | videoformat, data, cause)))
2782                         return NULL;
2783
2784                 if (c->_state == AST_STATE_DOWN) {
2785                         manager_event(EVENT_FLAG_CALL, "Newchannel",
2786                                       "Channel: %s\r\n"
2787                                       "State: %s\r\n"
2788                                       "CallerID: %s\r\n"
2789                                       "CallerIDName: %s\r\n"
2790                                       "Uniqueid: %s\r\n",
2791                                       c->name, ast_state2str(c->_state),
2792                                       S_OR(c->cid.cid_num, "<unknown>"),
2793                                       S_OR(c->cid.cid_name, "<unknown>"),
2794                                       c->uniqueid);
2795                 }
2796                 return c;
2797         }
2798
2799         ast_log(LOG_WARNING, "No channel type registered for '%s'\n", type);
2800         *cause = AST_CAUSE_NOSUCHDRIVER;
2801         AST_LIST_UNLOCK(&channels);
2802
2803         return NULL;
2804 }
2805
2806 int ast_call(struct ast_channel *chan, char *addr, int timeout)
2807 {
2808         /* Place an outgoing call, but don't wait any longer than timeout ms before returning.
2809            If the remote end does not answer within the timeout, then do NOT hang up, but
2810            return anyway.  */
2811         int res = -1;
2812         /* Stop if we're a zombie or need a soft hangup */
2813         ast_channel_lock(chan);
2814         if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
2815                 if (chan->tech->call)
2816                         res = chan->tech->call(chan, addr, timeout);
2817                 ast_set_flag(chan, AST_FLAG_OUTGOING);
2818         }
2819         ast_channel_unlock(chan);
2820         return res;
2821 }
2822
2823 /*!
2824   \brief Transfer a call to dest, if the channel supports transfer
2825
2826   Called by:
2827     \arg app_transfer
2828     \arg the manager interface
2829 */
2830 int ast_transfer(struct ast_channel *chan, char *dest)
2831 {
2832         int res = -1;
2833
2834         /* Stop if we're a zombie or need a soft hangup */
2835         ast_channel_lock(chan);
2836         if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
2837                 if (chan->tech->transfer) {
2838                         res = chan->tech->transfer(chan, dest);
2839                         if (!res)
2840                                 res = 1;
2841                 } else
2842                         res = 0;
2843         }
2844         ast_channel_unlock(chan);
2845         return res;
2846 }
2847
2848 int ast_readstring(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders)
2849 {
2850         return ast_readstring_full(c, s, len, timeout, ftimeout, enders, -1, -1);
2851 }
2852
2853 int ast_readstring_full(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders, int audiofd, int ctrlfd)
2854 {
2855         int pos = 0;    /* index in the buffer where we accumulate digits */
2856         int to = ftimeout;
2857
2858         /* Stop if we're a zombie or need a soft hangup */
2859         if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
2860                 return -1;
2861         if (!len)
2862                 return -1;
2863         for (;;) {
2864                 int d;
2865                 if (c->stream) {
2866                         d = ast_waitstream_full(c, AST_DIGIT_ANY, audiofd, ctrlfd);
2867                         ast_stopstream(c);
2868                         usleep(1000);
2869                         if (!d)
2870                                 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
2871                 } else {
2872                         d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
2873                 }
2874                 if (d < 0)
2875                         return -1;
2876                 if (d == 0) {
2877                         s[pos]='\0';
2878                         return 1;
2879                 }
2880                 if (d == 1) {
2881                         s[pos]='\0';
2882                         return 2;
2883                 }
2884                 if (!strchr(enders, d))
2885                         s[pos++] = d;
2886                 if (strchr(enders, d) || (pos >= len)) {
2887                         s[pos]='\0';
2888                         return 0;
2889                 }
2890                 to = timeout;
2891         }
2892         /* Never reached */
2893         return 0;
2894 }
2895
2896 int ast_channel_supports_html(struct ast_channel *chan)
2897 {
2898         return (chan->tech->send_html) ? 1 : 0;
2899 }
2900
2901 int ast_channel_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
2902 {
2903         if (chan->tech->send_html)
2904                 return chan->tech->send_html(chan, subclass, data, datalen);
2905         return -1;
2906 }
2907
2908 int ast_channel_sendurl(struct ast_channel *chan, const char *url)
2909 {
2910         return ast_channel_sendhtml(chan, AST_HTML_URL, url, strlen(url) + 1);
2911 }
2912
2913 int ast_channel_make_compatible(struct ast_channel *chan, struct ast_channel *peer)
2914 {
2915         int src;
2916         int dst;
2917
2918         /* Set up translation from the chan to the peer */
2919         src = chan->nativeformats;
2920         dst = peer->nativeformats;
2921         if (ast_translator_best_choice(&dst, &src) < 0) {
2922                 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", chan->name, src, peer->name, dst);
2923                 return -1;
2924         }
2925
2926         /* if the best path is not 'pass through', then
2927            transcoding is needed; if desired, force transcode path
2928            to use SLINEAR between channels, but only if there is
2929            no direct conversion available */
2930         if ((src != dst) && ast_opt_transcode_via_slin &&
2931             (ast_translate_path_steps(dst, src) != 1))
2932                 dst = AST_FORMAT_SLINEAR;
2933         if (ast_set_read_format(chan, dst) < 0) {
2934                 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", chan->name, dst);
2935                 return -1;
2936         }
2937         if (ast_set_write_format(peer, dst) < 0) {
2938                 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", peer->name, dst);
2939                 return -1;
2940         }
2941
2942         /* Set up translation from the peer to the chan */
2943         src = peer->nativeformats;
2944         dst = chan->nativeformats;
2945         if (ast_translator_best_choice(&dst, &src) < 0) {
2946                 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", peer->name, src, chan->name, dst);
2947                 return -1;
2948         }
2949
2950         /* if the best path is not 'pass through', then
2951            transcoding is needed; if desired, force transcode path
2952            to use SLINEAR between channels, but only if there is
2953            no direct conversion available */
2954         if ((src != dst) && ast_opt_transcode_via_slin &&
2955             (ast_translate_path_steps(dst, src) != 1))
2956                 dst = AST_FORMAT_SLINEAR;
2957         if (ast_set_read_format(peer, dst) < 0) {
2958                 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", peer->name, dst);
2959                 return -1;
2960         }
2961         if (ast_set_write_format(chan, dst) < 0) {
2962                 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", chan->name, dst);
2963                 return -1;
2964         }
2965         return 0;
2966 }
2967
2968 int ast_channel_masquerade(struct ast_channel *original, struct ast_channel *clone)
2969 {
2970         int res = -1;
2971         struct ast_channel *final_orig = original, *final_clone = clone;
2972
2973         ast_channel_lock(original);
2974         while (ast_channel_trylock(clone)) {
2975                 ast_channel_unlock(original);
2976                 usleep(1);
2977                 ast_channel_lock(original);
2978         }
2979
2980         /* each of these channels may be sitting behind a channel proxy (i.e. chan_agent)
2981            and if so, we don't really want to masquerade it, but its proxy */
2982         if (original->_bridge && (original->_bridge != ast_bridged_channel(original)))
2983                 final_orig = original->_bridge;
2984
2985         if (clone->_bridge && (clone->_bridge != ast_bridged_channel(clone)))
2986                 final_clone = clone->_bridge;
2987
2988         if ((final_orig != original) || (final_clone != clone)) {
2989                 ast_channel_lock(final_orig);
2990                 while (ast_channel_trylock(final_clone)) {
2991                         ast_channel_unlock(final_orig);
2992                         usleep(1);
2993                         ast_channel_lock(final_orig);
2994                 }
2995                 ast_channel_unlock(clone);
2996                 ast_channel_unlock(original);
2997                 original = final_orig;
2998                 clone = final_clone;
2999         }
3000
3001         if (original == clone) {
3002                 ast_log(LOG_WARNING, "Can't masquerade channel '%s' into itself!\n", original->name);
3003                 ast_channel_unlock(clone);
3004                 ast_channel_unlock(original);
3005                 return -1;
3006         }
3007
3008         ast_log(LOG_DEBUG, "Planning to masquerade channel %s into the structure of %s\n",
3009                 clone->name, original->name);
3010         if (original->masq) {
3011                 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n",
3012                         original->masq->name, original->name);
3013         } else if (clone->masqr) {
3014                 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n",
3015                         clone->name, clone->masqr->name);
3016         } else {
3017                 original->masq = clone;
3018                 clone->masqr = original;
3019                 ast_queue_frame(original, &ast_null_frame);
3020                 ast_queue_frame(clone, &ast_null_frame);
3021                 ast_log(LOG_DEBUG, "Done planning to masquerade channel %s into the structure of %s\n", clone->name, original->name);
3022                 res = 0;
3023         }
3024
3025         ast_channel_unlock(clone);
3026         ast_channel_unlock(original);
3027
3028         return res;
3029 }
3030
3031 void ast_change_name(struct ast_channel *chan, char *newname)
3032 {
3033         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", chan->name, newname, chan->uniqueid);
3034         ast_string_field_set(chan, name, newname);
3035 }
3036
3037 void ast_channel_inherit_variables(const struct ast_channel *parent, struct ast_channel *child)
3038 {
3039         struct ast_var_t *current, *newvar;
3040         const char *varname;
3041
3042         AST_LIST_TRAVERSE(&parent->varshead, current, entries) {
3043                 int vartype = 0;
3044
3045                 varname = ast_var_full_name(current);
3046                 if (!varname)
3047                         continue;
3048
3049                 if (varname[0] == '_') {
3050                         vartype = 1;
3051                         if (varname[1] == '_')
3052                                 vartype = 2;
3053                 }
3054
3055                 switch (vartype) {
3056                 case 1:
3057                         newvar = ast_var_assign(&varname[1], ast_var_value(current));
3058                         if (newvar) {
3059                                 AST_LIST_INSERT_TAIL(&child->varshead, newvar, entries);
3060                                 if (option_debug)
3061                                         ast_log(LOG_DEBUG, "Copying soft-transferable variable %s.\n", ast_var_name(newvar));
3062                         }
3063                         break;
3064                 case 2:
3065                         newvar = ast_var_assign(ast_var_full_name(current), ast_var_value(current));
3066                         if (newvar) {
3067                                 AST_LIST_INSERT_TAIL(&child->varshead, newvar, entries);
3068                                 if (option_debug)
3069                                         ast_log(LOG_DEBUG, "Copying hard-transferable variable %s.\n", ast_var_name(newvar));
3070                         }
3071                         break;
3072                 default:
3073                         if (option_debug)
3074                                 ast_log(LOG_DEBUG, "Not copying variable %s.\n", ast_var_name(current));
3075                         break;
3076                 }
3077         }
3078 }
3079
3080 /*!
3081   \brief Clone channel variables from 'clone' channel into 'original' channel
3082
3083   All variables except those related to app_groupcount are cloned.
3084   Variables are actually _removed_ from 'clone' channel, presumably
3085   because it will subsequently be destroyed.
3086
3087   \note Assumes locks will be in place on both channels when called.
3088 */
3089 static void clone_variables(struct ast_channel *original, struct ast_channel *clone)
3090 {
3091         struct ast_var_t *varptr;
3092
3093         /* we need to remove all app_groupcount related variables from the original
3094            channel before merging in the clone's variables; any groups assigned to the
3095            original channel should be released, only those assigned to the clone
3096            should remain
3097         */
3098
3099         AST_LIST_TRAVERSE_SAFE_BEGIN(&original->varshead, varptr, entries) {
3100                 if (!strncmp(ast_var_name(varptr), GROUP_CATEGORY_PREFIX, strlen(GROUP_CATEGORY_PREFIX))) {
3101                         AST_LIST_REMOVE_CURRENT(&original->varshead, entries);
3102                         ast_var_delete(varptr);
3103                 }
3104         }
3105         AST_LIST_TRAVERSE_SAFE_END;
3106
3107         /* Append variables from clone channel into original channel */
3108         /* XXX Is this always correct?  We have to in order to keep MACROS working XXX */
3109         if (AST_LIST_FIRST(&clone->varshead))
3110                 AST_LIST_APPEND_LIST(&original->varshead, &clone->varshead, entries);
3111 }
3112
3113 /*!
3114   \brief Masquerade a channel
3115
3116   \note Assumes channel will be locked when called
3117 */
3118 int ast_do_masquerade(struct ast_channel *original)
3119 {
3120         int x,i;
3121         int res=0;
3122         int origstate;
3123         struct ast_frame *cur;
3124         const struct ast_channel_tech *t;
3125         void *t_pvt;
3126         struct ast_callerid tmpcid;
3127         struct ast_channel *clone = original->masq;
3128         int rformat = original->readformat;
3129         int wformat = original->writeformat;
3130         char newn[100];
3131         char orig[100];
3132         char masqn[100];
3133         char zombn[100];
3134
3135         if (option_debug > 3)
3136                 ast_log(LOG_DEBUG, "Actually Masquerading %s(%d) into the structure of %s(%d)\n",
3137                         clone->name, clone->_state, original->name, original->_state);
3138
3139         /* XXX This is a seriously wacked out operation.  We're essentially putting the guts of
3140            the clone channel into the original channel.  Start by killing off the original
3141            channel's backend.   I'm not sure we're going to keep this function, because
3142            while the features are nice, the cost is very high in terms of pure nastiness. XXX */
3143
3144         /* We need the clone's lock, too */
3145         ast_channel_lock(clone);
3146
3147         if (option_debug > 1)
3148                 ast_log(LOG_DEBUG, "Got clone lock for masquerade on '%s' at %p\n", clone->name, &clone->lock);
3149
3150         /* Having remembered the original read/write formats, we turn off any translation on either
3151            one */
3152         free_translation(clone);
3153         free_translation(original);
3154
3155
3156         /* Unlink the masquerade */
3157         original->masq = NULL;
3158         clone->masqr = NULL;
3159         
3160         /* Save the original name */
3161         ast_copy_string(orig, original->name, sizeof(orig));
3162         /* Save the new name */
3163         ast_copy_string(newn, clone->name, sizeof(newn));
3164         /* Create the masq name */
3165         snprintf(masqn, sizeof(masqn), "%s<MASQ>", newn);
3166                 
3167         /* Copy the name from the clone channel */
3168         ast_string_field_set(original, name, newn);
3169
3170         /* Mangle the name of the clone channel */
3171         ast_string_field_set(clone, name, masqn);
3172         
3173         /* Notify any managers of the change, first the masq then the other */
3174         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", newn, masqn, clone->uniqueid);
3175         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", orig, newn, original->uniqueid);
3176
3177         /* Swap the technologies */     
3178         t = original->tech;
3179         original->tech = clone->tech;
3180         clone->tech = t;
3181
3182         t_pvt = original->tech_pvt;
3183         original->tech_pvt = clone->tech_pvt;
3184         clone->tech_pvt = t_pvt;
3185
3186         /* Swap the readq's */
3187         cur = AST_LIST_FIRST(&original->readq);
3188         AST_LIST_HEAD_SET_NOLOCK(&original->readq, AST_LIST_FIRST(&clone->readq));
3189         AST_LIST_HEAD_SET_NOLOCK(&clone->readq, cur);
3190
3191         /* Swap the alertpipes */
3192         for (i = 0; i < 2; i++) {
3193                 x = original->alertpipe[i];
3194                 original->alertpipe[i] = clone->alertpipe[i];
3195                 clone->alertpipe[i] = x;
3196         }
3197
3198         /* Swap the raw formats */
3199         x = original->rawreadformat;
3200         original->rawreadformat = clone->rawreadformat;
3201         clone->rawreadformat = x;
3202         x = original->rawwriteformat;
3203         original->rawwriteformat = clone->rawwriteformat;
3204         clone->rawwriteformat = x;
3205
3206         /* Save any pending frames on both sides.  Start by counting
3207          * how many we're going to need... */
3208         x = 0;
3209         if (original->alertpipe[1] > -1) {
3210                 AST_LIST_TRAVERSE(&clone->readq, cur, frame_list)
3211                         x++;
3212         }
3213
3214         /* If we had any, prepend them to the ones already in the queue, and 
3215          * load up the alertpipe */
3216         if (AST_LIST_FIRST(&clone->readq)) {
3217                 AST_LIST_INSERT_TAIL(&clone->readq, AST_LIST_FIRST(&original->readq), frame_list);
3218                 AST_LIST_HEAD_SET_NOLOCK(&original->readq, AST_LIST_FIRST(&clone->readq));
3219                 AST_LIST_HEAD_SET_NOLOCK(&clone->readq, NULL);
3220                 for (i = 0; i < x; i++)
3221                         write(original->alertpipe[1], &x, sizeof(x));
3222         }
3223         
3224         clone->_softhangup = AST_SOFTHANGUP_DEV;
3225
3226
3227         /* And of course, so does our current state.  Note we need not
3228            call ast_setstate since the event manager doesn't really consider
3229            these separate.  We do this early so that the clone has the proper
3230            state of the original channel. */
3231         origstate = original->_state;
3232         original->_state = clone->_state;
3233         clone->_state = origstate;
3234
3235         if (clone->tech->fixup){
3236                 res = clone->tech->fixup(original, clone);
3237                 if (res)
3238                         ast_log(LOG_WARNING, "Fixup failed on channel %s, strange things may happen.\n", clone->name);
3239         }
3240
3241         /* Start by disconnecting the original's physical side */
3242         if (clone->tech->hangup)
3243                 res = clone->tech->hangup(clone);
3244         if (res) {
3245                 ast_log(LOG_WARNING, "Hangup failed!  Strange things may happen!\n");
3246                 ast_channel_unlock(clone);
3247                 return -1;
3248         }
3249         
3250         snprintf(zombn, sizeof(zombn), "%s<ZOMBIE>", orig);
3251         /* Mangle the name of the clone channel */
3252         ast_string_field_set(clone, name, zombn);
3253         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", masqn, zombn, clone->uniqueid);
3254
3255         /* Update the type. */
3256         t_pvt = original->monitor;
3257         original->monitor = clone->monitor;
3258         clone->monitor = t_pvt;
3259         
3260         /* Keep the same language.  */
3261         ast_string_field_set(original, language, clone->language);
3262         /* Copy the FD's other than the generator fd */
3263         for (x = 0; x < AST_MAX_FDS; x++) {
3264                 if (x != AST_GENERATOR_FD)
3265                         original->fds[x] = clone->fds[x];
3266         }
3267
3268         /* move any whisperer over */
3269         ast_channel_whisper_stop(original);
3270         if (ast_test_flag(clone, AST_FLAG_WHISPER)) {
3271                 original->whisper = clone->whisper;
3272                 ast_set_flag(original, AST_FLAG_WHISPER);
3273                 clone->whisper = NULL;
3274                 ast_clear_flag(clone, AST_FLAG_WHISPER);
3275         }
3276
3277         /* Move data stores over */
3278         if (AST_LIST_FIRST(&clone->datastores))
3279                 AST_LIST_INSERT_TAIL(&original->datastores, AST_LIST_FIRST(&clone->datastores), entry);
3280         AST_LIST_HEAD_INIT_NOLOCK(&clone->datastores);
3281
3282         clone_variables(original, clone);
3283         AST_LIST_HEAD_INIT_NOLOCK(&clone->varshead);
3284         /* Presense of ADSI capable CPE follows clone */
3285         original->adsicpe = clone->adsicpe;
3286         /* Bridge remains the same */
3287         /* CDR fields remain the same */
3288         /* XXX What about blocking, softhangup, blocker, and lock and blockproc? XXX */
3289         /* Application and data remain the same */
3290         /* Clone exception  becomes real one, as with fdno */
3291         ast_copy_flags(original, clone, AST_FLAG_EXCEPTION);
3292         original->fdno = clone->fdno;
3293         /* Schedule context remains the same */
3294         /* Stream stuff stays the same */
3295         /* Keep the original state.  The fixup code will need to work with it most likely */
3296
3297         /* Just swap the whole structures, nevermind the allocations, they'll work themselves
3298            out. */
3299         tmpcid = original->cid;
3300         original->cid = clone->cid;
3301         clone->cid = tmpcid;
3302         
3303         /* Restore original timing file descriptor */
3304         original->fds[AST_TIMING_FD] = original->timingfd;
3305         
3306         /* Our native formats are different now */
3307         original->nativeformats = clone->nativeformats;
3308         
3309         /* Context, extension, priority, app data, jump table,  remain the same */
3310         /* pvt switches.  pbx stays the same, as does next */
3311         
3312         /* Set the write format */
3313         ast_set_write_format(original, wformat);
3314
3315         /* Set the read format */
3316         ast_set_read_format(original, rformat);
3317
3318         /* Copy the music class */
3319         ast_string_field_set(original, musicclass, clone->musicclass);
3320
3321         if (option_debug)
3322                 ast_log(LOG_DEBUG, "Putting channel %s in %d/%d formats\n", original->name, wformat, rformat);
3323
3324         /* Okay.  Last thing is to let the channel driver know about all this mess, so he
3325            can fix up everything as best as possible */
3326         if (original->tech->fixup) {
3327                 res = original->tech->fixup(clone, original);
3328                 if (res) {
3329                         ast_log(LOG_WARNING, "Channel for type '%s' could not fixup channel %s\n",
3330                                 original->tech->type, original->name);
3331                         ast_channel_unlock(clone);
3332                         return -1;
3333                 }
3334         } else
3335                 ast_log(LOG_WARNING, "Channel type '%s' does not have a fixup routine (for %s)!  Bad things may happen.\n",
3336                         original->tech->type, original->name);
3337         
3338         /* Now, at this point, the "clone" channel is totally F'd up.  We mark it as
3339            a zombie so nothing tries to touch it.  If it's already been marked as a
3340            zombie, then free it now (since it already is considered invalid). */
3341         if (ast_test_flag(clone, AST_FLAG_ZOMBIE)) {
3342                 if (option_debug)
3343                         ast_log(LOG_DEBUG, "Destroying channel clone '%s'\n", clone->name);
3344                 ast_channel_unlock(clone);
3345                 manager_event(EVENT_FLAG_CALL, "Hangup",
3346                         "Channel: %s\r\n"
3347                         "Uniqueid: %s\r\n"
3348                         "Cause: %d\r\n"
3349                         "Cause-txt: %s\r\n",
3350                         clone->name,
3351                         clone->uniqueid,
3352                         clone->hangupcause,
3353                         ast_cause2str(clone->hangupcause)
3354                         );
3355                 ast_channel_free(clone);
3356         } else {
3357                 ast_log(LOG_DEBUG, "Released clone lock on '%s'\n", clone->name);
3358                 ast_set_flag(clone, AST_FLAG_ZOMBIE);
3359                 ast_queue_frame(clone, &ast_null_frame);
3360                 ast_channel_unlock(clone);
3361         }
3362         
3363         /* Signal any blocker */
3364         if (ast_test_flag(original, AST_FLAG_BLOCKING))
3365                 pthread_kill(original->blocker, SIGURG);
3366         if (option_debug)
3367                 ast_log(LOG_DEBUG, "Done Masquerading %s (%d)\n", original->name, original->_state);
3368         return 0;
3369 }
3370
3371 void ast_set_callerid(struct ast_channel *chan, const char *callerid, const char *calleridname, const char *ani)
3372 {
3373         if (callerid) {
3374                 if (chan->cid.cid_num)
3375                         free(chan->cid.cid_num);
3376                 chan->cid.cid_num = ast_strdup(callerid);
3377         }
3378         if (calleridname) {
3379                 if (chan->cid.cid_name)
3380                         free(chan->cid.cid_name);
3381                 chan->cid.cid_name = ast_strdup(calleridname);
3382         }
3383         if (ani) {
3384                 if (chan->cid.cid_ani)
3385                         free(chan->cid.cid_ani);
3386                 chan->cid.cid_ani = ast_strdup(ani);
3387         }
3388         if (chan->cdr)
3389                 ast_cdr_setcid(chan->cdr, chan);
3390         manager_event(EVENT_FLAG_CALL, "Newcallerid",
3391                                 "Channel: %s\r\n"
3392                                 "CallerID: %s\r\n"
3393                                 "CallerIDName: %s\r\n"
3394                                 "Uniqueid: %s\r\n"
3395                                 "CID-CallingPres: %d (%s)\r\n",
3396                                 chan->name,
3397                                 S_OR(chan->cid.cid_num, "<Unknown>"),
3398                                 S_OR(chan->cid.cid_name, "<Unknown>"),
3399                                 chan->uniqueid,
3400                                 chan->cid.cid_pres,
3401                                 ast_describe_caller_presentation(chan->cid.cid_pres)
3402                                 );
3403 }
3404
3405 int ast_setstate(struct ast_channel *chan, enum ast_channel_state state)
3406 {
3407         int oldstate = chan->_state;
3408
3409         if (oldstate == state)
3410                 return 0;
3411
3412         chan->_state = state;
3413         ast_device_state_changed_literal(chan->name);
3414         manager_event(EVENT_FLAG_CALL,
3415                       (oldstate == AST_STATE_DOWN) ? "Newchannel" : "Newstate",
3416                       "Channel: %s\r\n"
3417                       "State: %s\r\n"
3418                       "CallerID: %s\r\n"
3419                       "CallerIDName: %s\r\n"
3420                       "Uniqueid: %s\r\n",
3421                       chan->name, ast_state2str(chan->_state),
3422                       S_OR(chan->cid.cid_num, "<unknown>"),
3423                       S_OR(chan->cid.cid_name, "<unknown>"),
3424                       chan->uniqueid);
3425
3426         return 0;
3427 }
3428
3429 /*! \brief Find bridged channel */
3430 struct ast_channel *ast_bridged_channel(struct ast_channel *chan)
3431 {
3432         struct ast_channel *bridged;
3433         bridged = chan->_bridge;
3434         if (bridged && bridged->tech->bridged_channel)
3435                 bridged = bridged->tech->bridged_channel(chan, bridged);
3436         return bridged;
3437 }
3438
3439 static void bridge_playfile(struct ast_channel *chan, struct ast_channel *peer, const char *sound, int remain)
3440 {
3441         int min = 0, sec = 0, check;
3442
3443         check = ast_autoservice_start(peer);
3444         if (check)
3445                 return;
3446
3447         if (remain > 0) {
3448                 if (remain / 60 > 1) {
3449                         min = remain / 60;
3450                         sec = remain % 60;
3451                 } else {
3452                         sec = remain;
3453                 }
3454         }
3455         
3456         if (!strcmp(sound,"timeleft")) {        /* Queue support */
3457                 ast_stream_and_wait(chan, "vm-youhave", chan->language, "");
3458                 if (min) {
3459                         ast_say_number(chan, min, AST_DIGIT_ANY, chan->language, NULL);
3460                         ast_stream_and_wait(chan, "queue-minutes", chan->language, "");
3461                 }
3462                 if (sec) {
3463                         ast_say_number(chan, sec, AST_DIGIT_ANY, chan->language, NULL);
3464                         ast_stream_and_wait(chan, "queue-seconds", chan->language, "");
3465                 }
3466         } else {
3467                 ast_stream_and_wait(chan, sound, chan->language, "");
3468         }
3469
3470         ast_autoservice_stop(peer);
3471 }
3472
3473 static enum ast_bridge_result ast_generic_bridge(struct ast_channel *c0, struct ast_channel *c1,
3474                                                  struct ast_bridge_config *config, struct ast_frame **fo,
3475                                                  struct ast_channel **rc, struct timeval bridge_end)
3476 {
3477         /* Copy voice back and forth between the two channels. */
3478         struct ast_channel *cs[3];
3479         struct ast_frame *f;
3480         enum ast_bridge_result res = AST_BRIDGE_COMPLETE;
3481         int o0nativeformats;
3482         int o1nativeformats;
3483         int watch_c0_dtmf;
3484         int watch_c1_dtmf;
3485         void *pvt0, *pvt1;
3486         /* Indicates whether a frame was queued into a jitterbuffer */
3487         int frame_put_in_jb = 0;
3488         int jb_in_use;
3489         int to;
3490         
3491         cs[0] = c0;
3492         cs[1] = c1;
3493         pvt0 = c0->tech_pvt;
3494         pvt1 = c1->tech_pvt;
3495         o0nativeformats = c0->nativeformats;
3496         o1nativeformats = c1->nativeformats;
3497         watch_c0_dtmf = config->flags & AST_BRIDGE_DTMF_CHANNEL_0;
3498         watch_c1_dtmf = config->flags & AST_BRIDGE_DTMF_CHANNEL_1;
3499
3500         /* Check the need of a jitterbuffer for each channel */
3501         jb_in_use = ast_jb_do_usecheck(c0, c1);
3502
3503         for (;;) {
3504                 struct ast_channel *who, *other;
3505
3506                 if ((c0->tech_pvt != pvt0) || (c1->tech_pvt != pvt1) ||
3507                     (o0nativeformats != c0->nativeformats) ||
3508                     (o1nativeformats != c1->nativeformats)) {
3509                         /* Check for Masquerade, codec changes, etc */
3510                         res = AST_BRIDGE_RETRY;
3511                         break;
3512                 }
3513                 if (bridge_end.tv_sec) {
3514                         to = ast_tvdiff_ms(bridge_end, ast_tvnow());
3515                         if (to <= 0) {
3516                                 res = AST_BRIDGE_RETRY;
3517                                 break;
3518                         }
3519                 } else
3520                         to = -1;
3521                 /* Calculate the appropriate max sleep interval - in general, this is the time,
3522                    left to the closest jb delivery moment */
3523                 if (jb_in_use)
3524                         to = ast_jb_get_when_to_wakeup(c0, c1, to);
3525                 who = ast_waitfor_n(cs, 2, &to);
3526                 if (!who) {
3527                         /* No frame received within the specified timeout - check if we have to deliver now */
3528                         if (jb_in_use)
3529                                 ast_jb_get_and_deliver(c0, c1);
3530                         if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE || c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE) {
3531                                 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
3532                                         c0->_softhangup = 0;
3533                                 if (c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
3534                                         c1->_softhangup = 0;
3535                                 c0->_bridge = c1;
3536                                 c1->_bridge = c0;
3537                         }
3538                         continue;
3539                 }
3540                 f = ast_read(who);
3541                 if (!f) {
3542                         *fo = NULL;
3543                         *rc = who;
3544                         ast_log(LOG_DEBUG, "Didn't get a frame from channel: %s\n",who->name);
3545                         break;
3546                 }
3547
3548                 other = (who == c0) ? c1 : c0; /* the 'other' channel */
3549                 /* Try add the frame info the who's bridged channel jitterbuff */
3550                 if (jb_in_use)
3551                         frame_put_in_jb = !ast_jb_put(other, f);<