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