2 * Asterisk -- A telephony toolkit for Linux.
6 * Copyright (C) 1999 - 2005, Digium, Inc.
8 * Mark Spencer <markster@digium.com>
10 * This program is free software, distributed under the terms of
11 * the GNU General Public License
21 #include <math.h> /* For PI */
22 #include "asterisk/pbx.h"
23 #include "asterisk/frame.h"
24 #include "asterisk/sched.h"
25 #include "asterisk/options.h"
26 #include "asterisk/channel.h"
27 #include "asterisk/musiconhold.h"
28 #include "asterisk/logger.h"
29 #include "asterisk/say.h"
30 #include "asterisk/file.h"
31 #include "asterisk/cli.h"
32 #include "asterisk/translate.h"
33 #include "asterisk/manager.h"
34 #include "asterisk/chanvars.h"
35 #include "asterisk/linkedlists.h"
36 #include "asterisk/indications.h"
37 #include "asterisk/monitor.h"
38 #include "asterisk/causes.h"
39 #include "asterisk/utils.h"
40 #include "asterisk/lock.h"
41 #include "asterisk/app.h"
42 #include "asterisk/transcap.h"
43 #ifdef ZAPTEL_OPTIMIZATIONS
44 #include <sys/ioctl.h>
46 #include <linux/zaptel.h>
49 #endif /* __linux__ */
51 #error "You need newer zaptel! Please cvs update zaptel"
56 /* uncomment if you have problems with 'monitoring' synchronized files */
58 #define MONITOR_CONSTANT_DELAY
59 #define MONITOR_DELAY 150 * 8 /* 150 ms of MONITORING DELAY */
62 static int shutting_down = 0;
63 static int uniqueint = 0;
65 unsigned long global_fin = 0, global_fout = 0;
67 /* XXX Lock appropriately in more functions XXX */
70 const struct ast_channel_tech *tech;
71 struct chanlist *next;
73 struct ast_channel *channels = NULL;
75 /* Protect the channel list (highly unlikely that two things would change
76 it at the same time, but still! */
78 AST_MUTEX_DEFINE_STATIC(chlock);
80 static int show_channeltypes(int fd, int argc, char *argv[])
82 #define FORMAT "%-7.7s %-50.50s\n"
83 struct chanlist *cl = backends;
84 ast_cli(fd, FORMAT, "Type", "Description");
85 ast_cli(fd, FORMAT, "------", "-----------");
86 if (ast_mutex_lock(&chlock)) {
87 ast_log(LOG_WARNING, "Unable to lock channel list\n");
91 ast_cli(fd, FORMAT, cl->tech->type, cl->tech->description);
94 ast_mutex_unlock(&chlock);
95 return RESULT_SUCCESS;
99 static char show_channeltypes_usage[] =
100 "Usage: show channeltypes\n"
101 " Shows available channel types registered in your Asterisk server.\n";
103 static struct ast_cli_entry cli_show_channeltypes =
104 { { "show", "channeltypes", NULL }, show_channeltypes, "Show available channel types", show_channeltypes_usage };
106 int ast_check_hangup(struct ast_channel *chan)
110 /* if soft hangup flag, return true */
111 if (chan->_softhangup) return 1;
112 /* if no technology private data, return true */
113 if (!chan->tech_pvt) return 1;
114 /* if no hangup scheduled, just return here */
115 if (!chan->whentohangup) return 0;
116 time(&myt); /* get current time */
117 /* return, if not yet */
118 if (chan->whentohangup > myt) return 0;
119 chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
123 static int ast_check_hangup_locked(struct ast_channel *chan)
126 ast_mutex_lock(&chan->lock);
127 res = ast_check_hangup(chan);
128 ast_mutex_unlock(&chan->lock);
132 void ast_begin_shutdown(int hangup)
134 struct ast_channel *c;
137 ast_mutex_lock(&chlock);
140 ast_softhangup(c, AST_SOFTHANGUP_SHUTDOWN);
143 ast_mutex_unlock(&chlock);
147 int ast_active_channels(void)
149 struct ast_channel *c;
151 ast_mutex_lock(&chlock);
157 ast_mutex_unlock(&chlock);
161 void ast_cancel_shutdown(void)
166 int ast_shutting_down(void)
168 return shutting_down;
171 void ast_channel_setwhentohangup(struct ast_channel *chan, time_t offset)
177 chan->whentohangup = myt + offset;
179 chan->whentohangup = 0;
183 int ast_channel_register(const struct ast_channel_tech *tech)
185 struct chanlist *chan;
187 ast_mutex_lock(&chlock);
191 if (!strcasecmp(tech->type, chan->tech->type)) {
192 ast_log(LOG_WARNING, "Already have a handler for type '%s'\n", tech->type);
193 ast_mutex_unlock(&chlock);
199 chan = malloc(sizeof(*chan));
201 ast_log(LOG_WARNING, "Out of memory\n");
202 ast_mutex_unlock(&chlock);
206 chan->next = backends;
210 ast_log(LOG_DEBUG, "Registered handler for '%s' (%s)\n", chan->tech->type, chan->tech->description);
212 if (option_verbose > 1)
213 ast_verbose(VERBOSE_PREFIX_2 "Registered channel type '%s' (%s)\n", chan->tech->type,
214 chan->tech->description);
216 ast_mutex_unlock(&chlock);
220 char *ast_state2str(int state)
222 /* XXX Not reentrant XXX */
223 static char localtmp[256];
227 case AST_STATE_RESERVED:
229 case AST_STATE_OFFHOOK:
231 case AST_STATE_DIALING:
235 case AST_STATE_RINGING:
242 snprintf(localtmp, sizeof(localtmp), "Unknown (%d)\n", state);
247 char *ast_transfercapability2str(int transfercapability)
249 switch(transfercapability) {
250 case AST_TRANS_CAP_SPEECH:
252 case AST_TRANS_CAP_DIGITAL:
254 case AST_TRANS_CAP_RESTRICTED_DIGITAL:
255 return "RESTRICTED_DIGITAL";
256 case AST_TRANS_CAP_3_1K_AUDIO:
258 case AST_TRANS_CAP_DIGITAL_W_TONES:
259 return "DIGITAL_W_TONES";
260 case AST_TRANS_CAP_VIDEO:
267 int ast_best_codec(int fmts)
269 /* This just our opinion, expressed in code. We are asked to choose
270 the best codec to use, given no information */
274 /* Okay, ulaw is used by all telephony equipment, so start with it */
276 /* Unless of course, you're a silly European, so then prefer ALAW */
278 /* Okay, well, signed linear is easy to translate into other stuff */
280 /* G.726 is standard ADPCM */
282 /* ADPCM has great sound quality and is still pretty easy to translate */
284 /* Okay, we're down to vocoders now, so pick GSM because it's small and easier to
285 translate and sounds pretty good */
287 /* iLBC is not too bad */
289 /* Speex is free, but computationally more expensive than GSM */
291 /* Ick, LPC10 sounds terrible, but at least we have code for it, if you're tacky enough
294 /* G.729a is faster than 723 and slightly less expensive */
296 /* Down to G.723.1 which is proprietary but at least designed for voice */
301 for (x=0;x<sizeof(prefs) / sizeof(prefs[0]); x++)
304 ast_log(LOG_WARNING, "Don't know any of 0x%x formats\n", fmts);
308 static const struct ast_channel_tech null_tech = {
310 .description = "Null channel (should not see this)",
313 struct ast_channel *ast_channel_alloc(int needqueue)
315 struct ast_channel *tmp;
318 struct varshead *headp;
321 /* If shutting down, don't allocate any new channels */
325 tmp = malloc(sizeof(struct ast_channel));
327 ast_log(LOG_WARNING, "Out of memory\n");
331 memset(tmp, 0, sizeof(struct ast_channel));
332 tmp->sched = sched_context_create();
334 ast_log(LOG_WARNING, "Unable to create schedule context\n");
339 for (x=0;x<AST_MAX_FDS - 1;x++)
342 #ifdef ZAPTEL_OPTIMIZATIONS
343 tmp->timingfd = open("/dev/zap/timer", O_RDWR);
344 if (tmp->timingfd > -1) {
345 /* Check if timing interface supports new
348 if (!ioctl(tmp->timingfd, ZT_TIMERPONG, &flags))
356 if (pipe(tmp->alertpipe)) {
357 ast_log(LOG_WARNING, "Alert pipe creation failed!\n");
361 flags = fcntl(tmp->alertpipe[0], F_GETFL);
362 fcntl(tmp->alertpipe[0], F_SETFL, flags | O_NONBLOCK);
363 flags = fcntl(tmp->alertpipe[1], F_GETFL);
364 fcntl(tmp->alertpipe[1], F_SETFL, flags | O_NONBLOCK);
367 /* Make sure we've got it done right if they don't */
368 tmp->alertpipe[0] = tmp->alertpipe[1] = -1;
370 /* Always watch the alertpipe */
371 tmp->fds[AST_MAX_FDS-1] = tmp->alertpipe[0];
372 /* And timing pipe */
373 tmp->fds[AST_MAX_FDS-2] = tmp->timingfd;
374 strncpy(tmp->name, "**Unknown**", sizeof(tmp->name)-1);
376 tmp->_state = AST_STATE_DOWN;
380 tmp->fin = global_fin;
381 tmp->fout = global_fout;
382 snprintf(tmp->uniqueid, sizeof(tmp->uniqueid), "%li.%d", (long)time(NULL), uniqueint++);
383 headp = &tmp->varshead;
384 ast_mutex_init(&tmp->lock);
385 AST_LIST_HEAD_INIT(headp);
386 strncpy(tmp->context, "default", sizeof(tmp->context)-1);
387 strncpy(tmp->language, defaultlanguage, sizeof(tmp->language)-1);
388 strncpy(tmp->exten, "s", sizeof(tmp->exten)-1);
390 tmp->amaflags = ast_default_amaflags;
391 strncpy(tmp->accountcode, ast_default_accountcode, sizeof(tmp->accountcode)-1);
393 tmp->tech = &null_tech;
395 ast_mutex_lock(&chlock);
396 tmp->next = channels;
399 ast_mutex_unlock(&chlock);
403 int ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin)
406 struct ast_frame *prev, *cur;
409 /* Build us a copy and free the original one */
412 ast_log(LOG_WARNING, "Unable to duplicate frame\n");
415 ast_mutex_lock(&chan->lock);
419 if ((cur->frametype == AST_FRAME_CONTROL) && (cur->subclass == AST_CONTROL_HANGUP)) {
420 /* Don't bother actually queueing anything after a hangup */
422 ast_mutex_unlock(&chan->lock);
429 /* Allow up to 96 voice frames outstanding, and up to 128 total frames */
430 if (((fin->frametype == AST_FRAME_VOICE) && (qlen > 96)) || (qlen > 128)) {
431 if (fin->frametype != AST_FRAME_VOICE) {
432 ast_log(LOG_WARNING, "Exceptionally long queue length queuing to %s\n", chan->name);
435 ast_log(LOG_DEBUG, "Dropping voice to exceptionally long queue on %s\n", chan->name);
437 ast_mutex_unlock(&chan->lock);
445 if (chan->alertpipe[1] > -1) {
446 if (write(chan->alertpipe[1], &blah, sizeof(blah)) != sizeof(blah))
447 ast_log(LOG_WARNING, "Unable to write to alert pipe on %s, frametype/subclass %d/%d (qlen = %d): %s!\n",
448 chan->name, f->frametype, f->subclass, qlen, strerror(errno));
449 #ifdef ZAPTEL_OPTIMIZATIONS
450 } else if (chan->timingfd > -1) {
451 ioctl(chan->timingfd, ZT_TIMERPING, &blah);
453 } else if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
454 pthread_kill(chan->blocker, SIGURG);
456 ast_mutex_unlock(&chan->lock);
460 int ast_queue_hangup(struct ast_channel *chan)
462 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_HANGUP };
463 chan->_softhangup |= AST_SOFTHANGUP_DEV;
464 return ast_queue_frame(chan, &f);
467 int ast_queue_control(struct ast_channel *chan, int control)
469 struct ast_frame f = { AST_FRAME_CONTROL, };
470 f.subclass = control;
471 return ast_queue_frame(chan, &f);
474 int ast_channel_defer_dtmf(struct ast_channel *chan)
478 pre = ast_test_flag(chan, AST_FLAG_DEFER_DTMF);
479 ast_set_flag(chan, AST_FLAG_DEFER_DTMF);
484 void ast_channel_undefer_dtmf(struct ast_channel *chan)
487 ast_clear_flag(chan, AST_FLAG_DEFER_DTMF);
490 struct ast_channel *ast_channel_walk_locked(struct ast_channel *prev)
492 /* Returns next channel (locked) */
493 struct ast_channel *l, *ret;
497 ast_mutex_lock(&chlock);
501 if (ast_mutex_trylock(&l->lock)) {
503 ast_log(LOG_DEBUG, "Avoiding initial deadlock for '%s'\n", l->name);
505 ast_log(LOG_WARNING, "Avoided initial deadlock for '%s', %d retries!\n", l->name, retries);
506 ast_mutex_unlock(&chlock);
515 ast_mutex_unlock(&chlock);
524 if (ast_mutex_trylock(&ret->lock)) {
526 ast_log(LOG_DEBUG, "Avoiding deadlock for '%s'\n", ret->name);
528 ast_log(LOG_WARNING, "Avoided deadlock for '%s', %d retries!\n", ret->name, retries);
529 ast_mutex_unlock(&chlock);
538 ast_mutex_unlock(&chlock);
543 struct ast_channel *ast_get_channel_by_name_locked(char *channame)
545 struct ast_channel *chan;
546 chan = ast_channel_walk_locked(NULL);
548 if (!strcasecmp(chan->name, channame))
550 ast_mutex_unlock(&chan->lock);
551 chan = ast_channel_walk_locked(chan);
556 int ast_safe_sleep_conditional( struct ast_channel *chan, int ms,
557 int (*cond)(void*), void *data )
562 if( cond && ((*cond)(data) == 0 ) )
564 ms = ast_waitfor(chan, ms);
577 int ast_safe_sleep(struct ast_channel *chan, int ms)
581 ms = ast_waitfor(chan, ms);
594 static void free_cid(struct ast_callerid *cid)
605 free(cid->cid_rdnis);
608 void ast_channel_free(struct ast_channel *chan)
610 struct ast_channel *last=NULL, *cur;
612 struct ast_var_t *vardata;
613 struct ast_frame *f, *fp;
614 struct varshead *headp;
615 char name[AST_CHANNEL_NAME];
617 headp=&chan->varshead;
619 ast_mutex_lock(&chlock);
624 last->next = cur->next;
626 channels = cur->next;
633 ast_log(LOG_WARNING, "Unable to find channel in list\n");
635 /* Lock and unlock the channel just to be sure nobody
636 has it locked still */
637 ast_mutex_lock(&cur->lock);
638 ast_mutex_unlock(&cur->lock);
640 if (chan->tech_pvt) {
641 ast_log(LOG_WARNING, "Channel '%s' may not have been hung up properly\n", chan->name);
642 free(chan->tech_pvt);
645 strncpy(name, chan->name, sizeof(name)-1);
647 /* Stop monitoring */
649 chan->monitor->stop( chan, 0 );
652 /* If there is native format music-on-hold state, free it */
653 if(chan->music_state)
654 ast_moh_cleanup(chan);
656 /* Free translatosr */
658 ast_translator_free_path(chan->readtrans);
659 if (chan->writetrans)
660 ast_translator_free_path(chan->writetrans);
662 ast_log(LOG_WARNING, "PBX may not have been terminated properly on '%s'\n", chan->name);
663 free_cid(&chan->cid);
664 ast_mutex_destroy(&chan->lock);
665 /* Close pipes if appropriate */
666 if ((fd = chan->alertpipe[0]) > -1)
668 if ((fd = chan->alertpipe[1]) > -1)
670 if ((fd = chan->timingfd) > -1)
680 /* loop over the variables list, freeing all data and deleting list items */
681 /* no need to lock the list, as the channel is already locked */
683 while (!AST_LIST_EMPTY(headp)) { /* List Deletion. */
684 vardata = AST_LIST_REMOVE_HEAD(headp, entries);
685 /* printf("deleting var %s=%s\n",ast_var_name(vardata),ast_var_value(vardata)); */
686 ast_var_delete(vardata);
690 ast_mutex_unlock(&chlock);
692 ast_device_state_changed(name);
695 static void ast_spy_detach(struct ast_channel *chan)
697 struct ast_channel_spy *chanspy;
701 for (chanspy = chan->spiers; chanspy; chanspy = chanspy->next) {
702 if (chanspy->status == CHANSPY_RUNNING) {
703 chanspy->status = CHANSPY_DONE;
707 /* signal all the spys to get lost and allow them time to unhook themselves
708 god help us if they don't......
710 while (chan->spiers && to >= 0) {
711 ast_safe_sleep(chan, sleepms);
718 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
721 struct ast_frame f = { AST_FRAME_NULL };
723 ast_log(LOG_DEBUG, "Soft-Hanging up channel '%s'\n", chan->name);
724 /* Inform channel driver that we need to be hung up, if it cares */
725 chan->_softhangup |= cause;
726 ast_queue_frame(chan, &f);
727 /* Interrupt any poll call or such */
728 if (ast_test_flag(chan, AST_FLAG_BLOCKING))
729 pthread_kill(chan->blocker, SIGURG);
733 int ast_softhangup(struct ast_channel *chan, int cause)
736 ast_mutex_lock(&chan->lock);
737 res = ast_softhangup_nolock(chan, cause);
738 ast_mutex_unlock(&chan->lock);
742 static void ast_queue_spy_frame(struct ast_channel_spy *spy, struct ast_frame *f, int pos)
744 struct ast_frame *tmpf = NULL;
747 ast_mutex_lock(&spy->lock);
748 for (tmpf=spy->queue[pos]; tmpf && tmpf->next; tmpf=tmpf->next) {
752 struct ast_frame *freef, *headf;
754 ast_log(LOG_ERROR, "Too Many frames queued at once, flushing cache.\n");
755 headf = spy->queue[pos];
756 /* deref the queue right away so it looks empty */
757 spy->queue[pos] = NULL;
759 /* free the wasted frames */
765 ast_mutex_unlock(&spy->lock);
770 tmpf->next = ast_frdup(f);
772 spy->queue[pos] = ast_frdup(f);
775 ast_mutex_unlock(&spy->lock);
778 static void free_translation(struct ast_channel *clone)
780 if (clone->writetrans)
781 ast_translator_free_path(clone->writetrans);
782 if (clone->readtrans)
783 ast_translator_free_path(clone->readtrans);
784 clone->writetrans = NULL;
785 clone->readtrans = NULL;
786 clone->rawwriteformat = clone->nativeformats;
787 clone->rawreadformat = clone->nativeformats;
790 int ast_hangup(struct ast_channel *chan)
793 /* Don't actually hang up a channel that will masquerade as someone else, or
794 if someone is going to masquerade as us */
795 ast_mutex_lock(&chan->lock);
797 /* get rid of spies */
798 ast_spy_detach(chan);
801 if (ast_do_masquerade(chan))
802 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
806 ast_log(LOG_WARNING, "%s getting hung up, but someone is trying to masq into us?!?\n", chan->name);
807 ast_mutex_unlock(&chan->lock);
810 /* If this channel is one which will be masqueraded into something,
811 mark it as a zombie already, so we know to free it later */
813 ast_set_flag(chan, AST_FLAG_ZOMBIE);
814 ast_mutex_unlock(&chan->lock);
817 free_translation(chan);
819 ast_closestream(chan->stream);
821 ast_closestream(chan->vstream);
823 sched_context_destroy(chan->sched);
824 /* Clear any tone stuff remaining */
825 if (chan->generatordata)
826 chan->generator->release(chan, chan->generatordata);
827 chan->generatordata = NULL;
828 chan->generator = NULL;
830 /* End the CDR if it hasn't already */
831 ast_cdr_end(chan->cdr);
832 /* Post and Free the CDR */
833 ast_cdr_post(chan->cdr);
834 ast_cdr_free(chan->cdr);
836 if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
837 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
838 "is blocked by thread %ld in procedure %s! Expect a failure\n",
839 (long)pthread_self(), chan->name, (long)chan->blocker, chan->blockproc);
842 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE)) {
844 ast_log(LOG_DEBUG, "Hanging up channel '%s'\n", chan->name);
845 if (chan->tech->hangup)
846 res = chan->tech->hangup(chan);
849 ast_log(LOG_DEBUG, "Hanging up zombie '%s'\n", chan->name);
851 ast_mutex_unlock(&chan->lock);
852 manager_event(EVENT_FLAG_CALL, "Hangup",
856 chan->name, chan->uniqueid, chan->hangupcause);
857 ast_channel_free(chan);
861 void ast_channel_unregister(const struct ast_channel_tech *tech)
863 struct chanlist *chan, *last=NULL;
866 ast_log(LOG_DEBUG, "Unregistering channel type '%s'\n", tech->type);
868 ast_mutex_lock(&chlock);
872 if (chan->tech == tech) {
874 last->next = chan->next;
876 backends = backends->next;
878 ast_mutex_unlock(&chlock);
880 if (option_verbose > 1)
881 ast_verbose( VERBOSE_PREFIX_2 "Unregistered channel type '%s'\n", tech->type);
889 ast_mutex_unlock(&chlock);
892 int ast_answer(struct ast_channel *chan)
895 ast_mutex_lock(&chan->lock);
896 /* Stop if we're a zombie or need a soft hangup */
897 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
898 ast_mutex_unlock(&chan->lock);
901 switch(chan->_state) {
902 case AST_STATE_RINGING:
904 if (chan->tech->answer)
905 res = chan->tech->answer(chan);
906 ast_setstate(chan, AST_STATE_UP);
908 ast_cdr_answer(chan->cdr);
909 ast_mutex_unlock(&chan->lock);
914 ast_cdr_answer(chan->cdr);
917 ast_mutex_unlock(&chan->lock);
923 void ast_deactivate_generator(struct ast_channel *chan)
925 ast_mutex_lock(&chan->lock);
926 if (chan->generatordata) {
927 if (chan->generator && chan->generator->release)
928 chan->generator->release(chan, chan->generatordata);
929 chan->generatordata = NULL;
930 chan->generator = NULL;
931 ast_clear_flag(chan, AST_FLAG_WRITE_INT);
932 ast_settimeout(chan, 0, NULL, NULL);
934 ast_mutex_unlock(&chan->lock);
937 static int generator_force(void *data)
939 /* Called if generator doesn't have data */
942 int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples);
943 struct ast_channel *chan = data;
944 tmp = chan->generatordata;
945 chan->generatordata = NULL;
946 generate = chan->generator->generate;
947 res = generate(chan, tmp, 0, 160);
948 chan->generatordata = tmp;
950 ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
951 ast_deactivate_generator(chan);
956 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
959 ast_mutex_lock(&chan->lock);
960 if (chan->generatordata) {
961 if (chan->generator && chan->generator->release)
962 chan->generator->release(chan, chan->generatordata);
963 chan->generatordata = NULL;
966 if ((chan->generatordata = gen->alloc(chan, params))) {
967 ast_settimeout(chan, 160, generator_force, chan);
968 chan->generator = gen;
972 ast_mutex_unlock(&chan->lock);
976 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
978 /* Wait for x amount of time on a file descriptor to have input. */
979 struct timeval start, now;
986 pfds = alloca(sizeof(struct pollfd) * n);
988 ast_log(LOG_ERROR, "Out of memory\n");
992 gettimeofday(&start, NULL);
997 pfds[y].events = POLLIN | POLLPRI;
1001 res = poll(pfds, y, *ms);
1003 /* Simulate a timeout if we were interrupted */
1013 if ((res = ast_fdisset(pfds, fds[x], y, &spoint))) {
1026 gettimeofday(&now, NULL);
1027 passed = (now.tv_sec - start.tv_sec) * 1000;
1028 passed += (now.tv_usec - start.tv_usec) / 1000;
1037 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
1038 int *exception, int *outfd, int *ms)
1040 /* Wait for x amount of time on a file descriptor to have input. */
1041 struct timeval start, end;
1042 struct pollfd *pfds;
1048 long whentohangup = 0, havewhen = 0, diff;
1049 struct ast_channel *winner = NULL;
1051 pfds = alloca(sizeof(struct pollfd) * (n * AST_MAX_FDS + nfds));
1053 ast_log(LOG_ERROR, "Out of memory\n");
1063 /* Perform any pending masquerades */
1065 ast_mutex_lock(&c[x]->lock);
1066 if (c[x]->whentohangup) {
1069 diff = c[x]->whentohangup - now;
1070 if (!havewhen || (diff < whentohangup)) {
1072 whentohangup = diff;
1076 if (ast_do_masquerade(c[x])) {
1077 ast_log(LOG_WARNING, "Masquerade failed\n");
1079 ast_mutex_unlock(&c[x]->lock);
1083 ast_mutex_unlock(&c[x]->lock);
1089 if ((*ms < 0) || (whentohangup * 1000 < *ms)) {
1090 rms = whentohangup * 1000;
1095 for (y=0;y<AST_MAX_FDS;y++) {
1096 if (c[x]->fds[y] > -1) {
1097 pfds[max].fd = c[x]->fds[y];
1098 pfds[max].events = POLLIN | POLLPRI;
1102 CHECK_BLOCKING(c[x]);
1104 for (x=0;x<nfds; x++) {
1106 pfds[max].fd = fds[x];
1107 pfds[max].events = POLLIN | POLLPRI;
1112 gettimeofday(&start, NULL);
1113 res = poll(pfds, max, rms);
1116 ast_clear_flag(c[x], AST_FLAG_BLOCKING);
1117 /* Simulate a timeout if we were interrupted */
1121 /* Just an interrupt */
1133 ast_clear_flag(c[x], AST_FLAG_BLOCKING);
1134 if (havewhen && c[x]->whentohangup && (now > c[x]->whentohangup)) {
1135 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1139 for (y=0;y<AST_MAX_FDS;y++) {
1140 if (c[x]->fds[y] > -1) {
1141 if ((res = ast_fdisset(pfds, c[x]->fds[y], max, &spoint))) {
1143 ast_set_flag(c[x], AST_FLAG_EXCEPTION);
1145 ast_clear_flag(c[x], AST_FLAG_EXCEPTION);
1152 for (x=0;x<nfds;x++) {
1154 if ((res = ast_fdisset(pfds, fds[x], max, &spoint))) {
1169 gettimeofday(&end, NULL);
1170 diff = (end.tv_sec - start.tv_sec) * 1000;
1171 diff += (end.tv_usec - start.tv_usec) / 1000;
1180 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
1182 return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
1185 int ast_waitfor(struct ast_channel *c, int ms)
1187 struct ast_channel *chan;
1189 chan = ast_waitfor_n(&c, 1, &ms);
1199 char ast_waitfordigit(struct ast_channel *c, int ms)
1201 /* XXX Should I be merged with waitfordigit_full XXX */
1202 struct ast_frame *f;
1204 /* Stop if we're a zombie or need a soft hangup */
1205 if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
1207 /* Wait for a digit, no more than ms milliseconds total. */
1208 while(ms && !result) {
1209 ms = ast_waitfor(c, ms);
1210 if (ms < 0) /* Error */
1213 /* Read something */
1216 if (f->frametype == AST_FRAME_DTMF)
1217 result = f->subclass;
1226 int ast_settimeout(struct ast_channel *c, int samples, int (*func)(void *data), void *data)
1229 #ifdef ZAPTEL_OPTIMIZATIONS
1230 if (c->timingfd > -1) {
1235 ast_log(LOG_DEBUG, "Scheduling timer at %d sample intervals\n", samples);
1236 res = ioctl(c->timingfd, ZT_TIMERCONFIG, &samples);
1237 c->timingfunc = func;
1238 c->timingdata = data;
1243 char ast_waitfordigit_full(struct ast_channel *c, int ms, int audiofd, int cmdfd)
1245 struct ast_frame *f;
1246 struct ast_channel *rchan;
1249 /* Stop if we're a zombie or need a soft hangup */
1250 if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
1252 /* Wait for a digit, no more than ms milliseconds total. */
1255 rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
1256 if ((!rchan) && (outfd < 0) && (ms)) {
1257 if (errno == 0 || errno == EINTR)
1259 ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
1261 } else if (outfd > -1) {
1262 /* The FD we were watching has something waiting */
1270 switch(f->frametype) {
1271 case AST_FRAME_DTMF:
1275 case AST_FRAME_CONTROL:
1276 switch(f->subclass) {
1277 case AST_CONTROL_HANGUP:
1280 case AST_CONTROL_RINGING:
1281 case AST_CONTROL_ANSWER:
1285 ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", f->subclass);
1287 case AST_FRAME_VOICE:
1288 /* Write audio if appropriate */
1290 write(audiofd, f->data, f->datalen);
1296 return 0; /* Time is up */
1299 struct ast_frame *ast_read(struct ast_channel *chan)
1301 struct ast_frame *f = NULL;
1304 #ifdef ZAPTEL_OPTIMIZATIONS
1305 int (*func)(void *);
1309 static struct ast_frame null_frame =
1314 ast_mutex_lock(&chan->lock);
1316 if (ast_do_masquerade(chan)) {
1317 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1321 ast_mutex_unlock(&chan->lock);
1325 /* Stop if we're a zombie or need a soft hangup */
1326 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
1327 if (chan->generator)
1328 ast_deactivate_generator(chan);
1329 ast_mutex_unlock(&chan->lock);
1332 prestate = chan->_state;
1334 if (!ast_test_flag(chan, AST_FLAG_DEFER_DTMF) && !ast_strlen_zero(chan->dtmfq)) {
1335 /* We have DTMF that has been deferred. Return it now */
1336 chan->dtmff.frametype = AST_FRAME_DTMF;
1337 chan->dtmff.subclass = chan->dtmfq[0];
1338 /* Drop first digit */
1339 memmove(chan->dtmfq, chan->dtmfq + 1, sizeof(chan->dtmfq) - 1);
1340 ast_mutex_unlock(&chan->lock);
1341 return &chan->dtmff;
1344 /* Read and ignore anything on the alertpipe, but read only
1345 one sizeof(blah) per frame that we send from it */
1346 if (chan->alertpipe[0] > -1) {
1347 read(chan->alertpipe[0], &blah, sizeof(blah));
1349 #ifdef ZAPTEL_OPTIMIZATIONS
1350 if ((chan->timingfd > -1) && (chan->fdno == AST_MAX_FDS - 2) && ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
1351 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
1353 /* IF we can't get event, assume it's an expired as-per the old interface */
1354 res = ioctl(chan->timingfd, ZT_GETEVENT, &blah);
1356 blah = ZT_EVENT_TIMER_EXPIRED;
1358 if (blah == ZT_EVENT_TIMER_PING) {
1360 ast_log(LOG_NOTICE, "Oooh, there's a PING!\n");
1362 if (!chan->readq || !chan->readq->next) {
1363 /* Acknowledge PONG unless we need it again */
1365 ast_log(LOG_NOTICE, "Sending a PONG!\n");
1367 if (ioctl(chan->timingfd, ZT_TIMERPONG, &blah)) {
1368 ast_log(LOG_WARNING, "Failed to pong timer on '%s': %s\n", chan->name, strerror(errno));
1371 } else if (blah == ZT_EVENT_TIMER_EXPIRED) {
1372 ioctl(chan->timingfd, ZT_TIMERACK, &blah);
1373 func = chan->timingfunc;
1374 data = chan->timingdata;
1375 ast_mutex_unlock(&chan->lock);
1378 ast_log(LOG_DEBUG, "Calling private function\n");
1383 ast_mutex_lock(&chan->lock);
1384 ioctl(chan->timingfd, ZT_TIMERCONFIG, &blah);
1385 chan->timingdata = NULL;
1386 ast_mutex_unlock(&chan->lock);
1391 ast_log(LOG_NOTICE, "No/unknown event '%d' on timer for '%s'?\n", blah, chan->name);
1394 /* Check for pending read queue */
1397 chan->readq = f->next;
1398 /* Interpret hangup and return NULL */
1399 if ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_HANGUP)) {
1404 chan->blocker = pthread_self();
1405 if (ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
1406 if (chan->tech->exception)
1407 f = chan->tech->exception(chan);
1409 ast_log(LOG_WARNING, "Exception flag set on '%s', but no exception handler\n", chan->name);
1412 /* Clear the exception flag */
1413 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
1415 if (chan->tech->read)
1416 f = chan->tech->read(chan);
1418 ast_log(LOG_WARNING, "No read routine on channel %s\n", chan->name);
1422 if (f && (f->frametype == AST_FRAME_VOICE)) {
1423 if (!(f->subclass & chan->nativeformats)) {
1424 /* This frame can't be from the current native formats -- drop it on the
1426 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));
1431 struct ast_channel_spy *spying;
1432 for (spying = chan->spiers; spying; spying=spying->next) {
1433 ast_queue_spy_frame(spying, f, 0);
1436 if (chan->monitor && chan->monitor->read_stream ) {
1437 #ifndef MONITOR_CONSTANT_DELAY
1438 int jump = chan->outsmpl - chan->insmpl - 2 * f->samples;
1440 if (ast_seekstream(chan->monitor->read_stream, jump + f->samples, SEEK_FORCECUR) == -1)
1441 ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
1442 chan->insmpl += jump + 2 * f->samples;
1444 chan->insmpl+= f->samples;
1446 int jump = chan->outsmpl - chan->insmpl;
1447 if (jump - MONITOR_DELAY >= 0) {
1448 if (ast_seekstream(chan->monitor->read_stream, jump - f->samples, SEEK_FORCECUR) == -1)
1449 ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
1450 chan->insmpl += jump;
1452 chan->insmpl += f->samples;
1454 if (ast_writestream(chan->monitor->read_stream, f) < 0)
1455 ast_log(LOG_WARNING, "Failed to write data to channel monitor read stream\n");
1457 if (chan->readtrans) {
1458 f = ast_translate(chan->readtrans, f, 1);
1465 /* Make sure we always return NULL in the future */
1467 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1468 if (chan->generator)
1469 ast_deactivate_generator(chan);
1470 /* End the CDR if appropriate */
1472 ast_cdr_end(chan->cdr);
1473 } else if (ast_test_flag(chan, AST_FLAG_DEFER_DTMF) && f->frametype == AST_FRAME_DTMF) {
1474 if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2)
1475 chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
1477 ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
1479 } else if ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_ANSWER)) {
1480 if (prestate == AST_STATE_UP) {
1481 ast_log(LOG_DEBUG, "Dropping duplicate answer!\n");
1484 /* Answer the CDR */
1485 ast_setstate(chan, AST_STATE_UP);
1486 ast_cdr_answer(chan->cdr);
1489 /* Run any generator sitting on the line */
1490 if (f && (f->frametype == AST_FRAME_VOICE) && chan->generatordata) {
1491 /* Mask generator data temporarily and apply. If there is a timing function, it
1492 will be calling the generator instead */
1495 int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples);
1496 if (chan->timingfunc) {
1497 ast_log(LOG_DEBUG, "Generator got voice, switching to phase locked mode\n");
1498 ast_settimeout(chan, 0, NULL, NULL);
1500 tmp = chan->generatordata;
1501 chan->generatordata = NULL;
1502 generate = chan->generator->generate;
1503 res = generate(chan, tmp, f->datalen, f->samples);
1504 chan->generatordata = tmp;
1506 ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
1507 ast_deactivate_generator(chan);
1509 } else if (f && (f->frametype == AST_FRAME_CNG)) {
1510 if (chan->generator && !chan->timingfunc && (chan->timingfd > -1)) {
1511 ast_log(LOG_DEBUG, "Generator got CNG, switching to zap timed mode\n");
1512 ast_settimeout(chan, 160, generator_force, chan);
1515 if (chan->fin & 0x80000000)
1516 ast_frame_dump(chan->name, f, "<<");
1517 if ((chan->fin & 0x7fffffff) == 0x7fffffff)
1518 chan->fin &= 0x80000000;
1521 ast_mutex_unlock(&chan->lock);
1525 int ast_indicate(struct ast_channel *chan, int condition)
1528 /* Stop if we're a zombie or need a soft hangup */
1529 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
1531 ast_mutex_lock(&chan->lock);
1532 if (chan->tech->indicate)
1533 res = chan->tech->indicate(chan, condition);
1534 ast_mutex_unlock(&chan->lock);
1535 if (!chan->tech->indicate || res) {
1537 * Device does not support (that) indication, lets fake
1538 * it by doing our own tone generation. (PM2002)
1540 if (condition >= 0) {
1541 const struct tone_zone_sound *ts = NULL;
1542 switch (condition) {
1543 case AST_CONTROL_RINGING:
1544 ts = ast_get_indication_tone(chan->zone, "ring");
1546 case AST_CONTROL_BUSY:
1547 ts = ast_get_indication_tone(chan->zone, "busy");
1549 case AST_CONTROL_CONGESTION:
1550 ts = ast_get_indication_tone(chan->zone, "congestion");
1553 if (ts && ts->data[0]) {
1554 ast_log(LOG_DEBUG, "Driver for channel '%s' does not support indication %d, emulating it\n", chan->name, condition);
1555 ast_playtones_start(chan,0,ts->data, 1);
1557 } else if (condition == AST_CONTROL_PROGRESS) {
1558 /* ast_playtones_stop(chan); */
1559 } else if (condition == AST_CONTROL_PROCEEDING) {
1560 /* Do nothing, really */
1561 } else if (condition == AST_CONTROL_HOLD) {
1562 /* Do nothing.... */
1563 } else if (condition == AST_CONTROL_UNHOLD) {
1564 /* Do nothing.... */
1567 ast_log(LOG_WARNING, "Unable to handle indication %d for '%s'\n", condition, chan->name);
1571 else ast_playtones_stop(chan);
1576 int ast_recvchar(struct ast_channel *chan, int timeout)
1579 struct ast_frame *f;
1584 if (ast_check_hangup(chan)) return -1;
1585 res = ast_waitfor(chan,ourto);
1586 if (res <= 0) /* if timeout */
1592 if (f == NULL) return -1; /* if hangup */
1593 if ((f->frametype == AST_FRAME_CONTROL) &&
1594 (f->subclass == AST_CONTROL_HANGUP)) return -1; /* if hangup */
1595 if (f->frametype == AST_FRAME_TEXT) /* if a text frame */
1597 c = *((char *)f->data); /* get the data */
1605 int ast_sendtext(struct ast_channel *chan, char *text)
1608 /* Stop if we're a zombie or need a soft hangup */
1609 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
1611 CHECK_BLOCKING(chan);
1612 if (chan->tech->send_text)
1613 res = chan->tech->send_text(chan, text);
1614 ast_clear_flag(chan, AST_FLAG_BLOCKING);
1618 static int do_senddigit(struct ast_channel *chan, char digit)
1622 if (chan->tech->send_digit)
1623 res = chan->tech->send_digit(chan, digit);
1624 if (!chan->tech->send_digit || res) {
1626 * Device does not support DTMF tones, lets fake
1627 * it by doing our own generation. (PM2002)
1629 static const char* dtmf_tones[] = {
1630 "!941+1336/100,!0/100", /* 0 */
1631 "!697+1209/100,!0/100", /* 1 */
1632 "!697+1336/100,!0/100", /* 2 */
1633 "!697+1477/100,!0/100", /* 3 */
1634 "!770+1209/100,!0/100", /* 4 */
1635 "!770+1336/100,!0/100", /* 5 */
1636 "!770+1477/100,!0/100", /* 6 */
1637 "!852+1209/100,!0/100", /* 7 */
1638 "!852+1336/100,!0/100", /* 8 */
1639 "!852+1477/100,!0/100", /* 9 */
1640 "!697+1633/100,!0/100", /* A */
1641 "!770+1633/100,!0/100", /* B */
1642 "!852+1633/100,!0/100", /* C */
1643 "!941+1633/100,!0/100", /* D */
1644 "!941+1209/100,!0/100", /* * */
1645 "!941+1477/100,!0/100" }; /* # */
1646 if (digit >= '0' && digit <='9')
1647 ast_playtones_start(chan,0,dtmf_tones[digit-'0'], 0);
1648 else if (digit >= 'A' && digit <= 'D')
1649 ast_playtones_start(chan,0,dtmf_tones[digit-'A'+10], 0);
1650 else if (digit == '*')
1651 ast_playtones_start(chan,0,dtmf_tones[14], 0);
1652 else if (digit == '#')
1653 ast_playtones_start(chan,0,dtmf_tones[15], 0);
1656 ast_log(LOG_DEBUG, "Unable to handle DTMF tone '%c' for '%s'\n", digit, chan->name);
1662 int ast_senddigit(struct ast_channel *chan, char digit)
1664 return do_senddigit(chan, digit);
1667 int ast_prod(struct ast_channel *chan)
1669 struct ast_frame a = { AST_FRAME_VOICE };
1671 /* Send an empty audio frame to get things moving */
1672 if (chan->_state != AST_STATE_UP) {
1673 ast_log(LOG_DEBUG, "Prodding channel '%s'\n", chan->name);
1674 a.subclass = chan->rawwriteformat;
1675 a.data = nothing + AST_FRIENDLY_OFFSET;
1677 if (ast_write(chan, &a))
1678 ast_log(LOG_WARNING, "Prodding channel '%s' failed\n", chan->name);
1683 int ast_write_video(struct ast_channel *chan, struct ast_frame *fr)
1686 if (!chan->tech->write_video)
1688 res = ast_write(chan, fr);
1694 int ast_write(struct ast_channel *chan, struct ast_frame *fr)
1697 struct ast_frame *f = NULL;
1698 /* Stop if we're a zombie or need a soft hangup */
1699 ast_mutex_lock(&chan->lock);
1700 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
1701 ast_mutex_unlock(&chan->lock);
1704 /* Handle any pending masquerades */
1706 if (ast_do_masquerade(chan)) {
1707 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1708 ast_mutex_unlock(&chan->lock);
1713 ast_mutex_unlock(&chan->lock);
1716 if (chan->generatordata) {
1717 if (ast_test_flag(chan, AST_FLAG_WRITE_INT))
1718 ast_deactivate_generator(chan);
1720 ast_mutex_unlock(&chan->lock);
1724 if (chan->fout & 0x80000000)
1725 ast_frame_dump(chan->name, fr, ">>");
1726 CHECK_BLOCKING(chan);
1727 switch(fr->frametype) {
1728 case AST_FRAME_CONTROL:
1729 /* XXX Interpret control frames XXX */
1730 ast_log(LOG_WARNING, "Don't know how to handle control frames yet\n");
1732 case AST_FRAME_DTMF:
1733 ast_clear_flag(chan, AST_FLAG_BLOCKING);
1734 ast_mutex_unlock(&chan->lock);
1735 res = do_senddigit(chan,fr->subclass);
1736 ast_mutex_lock(&chan->lock);
1737 CHECK_BLOCKING(chan);
1739 case AST_FRAME_TEXT:
1740 if (chan->tech->send_text)
1741 res = chan->tech->send_text(chan, (char *) fr->data);
1745 case AST_FRAME_HTML:
1746 if (chan->tech->send_html)
1747 res = chan->tech->send_html(chan, fr->subclass, (char *) fr->data, fr->datalen);
1751 case AST_FRAME_VIDEO:
1752 /* XXX Handle translation of video codecs one day XXX */
1753 if (chan->tech->write_video)
1754 res = chan->tech->write_video(chan, fr);
1759 if (chan->tech->write) {
1760 if (chan->writetrans) {
1761 f = ast_translate(chan->writetrans, fr, 0);
1765 res = chan->tech->write(chan, f);
1767 if (f->frametype == AST_FRAME_VOICE && chan->spiers) {
1768 struct ast_channel_spy *spying;
1769 for (spying = chan->spiers; spying; spying=spying->next) {
1770 ast_queue_spy_frame(spying, f, 1);
1774 if( chan->monitor &&
1775 chan->monitor->write_stream &&
1776 f && ( f->frametype == AST_FRAME_VOICE ) ) {
1777 #ifndef MONITOR_CONSTANT_DELAY
1778 int jump = chan->insmpl - chan->outsmpl - 2 * f->samples;
1780 if (ast_seekstream(chan->monitor->write_stream, jump + f->samples, SEEK_FORCECUR) == -1)
1781 ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
1782 chan->outsmpl += jump + 2 * f->samples;
1784 chan->outsmpl += f->samples;
1786 int jump = chan->insmpl - chan->outsmpl;
1787 if (jump - MONITOR_DELAY >= 0) {
1788 if (ast_seekstream(chan->monitor->write_stream, jump - f->samples, SEEK_FORCECUR) == -1)
1789 ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
1790 chan->outsmpl += jump;
1792 chan->outsmpl += f->samples;
1794 if (ast_writestream(chan->monitor->write_stream, f) < 0)
1795 ast_log(LOG_WARNING, "Failed to write data to channel monitor write stream\n");
1803 ast_clear_flag(chan, AST_FLAG_BLOCKING);
1804 /* Consider a write failure to force a soft hangup */
1806 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1808 if ((chan->fout & 0x7fffffff) == 0x7fffffff)
1809 chan->fout &= 0x80000000;
1814 ast_mutex_unlock(&chan->lock);
1818 static int set_format(struct ast_channel *chan, int fmt, int *rawformat, int *format,
1819 struct ast_trans_pvt **trans, const int direction)
1824 native = chan->nativeformats;
1825 /* Find a translation path from the native format to one of the desired formats */
1828 res = ast_translator_best_choice(&fmt, &native);
1831 res = ast_translator_best_choice(&native, &fmt);
1834 ast_log(LOG_NOTICE, "Unable to find a path from %s to %s\n",
1835 ast_getformatname(native), ast_getformatname(fmt));
1839 /* Now we have a good choice for both. */
1840 ast_mutex_lock(&chan->lock);
1841 *rawformat = native;
1842 /* User perspective is fmt */
1844 /* Free any read translation we have right now */
1846 ast_translator_free_path(*trans);
1847 /* Build a translation path from the raw format to the desired format */
1850 *trans = ast_translator_build_path(*format, *rawformat);
1853 *trans = ast_translator_build_path(*rawformat, *format);
1854 ast_mutex_unlock(&chan->lock);
1856 ast_log(LOG_DEBUG, "Set channel %s to %s format %s\n", chan->name,
1857 direction ? "write" : "read", ast_getformatname(fmt));
1861 int ast_set_read_format(struct ast_channel *chan, int fmt)
1863 return set_format(chan, fmt, &chan->rawreadformat, &chan->readformat,
1864 &chan->readtrans, 0);
1867 int ast_set_write_format(struct ast_channel *chan, int fmt)
1869 return set_format(chan, fmt, &chan->rawwriteformat, &chan->writeformat,
1870 &chan->writetrans, 1);
1873 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)
1877 struct ast_channel *chan;
1878 struct ast_frame *f;
1881 chan = ast_request(type, format, data, &cause);
1887 variable = ast_strdupa(oh->variable);
1891 /* FIXME replace this call with strsep NOT*/
1892 while( (var = strtok_r(NULL, "|", &tmp)) ) {
1893 pbx_builtin_setvar( chan, var );
1895 ast_set_callerid(chan, oh->cid_num, oh->cid_name, oh->cid_num);
1896 if (oh->account && *oh->account)
1897 ast_cdr_setaccount(chan, oh->account);
1899 ast_set_callerid(chan, cid_num, cid_name, cid_num);
1901 if (!ast_call(chan, data, 0)) {
1902 while(timeout && (chan->_state != AST_STATE_UP)) {
1903 res = ast_waitfor(chan, timeout);
1905 /* Something not cool, or timed out */
1908 /* If done, break out */
1915 state = AST_CONTROL_HANGUP;
1919 if (f->frametype == AST_FRAME_CONTROL) {
1920 if (f->subclass == AST_CONTROL_RINGING)
1921 state = AST_CONTROL_RINGING;
1922 else if ((f->subclass == AST_CONTROL_BUSY) || (f->subclass == AST_CONTROL_CONGESTION)) {
1923 state = f->subclass;
1926 } else if (f->subclass == AST_CONTROL_ANSWER) {
1927 state = f->subclass;
1930 } else if (f->subclass == AST_CONTROL_PROGRESS) {
1932 } else if (f->subclass == -1) {
1933 /* Ignore -- just stopping indications */
1935 ast_log(LOG_NOTICE, "Don't know what to do with control frame %d\n", f->subclass);
1941 ast_log(LOG_NOTICE, "Unable to call channel %s/%s\n", type, (char *)data);
1943 ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
1945 case AST_CAUSE_BUSY:
1946 state = AST_CONTROL_BUSY;
1948 case AST_CAUSE_CONGESTION:
1949 state = AST_CONTROL_CONGESTION;
1956 if (oh->context && *oh->context)
1957 strncpy(chan->context, oh->context, sizeof(chan->context) - 1);
1958 if (oh->exten && *oh->exten)
1959 strncpy(chan->exten, oh->exten, sizeof(chan->exten) - 1);
1960 chan->priority = oh->priority;
1962 if (chan->_state == AST_STATE_UP)
1963 state = AST_CONTROL_ANSWER;
1967 if (chan && res <= 0) {
1969 chan->cdr = ast_cdr_alloc();
1971 ast_cdr_init(chan->cdr, chan);
1975 snprintf(tmp, 256, "%s/%s", type, (char *)data);
1976 ast_cdr_setapp(chan->cdr,"Dial",tmp);
1977 ast_cdr_update(chan);
1978 ast_cdr_start(chan->cdr);
1979 ast_cdr_end(chan->cdr);
1980 /* If the cause wasn't handled properly */
1981 if (ast_cdr_disposition(chan->cdr,chan->hangupcause))
1982 ast_cdr_failed(chan->cdr);
1984 ast_log(LOG_WARNING, "Unable to create Call Detail Record\n");
1991 struct ast_channel *ast_request_and_dial(const char *type, int format, void *data, int timeout, int *outstate, const char *cidnum, const char *cidname)
1993 return __ast_request_and_dial(type, format, data, timeout, outstate, cidnum, cidname, NULL);
1996 struct ast_channel *ast_request(const char *type, int format, void *data, int *cause)
1998 struct chanlist *chan;
1999 struct ast_channel *c = NULL;
2006 *cause = AST_CAUSE_NOTDEFINED;
2007 if (ast_mutex_lock(&chlock)) {
2008 ast_log(LOG_WARNING, "Unable to lock channel list\n");
2013 if (!strcasecmp(type, chan->tech->type)) {
2014 capabilities = chan->tech->capabilities;
2016 res = ast_translator_best_choice(&fmt, &capabilities);
2018 ast_log(LOG_WARNING, "No translator path exists for channel type %s (native %d) to %d\n", type, chan->tech->capabilities, format);
2019 ast_mutex_unlock(&chlock);
2022 ast_mutex_unlock(&chlock);
2023 if (chan->tech->requester)
2024 c = chan->tech->requester(type, capabilities, data, cause);
2026 if (c->_state == AST_STATE_DOWN) {
2027 manager_event(EVENT_FLAG_CALL, "Newchannel",
2031 "CallerIDName: %s\r\n"
2033 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);
2041 ast_log(LOG_WARNING, "No channel type registered for '%s'\n", type);
2042 *cause = AST_CAUSE_NOSUCHDRIVER;
2044 ast_mutex_unlock(&chlock);
2048 int ast_parse_device_state(char *device)
2050 char name[AST_CHANNEL_NAME] = "";
2052 struct ast_channel *chan;
2054 chan = ast_channel_walk_locked(NULL);
2056 strncpy(name, chan->name, sizeof(name)-1);
2057 ast_mutex_unlock(&chan->lock);
2058 cut = strchr(name,'-');
2061 if (!strcmp(name, device))
2062 return AST_DEVICE_INUSE;
2063 chan = ast_channel_walk_locked(chan);
2065 return AST_DEVICE_UNKNOWN;
2068 int ast_device_state(char *device)
2070 char tech[AST_MAX_EXTENSION] = "";
2072 struct chanlist *chanls;
2075 strncpy(tech, device, sizeof(tech)-1);
2076 number = strchr(tech, '/');
2078 return AST_DEVICE_INVALID;
2083 if (ast_mutex_lock(&chlock)) {
2084 ast_log(LOG_WARNING, "Unable to lock channel list\n");
2089 if (!strcasecmp(tech, chanls->tech->type)) {
2090 ast_mutex_unlock(&chlock);
2091 if (!chanls->tech->devicestate)
2092 return ast_parse_device_state(device);
2094 res = chanls->tech->devicestate(number);
2095 if (res == AST_DEVICE_UNKNOWN)
2096 return ast_parse_device_state(device);
2101 chanls = chanls->next;
2103 ast_mutex_unlock(&chlock);
2104 return AST_DEVICE_INVALID;
2107 int ast_call(struct ast_channel *chan, char *addr, int timeout)
2109 /* Place an outgoing call, but don't wait any longer than timeout ms before returning.
2110 If the remote end does not answer within the timeout, then do NOT hang up, but
2113 /* Stop if we're a zombie or need a soft hangup */
2114 ast_mutex_lock(&chan->lock);
2115 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan))
2116 if (chan->tech->call)
2117 res = chan->tech->call(chan, addr, timeout);
2118 ast_mutex_unlock(&chan->lock);
2122 int ast_transfer(struct ast_channel *chan, char *dest)
2124 /* Place an outgoing call, but don't wait any longer than timeout ms before returning.
2125 If the remote end does not answer within the timeout, then do NOT hang up, but
2128 /* Stop if we're a zombie or need a soft hangup */
2129 ast_mutex_lock(&chan->lock);
2130 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
2131 if (chan->tech->transfer) {
2132 res = chan->tech->transfer(chan, dest);
2138 ast_mutex_unlock(&chan->lock);
2142 int ast_readstring(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders)
2147 /* XXX Merge with full version? XXX */
2148 /* Stop if we're a zombie or need a soft hangup */
2149 if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
2155 d = ast_waitstream(c, AST_DIGIT_ANY);
2159 d = ast_waitfordigit(c, to);
2161 d = ast_waitfordigit(c, to);
2169 if (!strchr(enders, d))
2171 if (strchr(enders, d) || (pos >= len)) {
2181 int ast_readstring_full(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders, int audiofd, int ctrlfd)
2186 /* Stop if we're a zombie or need a soft hangup */
2187 if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
2193 d = ast_waitstream_full(c, AST_DIGIT_ANY, audiofd, ctrlfd);
2197 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
2199 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
2211 if (!strchr(enders, d))
2213 if (strchr(enders, d) || (pos >= len)) {
2223 int ast_channel_supports_html(struct ast_channel *chan)
2225 if (chan->tech->send_html)
2230 int ast_channel_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
2232 if (chan->tech->send_html)
2233 return chan->tech->send_html(chan, subclass, data, datalen);
2237 int ast_channel_sendurl(struct ast_channel *chan, const char *url)
2239 if (chan->tech->send_html)
2240 return chan->tech->send_html(chan, AST_HTML_URL, url, strlen(url) + 1);
2244 int ast_channel_make_compatible(struct ast_channel *chan, struct ast_channel *peer)
2249 /* Set up translation from the chan to the peer */
2250 src = chan->nativeformats;
2251 dst = peer->nativeformats;
2252 if (ast_translator_best_choice(&dst, &src) < 0) {
2253 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", chan->name, src, peer->name, dst);
2256 /* if the best path is not 'pass through', then
2257 transcoding is needed; if desired, force transcode path
2258 to use SLINEAR between channels */
2259 if ((src != dst) && option_transcode_slin)
2260 dst = AST_FORMAT_SLINEAR;
2261 if (ast_set_read_format(chan, dst) < 0) {
2262 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", chan->name, dst);
2265 if (ast_set_write_format(peer, dst) < 0) {
2266 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", peer->name, dst);
2270 /* Set up translation from the peer to the chan */
2271 src = peer->nativeformats;
2272 dst = chan->nativeformats;
2273 if (ast_translator_best_choice(&dst, &src) < 0) {
2274 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", peer->name, src, chan->name, dst);
2277 /* if the best path is not 'pass through', then
2278 transcoding is needed; if desired, force transcode path
2279 to use SLINEAR between channels */
2280 if ((src != dst) && option_transcode_slin)
2281 dst = AST_FORMAT_SLINEAR;
2282 if (ast_set_read_format(peer, dst) < 0) {
2283 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", peer->name, dst);
2286 if (ast_set_write_format(chan, dst) < 0) {
2287 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", chan->name, dst);
2293 int ast_channel_masquerade(struct ast_channel *original, struct ast_channel *clone)
2295 struct ast_frame null = { AST_FRAME_NULL, };
2297 if (original == clone) {
2298 ast_log(LOG_WARNING, "Can't masquerade channel '%s' into itself!\n", original->name);
2301 ast_mutex_lock(&original->lock);
2302 while(ast_mutex_trylock(&clone->lock)) {
2303 ast_mutex_unlock(&original->lock);
2305 ast_mutex_lock(&original->lock);
2307 ast_log(LOG_DEBUG, "Planning to masquerade %s into the structure of %s\n",
2308 clone->name, original->name);
2309 if (original->masq) {
2310 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n",
2311 original->masq->name, original->name);
2312 } else if (clone->masqr) {
2313 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n",
2314 clone->name, clone->masqr->name);
2316 original->masq = clone;
2317 clone->masqr = original;
2318 ast_queue_frame(original, &null);
2319 ast_queue_frame(clone, &null);
2320 ast_log(LOG_DEBUG, "Done planning to masquerade %s into the structure of %s\n", original->name, clone->name);
2323 ast_mutex_unlock(&clone->lock);
2324 ast_mutex_unlock(&original->lock);
2328 void ast_change_name(struct ast_channel *chan, char *newname)
2331 strncpy(tmp, chan->name, sizeof(tmp) - 1);
2332 strncpy(chan->name, newname, sizeof(chan->name) - 1);
2333 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", tmp, chan->name, chan->uniqueid);
2336 void ast_channel_inherit_variables(const struct ast_channel *parent, struct ast_channel *child)
2338 struct ast_var_t *current, *newvar;
2341 AST_LIST_TRAVERSE(&parent->varshead, current, entries) {
2344 varname = ast_var_full_name(current);
2348 if (varname[0] == '_') {
2350 if (varname[1] == '_')
2356 newvar = ast_var_assign(&varname[1], ast_var_value(current));
2358 AST_LIST_INSERT_HEAD(&child->varshead, newvar, entries);
2360 ast_log(LOG_DEBUG, "Copying soft-transferable variable %s.\n", ast_var_name(newvar));
2364 newvar = ast_var_assign(ast_var_full_name(current), ast_var_value(current));
2366 AST_LIST_INSERT_HEAD(&child->varshead, newvar, entries);
2368 ast_log(LOG_DEBUG, "Copying hard-transferable variable %s.\n", ast_var_name(newvar));
2373 ast_log(LOG_DEBUG, "Not copying variable %s.\n", ast_var_name(current));
2379 /* Clone channel variables from 'clone' channel into 'original' channel
2380 All variables except those related to app_groupcount are cloned
2381 Variables are actually _removed_ from 'clone' channel, presumably
2382 because it will subsequently be destroyed.
2383 Assumes locks will be in place on both channels when called.
2386 static void clone_variables(struct ast_channel *original, struct ast_channel *clone)
2388 struct ast_var_t *varptr;
2390 /* we need to remove all app_groupcount related variables from the original
2391 channel before merging in the clone's variables; any groups assigned to the
2392 original channel should be released, only those assigned to the clone
2396 AST_LIST_TRAVERSE_SAFE_BEGIN(&original->varshead, varptr, entries) {
2397 if (!strncmp(ast_var_name(varptr), GROUP_CATEGORY_PREFIX, strlen(GROUP_CATEGORY_PREFIX))) {
2398 AST_LIST_REMOVE(&original->varshead, varptr, entries);
2399 ast_var_delete(varptr);
2402 AST_LIST_TRAVERSE_SAFE_END;
2404 /* Append variables from clone channel into original channel */
2405 /* XXX Is this always correct? We have to in order to keep MACROS working XXX */
2406 if (AST_LIST_FIRST(&clone->varshead))
2407 AST_LIST_INSERT_TAIL(&original->varshead, AST_LIST_FIRST(&clone->varshead), entries);
2410 /* Assumes channel will be locked when called */
2411 int ast_do_masquerade(struct ast_channel *original)
2416 struct ast_frame *cur, *prev;
2417 const struct ast_channel_tech *t;
2419 struct ast_callerid tmpcid;
2420 struct ast_channel *clone = original->masq;
2421 int rformat = original->readformat;
2422 int wformat = original->writeformat;
2429 ast_log(LOG_DEBUG, "Actually Masquerading %s(%d) into the structure of %s(%d)\n",
2430 clone->name, clone->_state, original->name, original->_state);
2432 /* XXX This is a seriously wacked out operation. We're essentially putting the guts of
2433 the clone channel into the original channel. Start by killing off the original
2434 channel's backend. I'm not sure we're going to keep this function, because
2435 while the features are nice, the cost is very high in terms of pure nastiness. XXX */
2437 /* We need the clone's lock, too */
2438 ast_mutex_lock(&clone->lock);
2440 ast_log(LOG_DEBUG, "Got clone lock on '%s' at %p\n", clone->name, &clone->lock);
2442 /* Having remembered the original read/write formats, we turn off any translation on either
2444 free_translation(clone);
2445 free_translation(original);
2448 /* Unlink the masquerade */
2449 original->masq = NULL;
2450 clone->masqr = NULL;
2452 /* Save the original name */
2453 strncpy(orig, original->name, sizeof(orig) - 1);
2454 /* Save the new name */
2455 strncpy(newn, clone->name, sizeof(newn) - 1);
2456 /* Create the masq name */
2457 snprintf(masqn, sizeof(masqn), "%s<MASQ>", newn);
2459 /* Copy the name from the clone channel */
2460 strncpy(original->name, newn, sizeof(original->name)-1);
2462 /* Mangle the name of the clone channel */
2463 strncpy(clone->name, masqn, sizeof(clone->name) - 1);
2465 /* Notify any managers of the change, first the masq then the other */
2466 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", newn, masqn, clone->uniqueid);
2467 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", orig, newn, original->uniqueid);
2469 /* Swap the technlogies */
2471 original->tech = clone->tech;
2474 t_pvt = original->tech_pvt;
2475 original->tech_pvt = clone->tech_pvt;
2476 clone->tech_pvt = t_pvt;
2478 /* Swap the readq's */
2479 cur = original->readq;
2480 original->readq = clone->readq;
2483 /* Swap the alertpipes */
2484 for (i = 0; i < 2; i++) {
2485 x = original->alertpipe[i];
2486 original->alertpipe[i] = clone->alertpipe[i];
2487 clone->alertpipe[i] = x;
2490 /* Swap the raw formats */
2491 x = original->rawreadformat;
2492 original->rawreadformat = clone->rawreadformat;
2493 clone->rawreadformat = x;
2494 x = original->rawwriteformat;
2495 original->rawwriteformat = clone->rawwriteformat;
2496 clone->rawwriteformat = x;
2498 /* Save any pending frames on both sides. Start by counting
2499 * how many we're going to need... */
2508 /* If we had any, prepend them to the ones already in the queue, and
2509 * load up the alertpipe */
2511 prev->next = original->readq;
2512 original->readq = clone->readq;
2513 clone->readq = NULL;
2514 if (original->alertpipe[1] > -1) {
2516 write(original->alertpipe[1], &x, sizeof(x));
2519 clone->_softhangup = AST_SOFTHANGUP_DEV;
2522 /* And of course, so does our current state. Note we need not
2523 call ast_setstate since the event manager doesn't really consider
2524 these separate. We do this early so that the clone has the proper
2525 state of the original channel. */
2526 origstate = original->_state;
2527 original->_state = clone->_state;
2528 clone->_state = origstate;
2530 if (clone->tech->fixup){
2531 res = clone->tech->fixup(original, clone);
2533 ast_log(LOG_WARNING, "Fixup failed on channel %s, strange things may happen.\n", clone->name);
2536 /* Start by disconnecting the original's physical side */
2537 if (clone->tech->hangup)
2538 res = clone->tech->hangup(clone);
2540 ast_log(LOG_WARNING, "Hangup failed! Strange things may happen!\n");
2541 ast_mutex_unlock(&clone->lock);
2545 snprintf(zombn, sizeof(zombn), "%s<ZOMBIE>", orig);
2546 /* Mangle the name of the clone channel */
2547 strncpy(clone->name, zombn, sizeof(clone->name) - 1);
2548 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", masqn, zombn, clone->uniqueid);
2550 /* Update the type. */
2551 original->type = clone->type;
2553 /* Keep the same language. */
2554 strncpy(original->language, clone->language, sizeof(original->language));
2556 for (x=0;x<AST_MAX_FDS;x++) {
2557 original->fds[x] = clone->fds[x];
2559 clone_variables(original, clone);
2560 clone->varshead.first = NULL;
2561 /* Presense of ADSI capable CPE follows clone */
2562 original->adsicpe = clone->adsicpe;
2563 /* Bridge remains the same */
2564 /* CDR fields remain the same */
2565 /* XXX What about blocking, softhangup, blocker, and lock and blockproc? XXX */
2566 /* Application and data remain the same */
2567 /* Clone exception becomes real one, as with fdno */
2568 ast_copy_flags(original, clone, AST_FLAG_EXCEPTION);
2569 original->fdno = clone->fdno;
2570 /* Schedule context remains the same */
2571 /* Stream stuff stays the same */
2572 /* Keep the original state. The fixup code will need to work with it most likely */
2574 /* Just swap the whole structures, nevermind the allocations, they'll work themselves
2576 tmpcid = original->cid;
2577 original->cid = clone->cid;
2578 clone->cid = tmpcid;
2580 /* Restore original timing file descriptor */
2581 original->fds[AST_MAX_FDS - 2] = original->timingfd;
2583 /* Our native formats are different now */
2584 original->nativeformats = clone->nativeformats;
2586 /* Context, extension, priority, app data, jump table, remain the same */
2587 /* pvt switches. pbx stays the same, as does next */
2589 /* Set the write format */
2590 ast_set_write_format(original, wformat);
2592 /* Set the read format */
2593 ast_set_read_format(original, rformat);
2595 /* Copy the music class */
2596 strncpy(original->musicclass, clone->musicclass, sizeof(original->musicclass) - 1);
2598 ast_log(LOG_DEBUG, "Putting channel %s in %d/%d formats\n", original->name, wformat, rformat);
2600 /* Okay. Last thing is to let the channel driver know about all this mess, so he
2601 can fix up everything as best as possible */
2602 if (original->tech->fixup) {
2603 res = original->tech->fixup(clone, original);
2605 ast_log(LOG_WARNING, "Driver for '%s' could not fixup channel %s\n",
2606 original->type, original->name);
2607 ast_mutex_unlock(&clone->lock);
2611 ast_log(LOG_WARNING, "Driver '%s' does not have a fixup routine (for %s)! Bad things may happen.\n",
2612 original->type, original->name);
2614 /* Now, at this point, the "clone" channel is totally F'd up. We mark it as
2615 a zombie so nothing tries to touch it. If it's already been marked as a
2616 zombie, then free it now (since it already is considered invalid). */
2617 if (ast_test_flag(clone, AST_FLAG_ZOMBIE)) {
2618 ast_log(LOG_DEBUG, "Destroying clone '%s'\n", clone->name);
2619 ast_mutex_unlock(&clone->lock);
2620 ast_channel_free(clone);
2621 manager_event(EVENT_FLAG_CALL, "Hangup", "Channel: %s\r\n", zombn);
2623 struct ast_frame null_frame = { AST_FRAME_NULL, };
2624 ast_log(LOG_DEBUG, "Released clone lock on '%s'\n", clone->name);
2625 ast_set_flag(clone, AST_FLAG_ZOMBIE);
2626 ast_queue_frame(clone, &null_frame);
2627 ast_mutex_unlock(&clone->lock);
2630 /* Signal any blocker */
2631 if (ast_test_flag(original, AST_FLAG_BLOCKING))
2632 pthread_kill(original->blocker, SIGURG);
2633 ast_log(LOG_DEBUG, "Done Masquerading %s (%d)\n",
2634 original->name, original->_state);
2638 void ast_set_callerid(struct ast_channel *chan, const char *callerid, const char *calleridname, const char *ani)
2641 if (chan->cid.cid_num)
2642 free(chan->cid.cid_num);
2643 if (ast_strlen_zero(callerid))
2644 chan->cid.cid_num = NULL;
2646 chan->cid.cid_num = strdup(callerid);
2649 if (chan->cid.cid_name)
2650 free(chan->cid.cid_name);
2651 if (ast_strlen_zero(calleridname))
2652 chan->cid.cid_name = NULL;
2654 chan->cid.cid_name = strdup(calleridname);
2657 if (chan->cid.cid_ani)
2658 free(chan->cid.cid_ani);
2659 if (ast_strlen_zero(ani))
2660 chan->cid.cid_ani = NULL;
2662 chan->cid.cid_ani = strdup(ani);
2665 ast_cdr_setcid(chan->cdr, chan);
2666 manager_event(EVENT_FLAG_CALL, "Newcallerid",
2669 "CallerIDName: %s\r\n"
2671 chan->name, chan->cid.cid_num ?
2672 chan->cid.cid_num : "<Unknown>",
2673 chan->cid.cid_name ?
2674 chan->cid.cid_name : "<Unknown>",
2678 int ast_setstate(struct ast_channel *chan, int state)
2680 if (chan->_state != state) {
2681 int oldstate = chan->_state;
2682 chan->_state = state;
2683 if (oldstate == AST_STATE_DOWN) {
2684 ast_device_state_changed(chan->name);
2685 manager_event(EVENT_FLAG_CALL, "Newchannel",
2689 "CallerIDName: %s\r\n"
2691 chan->name, ast_state2str(chan->_state),
2692 chan->cid.cid_num ? chan->cid.cid_num : "<unknown>",
2693 chan->cid.cid_name ? chan->cid.cid_name : "<unknown>",
2696 manager_event(EVENT_FLAG_CALL, "Newstate",
2700 "CallerIDName: %s\r\n"
2702 chan->name, ast_state2str(chan->_state),
2703 chan->cid.cid_num ? chan->cid.cid_num : "<unknown>",
2704 chan->cid.cid_name ? chan->cid.cid_name : "<unknown>",
2711 static long tvdiff(struct timeval *now, struct timeval *then)
2714 return (((now->tv_sec * 1000) + now->tv_usec / 1000) - ((then->tv_sec * 1000) + then->tv_usec / 1000));
2716 return (now->tv_sec - then->tv_sec) * 1000 + (now->tv_usec - then->tv_usec) / 1000;
2720 struct ast_channel *ast_bridged_channel(struct ast_channel *chan)
2722 struct ast_channel *bridged;
2723 bridged = chan->_bridge;
2724 if (bridged && bridged->tech->bridged_channel)
2725 bridged = bridged->tech->bridged_channel(chan, bridged);
2729 static void bridge_playfile(struct ast_channel *chan, struct ast_channel *peer, char *sound, int remain)
2731 int res=0, min=0, sec=0,check=0;
2733 check = ast_autoservice_start(peer);
2738 if (remain / 60 > 1) {
2746 if (!strcmp(sound,"timeleft")) {
2747 res = ast_streamfile(chan, "vm-youhave", chan->language);
2748 res = ast_waitstream(chan, "");
2750 res = ast_say_number(chan, min, AST_DIGIT_ANY, chan->language, (char *) NULL);
2751 res = ast_streamfile(chan, "queue-minutes", chan->language);
2752 res = ast_waitstream(chan, "");
2755 res = ast_say_number(chan, sec, AST_DIGIT_ANY, chan->language, (char *) NULL);
2756 res = ast_streamfile(chan, "queue-seconds", chan->language);
2757 res = ast_waitstream(chan, "");
2760 res = ast_streamfile(chan, sound, chan->language);
2761 res = ast_waitstream(chan, "");
2764 check = ast_autoservice_stop(peer);
2767 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)
2769 /* Copy voice back and forth between the two channels. Give the peer
2770 the ability to transfer calls with '#<extension' syntax. */
2771 struct ast_channel *cs[3];
2773 struct ast_frame *f;
2774 struct ast_channel *who = NULL;
2777 int o0nativeformats;
2778 int o1nativeformats;
2779 struct timeval precise_now;
2780 long elapsed_ms=0, time_left_ms=0;
2786 o0nativeformats = c0->nativeformats;
2787 o1nativeformats = c1->nativeformats;
2790 if ((c0->pvt != pvt0) || (c1->pvt != pvt1) ||
2791 (o0nativeformats != c0->nativeformats) ||
2792 (o1nativeformats != c1->nativeformats)) {
2793 /* Check for Masquerade, codec changes, etc */
2798 if (config->timelimit) {
2799 /* If there is a time limit, return now */
2800 gettimeofday(&precise_now,NULL);
2801 elapsed_ms = tvdiff(&precise_now,start_time);
2802 time_left_ms = config->timelimit - elapsed_ms;
2804 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)) {
2808 if (time_left_ms <= 0) {
2812 if (time_left_ms >= 5000 && *playit) {
2819 who = ast_waitfor_n(cs, 2, &to);
2821 ast_log(LOG_DEBUG, "Nobody there, continuing...\n");
2822 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE || c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE) {
2823 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
2824 c0->_softhangup = 0;
2825 if (c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
2826 c1->_softhangup = 0;
2839 ast_log(LOG_DEBUG, "Didn't get a frame from channel: %s\n",who->name);
2843 if ((f->frametype == AST_FRAME_CONTROL) && !(config->flags & AST_BRIDGE_IGNORE_SIGS)) {
2844 if ((f->subclass == AST_CONTROL_HOLD) || (f->subclass == AST_CONTROL_UNHOLD)) {
2845 ast_indicate(who == c0 ? c1 : c0, f->subclass);
2850 ast_log(LOG_DEBUG, "Got a FRAME_CONTROL (%d) frame on channel %s\n", f->subclass, who->name);
2854 if ((f->frametype == AST_FRAME_VOICE) ||
2855 (f->frametype == AST_FRAME_TEXT) ||
2856 (f->frametype == AST_FRAME_VIDEO) ||
2857 (f->frametype == AST_FRAME_IMAGE) ||
2858 (f->frametype == AST_FRAME_HTML) ||
2859 (f->frametype == AST_FRAME_DTMF)) {
2861 if ((f->frametype == AST_FRAME_DTMF) &&
2862 (config->flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))) {
2864 if ((config->flags & AST_BRIDGE_DTMF_CHANNEL_0)) {
2867 /* Take out of conference mode */
2869 ast_log(LOG_DEBUG, "Got AST_BRIDGE_DTMF_CHANNEL_0 on c0 (%s)\n",c0->name);
2875 if (config->flags & AST_BRIDGE_DTMF_CHANNEL_1) {
2879 ast_log(LOG_DEBUG, "Got AST_BRIDGE_DTMF_CHANNEL_1 on c1 (%s)\n",c1->name);
2886 ast_log(LOG_DEBUG, "Read from %s\n", who->name);
2888 ast_log(LOG_DEBUG, "Servicing channel %s twice in a row?\n", last->name);
2892 /* Don't copy packets if there is a generator on either one, since they're
2893 not supposed to be listening anyway */
2902 /* Swap who gets priority */
2910 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)
2912 /* Copy voice back and forth between the two channels. Give the peer
2913 the ability to transfer calls with '#<extension' syntax. */
2914 struct ast_channel *cs[3];
2915 struct ast_channel *who = NULL;
2919 int o0nativeformats;
2920 int o1nativeformats;
2921 struct timeval start_time,precise_now;
2922 long elapsed_ms=0, time_left_ms=0;
2923 int playit=0, playitagain=1, first_time=1;
2926 firstpass = config->firstpass;
2927 config->firstpass = 0;
2930 gettimeofday(&start_time,NULL);
2931 time_left_ms = config->timelimit;
2933 if ((ast_test_flag(&(config->features_caller), AST_FEATURE_PLAY_WARNING)) && config->start_sound && firstpass)
2934 bridge_playfile(c0,c1,config->start_sound,time_left_ms / 1000);
2935 if ((ast_test_flag(&(config->features_callee), AST_FEATURE_PLAY_WARNING)) && config->start_sound && firstpass)
2936 bridge_playfile(c1,c0,config->start_sound,time_left_ms / 1000);
2938 /* Stop if we're a zombie or need a soft hangup */
2939 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))
2942 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n",
2943 c0->name, c0->_bridge->name);
2947 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n",
2948 c1->name, c1->_bridge->name);
2952 /* Keep track of bridge */
2958 manager_event(EVENT_FLAG_CALL, "Link",
2962 "Uniqueid2: %s\r\n",
2963 c0->name, c1->name, c0->uniqueid, c1->uniqueid);
2964 o1nativeformats = c1->nativeformats;
2965 o0nativeformats = c0->nativeformats;
2966 for (/* ever */;;) {
2968 if (config->timelimit) {
2969 gettimeofday(&precise_now,NULL);
2970 elapsed_ms = tvdiff(&precise_now,&start_time);
2971 time_left_ms = config->timelimit - elapsed_ms;
2973 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)) {
2974 /* narrowing down to the end */
2975 if (config->warning_freq == 0) {
2979 } else if (first_time) {
2983 if ((time_left_ms % config->warning_freq) <= 50) {
2988 if (time_left_ms <= 0) {
2989 if ((ast_test_flag(&(config->features_caller), AST_FEATURE_PLAY_WARNING)) && config->end_sound)
2990 bridge_playfile(c0,c1,config->end_sound,0);
2991 if ((ast_test_flag(&(config->features_callee), AST_FEATURE_PLAY_WARNING)) && config->end_sound)
2992 bridge_playfile(c1,c0,config->end_sound,0);
2998 if (time_left_ms >= 5000 && playit) {
2999 if ((ast_test_flag(&(config->features_caller), AST_FEATURE_PLAY_WARNING)) && config->warning_sound && config->play_warning)
3000 bridge_playfile(c0,c1,config->warning_sound,time_left_ms / 1000);
3001 if ((ast_test_flag(&(config->features_callee), AST_FEATURE_PLAY_WARNING)) && config->warning_sound && config->play_warning)
3002 bridge_playfile(c1,c0,config->warning_sound,time_left_ms / 1000);
3008 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE || c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE) {
3009 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
3010 c0->_softhangup = 0;
3011 if (c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
3012 c1->_softhangup = 0;
3015 ast_log(LOG_DEBUG, "Unbridge signal received. Ending native bridge.\n");
3019 /* Stop if we're a zombie or need a soft hangup */
3020 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)) {
3024 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");
3027 if (c0->tech->bridge && config->timelimit==0 &&
3028 (c0->tech->bridge == c1->tech->bridge) && !nativefailed && !c0->monitor && !c1->monitor && !c0->spiers && !c1->spiers) {
3029 /* Looks like they share a bridge code */
3030 if (option_verbose > 2)
3031 ast_verbose(VERBOSE_PREFIX_3 "Attempting native bridge of %s and %s\n", c0->name, c1->name);
3032 ast_set_flag(c0, AST_FLAG_NBRIDGE);
3033 ast_set_flag(c1, AST_FLAG_NBRIDGE);
3034 if (!(res = c0->tech->bridge(c0, c1, config->flags, fo, rc))) {
3037 manager_event(EVENT_FLAG_CALL, "Unlink",
3041 "Uniqueid2: %s\r\n",
3042 c0->name, c1->name, c0->uniqueid, c1->uniqueid);
3043 ast_log(LOG_DEBUG, "Returning from native bridge, channels: %s, %s\n",c0->name ,c1->name);
3044 ast_clear_flag(c0, AST_FLAG_NBRIDGE);
3045 ast_clear_flag(c1, AST_FLAG_NBRIDGE);
3046 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE || c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE) {
3054 ast_clear_flag(c0, AST_FLAG_NBRIDGE);
3055 ast_clear_flag(c1, AST_FLAG_NBRIDGE);
3058 /* If they return non-zero then continue on normally. Let "-2" mean don't worry about
3059 my not wanting to bridge */
3060 if ((res != -2) && (res != -3))
3061 ast_log(LOG_WARNING, "Private bridge between %s and %s failed\n", c0->name, c1->name);
3062 if (res != -3) nativefailed++;
3065 if (((c0->writeformat != c1->readformat) || (c0->readformat != c1->writeformat) || (c0->nativeformats != o0nativeformats) || (c1->nativeformats != o1nativeformats)) &&
3066 !(c0->generator || c1->generator)) {
3067 if (ast_channel_make_compatible(c0, c1)) {
3068 ast_log(LOG_WARNING, "Can't make %s and %s compatible\n", c0->name, c1->name);
3069 manager_event(EVENT_FLAG_CALL, "Unlink",
3073 "Uniqueid2: %s\r\n",
3074 c0->name, c1->name, c0->uniqueid, c1->uniqueid);
3077 o0nativeformats = c0->nativeformats;
3078 o1nativeformats = c1->nativeformats;
3080 res = ast_generic_bridge(&playitagain, &playit, &start_time, c0, c1, config, fo, rc);
3086 manager_event(EVENT_FLAG_CALL, "Unlink",