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