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