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