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