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