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