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