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