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