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 #ifdef ZAPTEL_OPTIMIZATIONS
43 #include <sys/ioctl.h>
45 #include <linux/zaptel.h>
48 #endif /* __linux__ */
50 #error "You need newer zaptel! Please cvs update zaptel"
55 /* uncomment if you have problems with 'monitoring' synchronized files */
57 #define MONITOR_CONSTANT_DELAY
58 #define MONITOR_DELAY 150 * 8 /* 150 ms of MONITORING DELAY */
61 static int shutting_down = 0;
62 static int uniqueint = 0;
64 unsigned long global_fin = 0, global_fout = 0;
66 /* XXX Lock appropriately in more functions XXX */
69 const struct ast_channel_tech *tech;
70 struct chanlist *next;
72 struct ast_channel *channels = NULL;
74 /* Protect the channel list (highly unlikely that two things would change
75 it at the same time, but still! */
77 AST_MUTEX_DEFINE_STATIC(chlock);
79 static int show_channeltypes(int fd, int argc, char *argv[])
81 #define FORMAT "%-7.7s %-50.50s\n"
82 struct chanlist *cl = backends;
83 ast_cli(fd, FORMAT, "Type", "Description");
84 ast_cli(fd, FORMAT, "------", "-----------");
85 if (ast_mutex_lock(&chlock)) {
86 ast_log(LOG_WARNING, "Unable to lock channel list\n");
90 ast_cli(fd, FORMAT, cl->tech->type, cl->tech->description);
93 ast_mutex_unlock(&chlock);
94 return RESULT_SUCCESS;
98 static char show_channeltypes_usage[] =
99 "Usage: show channeltypes\n"
100 " Shows available channel types registered in your Asterisk server.\n";
102 static struct ast_cli_entry cli_show_channeltypes =
103 { { "show", "channeltypes", NULL }, show_channeltypes, "Show available channel types", show_channeltypes_usage };
105 int ast_check_hangup(struct ast_channel *chan)
109 /* if soft hangup flag, return true */
110 if (chan->_softhangup) return 1;
111 /* if no technology private data, return true */
112 if (!chan->tech_pvt) return 1;
113 /* if no hangup scheduled, just return here */
114 if (!chan->whentohangup) return 0;
115 time(&myt); /* get current time */
116 /* return, if not yet */
117 if (chan->whentohangup > myt) return 0;
118 chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
122 static int ast_check_hangup_locked(struct ast_channel *chan)
125 ast_mutex_lock(&chan->lock);
126 res = ast_check_hangup(chan);
127 ast_mutex_unlock(&chan->lock);
131 void ast_begin_shutdown(int hangup)
133 struct ast_channel *c;
136 ast_mutex_lock(&chlock);
139 ast_softhangup(c, AST_SOFTHANGUP_SHUTDOWN);
142 ast_mutex_unlock(&chlock);
146 int ast_active_channels(void)
148 struct ast_channel *c;
150 ast_mutex_lock(&chlock);
156 ast_mutex_unlock(&chlock);
160 void ast_cancel_shutdown(void)
165 int ast_shutting_down(void)
167 return shutting_down;
170 void ast_channel_setwhentohangup(struct ast_channel *chan, time_t offset)
176 chan->whentohangup = myt + offset;
178 chan->whentohangup = 0;
182 int ast_channel_register(const struct ast_channel_tech *tech)
184 struct chanlist *chan;
186 ast_mutex_lock(&chlock);
190 if (!strcasecmp(tech->type, chan->tech->type)) {
191 ast_log(LOG_WARNING, "Already have a handler for type '%s'\n", tech->type);
192 ast_mutex_unlock(&chlock);
198 chan = malloc(sizeof(*chan));
200 ast_log(LOG_WARNING, "Out of memory\n");
201 ast_mutex_unlock(&chlock);
205 chan->next = backends;
209 ast_log(LOG_DEBUG, "Registered handler for '%s' (%s)\n", chan->tech->type, chan->tech->description);
211 if (option_verbose > 1)
212 ast_verbose(VERBOSE_PREFIX_2 "Registered channel type '%s' (%s)\n", chan->tech->type,
213 chan->tech->description);
215 ast_mutex_unlock(&chlock);
219 char *ast_state2str(int state)
221 /* XXX Not reentrant XXX */
222 static char localtmp[256];
226 case AST_STATE_RESERVED:
228 case AST_STATE_OFFHOOK:
230 case AST_STATE_DIALING:
234 case AST_STATE_RINGING:
241 snprintf(localtmp, sizeof(localtmp), "Unknown (%d)\n", state);
247 int ast_best_codec(int fmts)
249 /* This just our opinion, expressed in code. We are asked to choose
250 the best codec to use, given no information */
254 /* Okay, ulaw is used by all telephony equipment, so start with it */
256 /* Unless of course, you're a silly European, so then prefer ALAW */
258 /* Okay, well, signed linear is easy to translate into other stuff */
260 /* G.726 is standard ADPCM */
262 /* ADPCM has great sound quality and is still pretty easy to translate */
264 /* Okay, we're down to vocoders now, so pick GSM because it's small and easier to
265 translate and sounds pretty good */
267 /* iLBC is not too bad */
269 /* Speex is free, but computationally more expensive than GSM */
271 /* Ick, LPC10 sounds terrible, but at least we have code for it, if you're tacky enough
274 /* G.729a is faster than 723 and slightly less expensive */
276 /* Down to G.723.1 which is proprietary but at least designed for voice */
281 for (x=0;x<sizeof(prefs) / sizeof(prefs[0]); x++)
284 ast_log(LOG_WARNING, "Don't know any of 0x%x formats\n", fmts);
288 static const struct ast_channel_tech null_tech = {
290 .description = "Null channel (should not see this)",
293 struct ast_channel *ast_channel_alloc(int needqueue)
295 struct ast_channel *tmp;
298 struct varshead *headp;
301 /* If shutting down, don't allocate any new channels */
305 ast_mutex_lock(&chlock);
306 tmp = malloc(sizeof(struct ast_channel));
308 ast_log(LOG_WARNING, "Out of memory\n");
309 ast_mutex_unlock(&chlock);
313 memset(tmp, 0, sizeof(struct ast_channel));
314 tmp->sched = sched_context_create();
316 ast_log(LOG_WARNING, "Unable to create schedule context\n");
318 ast_mutex_unlock(&chlock);
322 for (x=0;x<AST_MAX_FDS - 1;x++)
325 #ifdef ZAPTEL_OPTIMIZATIONS
326 tmp->timingfd = open("/dev/zap/timer", O_RDWR);
327 if (tmp->timingfd > -1) {
328 /* Check if timing interface supports new
331 if (!ioctl(tmp->timingfd, ZT_TIMERPONG, &flags))
339 if (pipe(tmp->alertpipe)) {
340 ast_log(LOG_WARNING, "Alert pipe creation failed!\n");
342 ast_mutex_unlock(&chlock);
345 flags = fcntl(tmp->alertpipe[0], F_GETFL);
346 fcntl(tmp->alertpipe[0], F_SETFL, flags | O_NONBLOCK);
347 flags = fcntl(tmp->alertpipe[1], F_GETFL);
348 fcntl(tmp->alertpipe[1], F_SETFL, flags | O_NONBLOCK);
351 /* Make sure we've got it done right if they don't */
352 tmp->alertpipe[0] = tmp->alertpipe[1] = -1;
354 /* Always watch the alertpipe */
355 tmp->fds[AST_MAX_FDS-1] = tmp->alertpipe[0];
356 /* And timing pipe */
357 tmp->fds[AST_MAX_FDS-2] = tmp->timingfd;
358 strncpy(tmp->name, "**Unknown**", sizeof(tmp->name)-1);
360 tmp->_state = AST_STATE_DOWN;
364 tmp->fin = global_fin;
365 tmp->fout = global_fout;
366 snprintf(tmp->uniqueid, sizeof(tmp->uniqueid), "%li.%d", (long)time(NULL), uniqueint++);
367 headp = &tmp->varshead;
368 ast_mutex_init(&tmp->lock);
369 AST_LIST_HEAD_INIT(headp);
370 strncpy(tmp->context, "default", sizeof(tmp->context)-1);
371 strncpy(tmp->language, defaultlanguage, sizeof(tmp->language)-1);
372 strncpy(tmp->exten, "s", sizeof(tmp->exten)-1);
374 tmp->amaflags = ast_default_amaflags;
375 strncpy(tmp->accountcode, ast_default_accountcode, sizeof(tmp->accountcode)-1);
377 tmp->tech = &null_tech;
379 tmp->next = channels;
382 ast_mutex_unlock(&chlock);
386 int ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin)
389 struct ast_frame *prev, *cur;
392 /* Build us a copy and free the original one */
395 ast_log(LOG_WARNING, "Unable to duplicate frame\n");
398 ast_mutex_lock(&chan->lock);
402 if ((cur->frametype == AST_FRAME_CONTROL) && (cur->subclass == AST_CONTROL_HANGUP)) {
403 /* Don't bother actually queueing anything after a hangup */
405 ast_mutex_unlock(&chan->lock);
412 /* Allow up to 96 voice frames outstanding, and up to 128 total frames */
413 if (((fin->frametype == AST_FRAME_VOICE) && (qlen > 96)) || (qlen > 128)) {
414 if (fin->frametype != AST_FRAME_VOICE) {
415 ast_log(LOG_WARNING, "Exceptionally long queue length queuing to %s\n", chan->name);
418 ast_log(LOG_DEBUG, "Dropping voice to exceptionally long queue on %s\n", chan->name);
420 ast_mutex_unlock(&chan->lock);
428 if (chan->alertpipe[1] > -1) {
429 if (write(chan->alertpipe[1], &blah, sizeof(blah)) != sizeof(blah))
430 ast_log(LOG_WARNING, "Unable to write to alert pipe on %s, frametype/subclass %d/%d (qlen = %d): %s!\n",
431 chan->name, f->frametype, f->subclass, qlen, strerror(errno));
432 #ifdef ZAPTEL_OPTIMIZATIONS
433 } else if (chan->timingfd > -1) {
434 ioctl(chan->timingfd, ZT_TIMERPING, &blah);
436 } else if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
437 pthread_kill(chan->blocker, SIGURG);
439 ast_mutex_unlock(&chan->lock);
443 int ast_queue_hangup(struct ast_channel *chan)
445 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_HANGUP };
446 chan->_softhangup |= AST_SOFTHANGUP_DEV;
447 return ast_queue_frame(chan, &f);
450 int ast_queue_control(struct ast_channel *chan, int control)
452 struct ast_frame f = { AST_FRAME_CONTROL, };
453 f.subclass = control;
454 return ast_queue_frame(chan, &f);
457 int ast_channel_defer_dtmf(struct ast_channel *chan)
461 pre = ast_test_flag(chan, AST_FLAG_DEFER_DTMF);
462 ast_set_flag(chan, AST_FLAG_DEFER_DTMF);
467 void ast_channel_undefer_dtmf(struct ast_channel *chan)
470 ast_clear_flag(chan, AST_FLAG_DEFER_DTMF);
473 struct ast_channel *ast_channel_walk_locked(struct ast_channel *prev)
475 /* Returns next channel (locked) */
476 struct ast_channel *l, *ret;
480 ast_mutex_lock(&chlock);
484 if (ast_mutex_trylock(&l->lock)) {
486 ast_log(LOG_DEBUG, "Avoiding initial deadlock for '%s'\n", l->name);
488 ast_log(LOG_WARNING, "Avoided initial deadlock for '%s', %d retries!\n", l->name, retries);
489 ast_mutex_unlock(&chlock);
498 ast_mutex_unlock(&chlock);
507 if (ast_mutex_trylock(&ret->lock)) {
509 ast_log(LOG_DEBUG, "Avoiding deadlock for '%s'\n", ret->name);
511 ast_log(LOG_WARNING, "Avoided deadlock for '%s', %d retries!\n", ret->name, retries);
512 ast_mutex_unlock(&chlock);
521 ast_mutex_unlock(&chlock);
526 struct ast_channel *ast_get_channel_by_name_locked(char *channame)
528 struct ast_channel *chan;
529 chan = ast_channel_walk_locked(NULL);
531 if (!strcasecmp(chan->name, channame))
533 ast_mutex_unlock(&chan->lock);
534 chan = ast_channel_walk_locked(chan);
539 int ast_safe_sleep_conditional( struct ast_channel *chan, int ms,
540 int (*cond)(void*), void *data )
545 if( cond && ((*cond)(data) == 0 ) )
547 ms = ast_waitfor(chan, ms);
560 int ast_safe_sleep(struct ast_channel *chan, int ms)
564 ms = ast_waitfor(chan, ms);
577 static void free_cid(struct ast_callerid *cid)
588 free(cid->cid_rdnis);
591 void ast_channel_free(struct ast_channel *chan)
593 struct ast_channel *last=NULL, *cur;
595 struct ast_var_t *vardata;
596 struct ast_frame *f, *fp;
597 struct varshead *headp;
598 char name[AST_CHANNEL_NAME];
600 headp=&chan->varshead;
602 ast_mutex_lock(&chlock);
607 last->next = cur->next;
609 channels = cur->next;
616 ast_log(LOG_WARNING, "Unable to find channel in list\n");
618 /* Lock and unlock the channel just to be sure nobody
619 has it locked still */
620 ast_mutex_lock(&cur->lock);
621 ast_mutex_unlock(&cur->lock);
623 if (chan->tech_pvt) {
624 ast_log(LOG_WARNING, "Channel '%s' may not have been hung up properly\n", chan->name);
625 free(chan->tech_pvt);
628 strncpy(name, chan->name, sizeof(name)-1);
630 /* Stop monitoring */
632 chan->monitor->stop( chan, 0 );
635 /* If there is native format music-on-hold state, free it */
636 if(chan->music_state)
637 ast_moh_cleanup(chan);
639 /* Free translatosr */
641 ast_translator_free_path(chan->readtrans);
642 if (chan->writetrans)
643 ast_translator_free_path(chan->writetrans);
645 ast_log(LOG_WARNING, "PBX may not have been terminated properly on '%s'\n", chan->name);
646 free_cid(&chan->cid);
647 ast_mutex_destroy(&chan->lock);
648 /* Close pipes if appropriate */
649 if ((fd = chan->alertpipe[0]) > -1)
651 if ((fd = chan->alertpipe[1]) > -1)
653 if ((fd = chan->timingfd) > -1)
663 /* loop over the variables list, freeing all data and deleting list items */
664 /* no need to lock the list, as the channel is already locked */
666 while (!AST_LIST_EMPTY(headp)) { /* List Deletion. */
667 vardata = AST_LIST_REMOVE_HEAD(headp, entries);
668 /* printf("deleting var %s=%s\n",ast_var_name(vardata),ast_var_value(vardata)); */
669 ast_var_delete(vardata);
673 ast_mutex_unlock(&chlock);
675 ast_device_state_changed(name);
678 static void ast_spy_detach(struct ast_channel *chan)
680 struct ast_channel_spy *chanspy;
684 for (chanspy = chan->spiers; chanspy; chanspy = chanspy->next) {
685 if (chanspy->status == CHANSPY_RUNNING) {
686 chanspy->status = CHANSPY_DONE;
690 /* signal all the spys to get lost and allow them time to unhook themselves
691 god help us if they don't......
693 while (chan->spiers && to >= 0) {
694 ast_safe_sleep(chan, sleepms);
701 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
704 struct ast_frame f = { AST_FRAME_NULL };
706 ast_log(LOG_DEBUG, "Soft-Hanging up channel '%s'\n", chan->name);
707 /* Inform channel driver that we need to be hung up, if it cares */
708 chan->_softhangup |= cause;
709 ast_queue_frame(chan, &f);
710 /* Interrupt any poll call or such */
711 if (ast_test_flag(chan, AST_FLAG_BLOCKING))
712 pthread_kill(chan->blocker, SIGURG);
716 int ast_softhangup(struct ast_channel *chan, int cause)
719 ast_mutex_lock(&chan->lock);
720 res = ast_softhangup_nolock(chan, cause);
721 ast_mutex_unlock(&chan->lock);
725 static void ast_queue_spy_frame(struct ast_channel_spy *spy, struct ast_frame *f, int pos)
727 struct ast_frame *tmpf = NULL;
730 ast_mutex_lock(&spy->lock);
731 for (tmpf=spy->queue[pos]; tmpf && tmpf->next; tmpf=tmpf->next) {
735 struct ast_frame *freef, *headf;
737 ast_log(LOG_ERROR, "Too Many frames queued at once, flushing cache.\n");
738 headf = spy->queue[pos];
739 /* deref the queue right away so it looks empty */
740 spy->queue[pos] = NULL;
742 /* free the wasted frames */
748 ast_mutex_unlock(&spy->lock);
753 tmpf->next = ast_frdup(f);
755 spy->queue[pos] = ast_frdup(f);
758 ast_mutex_unlock(&spy->lock);
761 static void free_translation(struct ast_channel *clone)
763 if (clone->writetrans)
764 ast_translator_free_path(clone->writetrans);
765 if (clone->readtrans)
766 ast_translator_free_path(clone->readtrans);
767 clone->writetrans = NULL;
768 clone->readtrans = NULL;
769 clone->rawwriteformat = clone->nativeformats;
770 clone->rawreadformat = clone->nativeformats;
773 int ast_hangup(struct ast_channel *chan)
776 /* Don't actually hang up a channel that will masquerade as someone else, or
777 if someone is going to masquerade as us */
778 ast_mutex_lock(&chan->lock);
780 /* get rid of spies */
781 ast_spy_detach(chan);
784 if (ast_do_masquerade(chan))
785 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
789 ast_log(LOG_WARNING, "%s getting hung up, but someone is trying to masq into us?!?\n", chan->name);
790 ast_mutex_unlock(&chan->lock);
793 /* If this channel is one which will be masqueraded into something,
794 mark it as a zombie already, so we know to free it later */
796 ast_set_flag(chan, AST_FLAG_ZOMBIE);
797 ast_mutex_unlock(&chan->lock);
800 free_translation(chan);
802 ast_closestream(chan->stream);
804 ast_closestream(chan->vstream);
806 sched_context_destroy(chan->sched);
807 /* Clear any tone stuff remaining */
808 if (chan->generatordata)
809 chan->generator->release(chan, chan->generatordata);
810 chan->generatordata = NULL;
811 chan->generator = NULL;
813 /* End the CDR if it hasn't already */
814 ast_cdr_end(chan->cdr);
815 /* Post and Free the CDR */
816 ast_cdr_post(chan->cdr);
817 ast_cdr_free(chan->cdr);
819 if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
820 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
821 "is blocked by thread %ld in procedure %s! Expect a failure\n",
822 (long)pthread_self(), chan->name, (long)chan->blocker, chan->blockproc);
825 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE)) {
827 ast_log(LOG_DEBUG, "Hanging up channel '%s'\n", chan->name);
828 if (chan->tech->hangup)
829 res = chan->tech->hangup(chan);
832 ast_log(LOG_DEBUG, "Hanging up zombie '%s'\n", chan->name);
834 ast_mutex_unlock(&chan->lock);
835 manager_event(EVENT_FLAG_CALL, "Hangup",
839 chan->name, chan->uniqueid, chan->hangupcause);
840 ast_channel_free(chan);
844 void ast_channel_unregister(const struct ast_channel_tech *tech)
846 struct chanlist *chan, *last=NULL;
849 ast_log(LOG_DEBUG, "Unregistering channel type '%s'\n", tech->type);
851 ast_mutex_lock(&chlock);
855 if (chan->tech == tech) {
857 last->next = chan->next;
859 backends = backends->next;
861 ast_mutex_unlock(&chlock);
863 if (option_verbose > 1)
864 ast_verbose( VERBOSE_PREFIX_2 "Unregistered channel type '%s'\n", tech->type);
872 ast_mutex_unlock(&chlock);
875 int ast_answer(struct ast_channel *chan)
878 ast_mutex_lock(&chan->lock);
879 /* Stop if we're a zombie or need a soft hangup */
880 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
881 ast_mutex_unlock(&chan->lock);
884 switch(chan->_state) {
885 case AST_STATE_RINGING:
887 if (chan->tech->answer)
888 res = chan->tech->answer(chan);
889 ast_setstate(chan, AST_STATE_UP);
891 ast_cdr_answer(chan->cdr);
892 ast_mutex_unlock(&chan->lock);
897 ast_cdr_answer(chan->cdr);
900 ast_mutex_unlock(&chan->lock);
906 void ast_deactivate_generator(struct ast_channel *chan)
908 ast_mutex_lock(&chan->lock);
909 if (chan->generatordata) {
910 if (chan->generator && chan->generator->release)
911 chan->generator->release(chan, chan->generatordata);
912 chan->generatordata = NULL;
913 chan->generator = NULL;
914 ast_clear_flag(chan, AST_FLAG_WRITE_INT);
915 ast_settimeout(chan, 0, NULL, NULL);
917 ast_mutex_unlock(&chan->lock);
920 static int generator_force(void *data)
922 /* Called if generator doesn't have data */
925 int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples);
926 struct ast_channel *chan = data;
927 tmp = chan->generatordata;
928 chan->generatordata = NULL;
929 generate = chan->generator->generate;
930 res = generate(chan, tmp, 0, 160);
931 chan->generatordata = tmp;
933 ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
934 ast_deactivate_generator(chan);
939 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
942 ast_mutex_lock(&chan->lock);
943 if (chan->generatordata) {
944 if (chan->generator && chan->generator->release)
945 chan->generator->release(chan, chan->generatordata);
946 chan->generatordata = NULL;
949 if ((chan->generatordata = gen->alloc(chan, params))) {
950 ast_settimeout(chan, 160, generator_force, chan);
951 chan->generator = gen;
955 ast_mutex_unlock(&chan->lock);
959 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
961 /* Wait for x amount of time on a file descriptor to have input. */
962 struct timeval start, now;
969 pfds = alloca(sizeof(struct pollfd) * n);
971 ast_log(LOG_ERROR, "Out of memory\n");
975 gettimeofday(&start, NULL);
980 pfds[y].events = POLLIN | POLLPRI;
984 res = poll(pfds, y, *ms);
986 /* Simulate a timeout if we were interrupted */
996 if ((res = ast_fdisset(pfds, fds[x], y, &spoint))) {
1009 gettimeofday(&now, NULL);
1010 passed = (now.tv_sec - start.tv_sec) * 1000;
1011 passed += (now.tv_usec - start.tv_usec) / 1000;
1020 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
1021 int *exception, int *outfd, int *ms)
1023 /* Wait for x amount of time on a file descriptor to have input. */
1024 struct timeval start, end;
1025 struct pollfd *pfds;
1031 long whentohangup = 0, havewhen = 0, diff;
1032 struct ast_channel *winner = NULL;
1034 pfds = alloca(sizeof(struct pollfd) * (n * AST_MAX_FDS + nfds));
1036 ast_log(LOG_ERROR, "Out of memory\n");
1046 /* Perform any pending masquerades */
1048 ast_mutex_lock(&c[x]->lock);
1049 if (c[x]->whentohangup) {
1052 diff = c[x]->whentohangup - now;
1053 if (!havewhen || (diff < whentohangup)) {
1055 whentohangup = diff;
1059 if (ast_do_masquerade(c[x])) {
1060 ast_log(LOG_WARNING, "Masquerade failed\n");
1062 ast_mutex_unlock(&c[x]->lock);
1066 ast_mutex_unlock(&c[x]->lock);
1072 if ((*ms < 0) || (whentohangup * 1000 < *ms)) {
1073 rms = whentohangup * 1000;
1078 for (y=0;y<AST_MAX_FDS;y++) {
1079 if (c[x]->fds[y] > -1) {
1080 pfds[max].fd = c[x]->fds[y];
1081 pfds[max].events = POLLIN | POLLPRI;
1085 CHECK_BLOCKING(c[x]);
1087 for (x=0;x<nfds; x++) {
1089 pfds[max].fd = fds[x];
1090 pfds[max].events = POLLIN | POLLPRI;
1095 gettimeofday(&start, NULL);
1096 res = poll(pfds, max, rms);
1099 ast_clear_flag(c[x], AST_FLAG_BLOCKING);
1100 /* Simulate a timeout if we were interrupted */
1104 /* Just an interrupt */
1116 ast_clear_flag(c[x], AST_FLAG_BLOCKING);
1117 if (havewhen && c[x]->whentohangup && (now > c[x]->whentohangup)) {
1118 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1122 for (y=0;y<AST_MAX_FDS;y++) {
1123 if (c[x]->fds[y] > -1) {
1124 if ((res = ast_fdisset(pfds, c[x]->fds[y], max, &spoint))) {
1126 ast_set_flag(c[x], AST_FLAG_EXCEPTION);
1128 ast_clear_flag(c[x], AST_FLAG_EXCEPTION);
1135 for (x=0;x<nfds;x++) {
1137 if ((res = ast_fdisset(pfds, fds[x], max, &spoint))) {
1152 gettimeofday(&end, NULL);
1153 diff = (end.tv_sec - start.tv_sec) * 1000;
1154 diff += (end.tv_usec - start.tv_usec) / 1000;
1163 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
1165 return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
1168 int ast_waitfor(struct ast_channel *c, int ms)
1170 struct ast_channel *chan;
1172 chan = ast_waitfor_n(&c, 1, &ms);
1182 char ast_waitfordigit(struct ast_channel *c, int ms)
1184 /* XXX Should I be merged with waitfordigit_full XXX */
1185 struct ast_frame *f;
1187 /* Stop if we're a zombie or need a soft hangup */
1188 if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
1190 /* Wait for a digit, no more than ms milliseconds total. */
1191 while(ms && !result) {
1192 ms = ast_waitfor(c, ms);
1193 if (ms < 0) /* Error */
1196 /* Read something */
1199 if (f->frametype == AST_FRAME_DTMF)
1200 result = f->subclass;
1209 int ast_settimeout(struct ast_channel *c, int samples, int (*func)(void *data), void *data)
1212 #ifdef ZAPTEL_OPTIMIZATIONS
1213 if (c->timingfd > -1) {
1218 ast_log(LOG_DEBUG, "Scheduling timer at %d sample intervals\n", samples);
1219 res = ioctl(c->timingfd, ZT_TIMERCONFIG, &samples);
1220 c->timingfunc = func;
1221 c->timingdata = data;
1226 char ast_waitfordigit_full(struct ast_channel *c, int ms, int audiofd, int cmdfd)
1228 struct ast_frame *f;
1229 struct ast_channel *rchan;
1232 /* Stop if we're a zombie or need a soft hangup */
1233 if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
1235 /* Wait for a digit, no more than ms milliseconds total. */
1237 rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
1238 if ((!rchan) && (outfd < 0) && (ms)) {
1241 ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
1243 } else if (outfd > -1) {
1244 /* The FD we were watching has something waiting */
1252 switch(f->frametype) {
1253 case AST_FRAME_DTMF:
1257 case AST_FRAME_CONTROL:
1258 switch(f->subclass) {
1259 case AST_CONTROL_HANGUP:
1262 case AST_CONTROL_RINGING:
1263 case AST_CONTROL_ANSWER:
1267 ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", f->subclass);
1269 case AST_FRAME_VOICE:
1270 /* Write audio if appropriate */
1272 write(audiofd, f->data, f->datalen);
1278 return 0; /* Time is up */
1281 struct ast_frame *ast_read(struct ast_channel *chan)
1283 struct ast_frame *f = NULL;
1285 #ifdef ZAPTEL_OPTIMIZATIONS
1286 int (*func)(void *);
1291 static struct ast_frame null_frame =
1296 ast_mutex_lock(&chan->lock);
1298 if (ast_do_masquerade(chan)) {
1299 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1303 ast_mutex_unlock(&chan->lock);
1307 /* Stop if we're a zombie or need a soft hangup */
1308 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
1309 if (chan->generator)
1310 ast_deactivate_generator(chan);
1311 ast_mutex_unlock(&chan->lock);
1314 prestate = chan->_state;
1316 if (!ast_test_flag(chan, AST_FLAG_DEFER_DTMF) && !ast_strlen_zero(chan->dtmfq)) {
1317 /* We have DTMF that has been deferred. Return it now */
1318 chan->dtmff.frametype = AST_FRAME_DTMF;
1319 chan->dtmff.subclass = chan->dtmfq[0];
1320 /* Drop first digit */
1321 memmove(chan->dtmfq, chan->dtmfq + 1, sizeof(chan->dtmfq) - 1);
1322 ast_mutex_unlock(&chan->lock);
1323 return &chan->dtmff;
1326 /* Read and ignore anything on the alertpipe, but read only
1327 one sizeof(blah) per frame that we send from it */
1328 if (chan->alertpipe[0] > -1) {
1329 read(chan->alertpipe[0], &blah, sizeof(blah));
1331 #ifdef ZAPTEL_OPTIMIZATIONS
1332 if ((chan->timingfd > -1) && (chan->fdno == AST_MAX_FDS - 2) && ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
1333 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
1335 /* IF we can't get event, assume it's an expired as-per the old interface */
1336 res = ioctl(chan->timingfd, ZT_GETEVENT, &blah);
1338 blah = ZT_EVENT_TIMER_EXPIRED;
1340 if (blah == ZT_EVENT_TIMER_PING) {
1342 ast_log(LOG_NOTICE, "Oooh, there's a PING!\n");
1344 if (!chan->readq || !chan->readq->next) {
1345 /* Acknowledge PONG unless we need it again */
1347 ast_log(LOG_NOTICE, "Sending a PONG!\n");
1349 if (ioctl(chan->timingfd, ZT_TIMERPONG, &blah)) {
1350 ast_log(LOG_WARNING, "Failed to pong timer on '%s': %s\n", chan->name, strerror(errno));
1353 } else if (blah == ZT_EVENT_TIMER_EXPIRED) {
1354 ioctl(chan->timingfd, ZT_TIMERACK, &blah);
1355 func = chan->timingfunc;
1356 data = chan->timingdata;
1357 ast_mutex_unlock(&chan->lock);
1360 ast_log(LOG_DEBUG, "Calling private function\n");
1365 ast_mutex_lock(&chan->lock);
1366 ioctl(chan->timingfd, ZT_TIMERCONFIG, &blah);
1367 chan->timingdata = NULL;
1368 ast_mutex_unlock(&chan->lock);
1373 ast_log(LOG_NOTICE, "No/unknown event '%d' on timer for '%s'?\n", blah, chan->name);
1376 /* Check for pending read queue */
1379 chan->readq = f->next;
1380 /* Interpret hangup and return NULL */
1381 if ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_HANGUP)) {
1386 chan->blocker = pthread_self();
1387 if (ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
1388 if (chan->tech->exception)
1389 f = chan->tech->exception(chan);
1391 ast_log(LOG_WARNING, "Exception flag set on '%s', but no exception handler\n", chan->name);
1394 /* Clear the exception flag */
1395 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
1397 if (chan->tech->read)
1398 f = chan->tech->read(chan);
1400 ast_log(LOG_WARNING, "No read routine on channel %s\n", chan->name);
1404 if (f && (f->frametype == AST_FRAME_VOICE)) {
1405 if (!(f->subclass & chan->nativeformats)) {
1406 /* This frame can't be from the current native formats -- drop it on the
1408 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));
1413 struct ast_channel_spy *spying;
1414 for (spying = chan->spiers; spying; spying=spying->next) {
1415 ast_queue_spy_frame(spying, f, 0);
1418 if (chan->monitor && chan->monitor->read_stream ) {
1419 #ifndef MONITOR_CONSTANT_DELAY
1420 int jump = chan->outsmpl - chan->insmpl - 2 * f->samples;
1422 if (ast_seekstream(chan->monitor->read_stream, jump + f->samples, SEEK_FORCECUR) == -1)
1423 ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
1424 chan->insmpl += jump + 2 * f->samples;
1426 chan->insmpl+= f->samples;
1428 int jump = chan->outsmpl - chan->insmpl;
1429 if (jump - MONITOR_DELAY >= 0) {
1430 if (ast_seekstream(chan->monitor->read_stream, jump - f->samples, SEEK_FORCECUR) == -1)
1431 ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
1432 chan->insmpl += jump;
1434 chan->insmpl += f->samples;
1436 if (ast_writestream(chan->monitor->read_stream, f) < 0)
1437 ast_log(LOG_WARNING, "Failed to write data to channel monitor read stream\n");
1439 if (chan->readtrans) {
1440 f = ast_translate(chan->readtrans, f, 1);
1447 /* Make sure we always return NULL in the future */
1449 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1450 if (chan->generator)
1451 ast_deactivate_generator(chan);
1452 /* End the CDR if appropriate */
1454 ast_cdr_end(chan->cdr);
1455 } else if (ast_test_flag(chan, AST_FLAG_DEFER_DTMF) && f->frametype == AST_FRAME_DTMF) {
1456 if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2)
1457 chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
1459 ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
1461 } else if ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_ANSWER)) {
1462 if (prestate == AST_STATE_UP) {
1463 ast_log(LOG_DEBUG, "Dropping duplicate answer!\n");
1466 /* Answer the CDR */
1467 ast_setstate(chan, AST_STATE_UP);
1468 ast_cdr_answer(chan->cdr);
1471 /* Run any generator sitting on the line */
1472 if (f && (f->frametype == AST_FRAME_VOICE) && chan->generatordata) {
1473 /* Mask generator data temporarily and apply. If there is a timing function, it
1474 will be calling the generator instead */
1477 int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples);
1478 if (chan->timingfunc) {
1479 ast_log(LOG_DEBUG, "Generator got voice, switching to phase locked mode\n");
1480 ast_settimeout(chan, 0, NULL, NULL);
1482 tmp = chan->generatordata;
1483 chan->generatordata = NULL;
1484 generate = chan->generator->generate;
1485 res = generate(chan, tmp, f->datalen, f->samples);
1486 chan->generatordata = tmp;
1488 ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
1489 ast_deactivate_generator(chan);
1491 } else if (f && (f->frametype == AST_FRAME_CNG)) {
1492 if (chan->generator && !chan->timingfunc && (chan->timingfd > -1)) {
1493 ast_log(LOG_DEBUG, "Generator got CNG, switching to zap timed mode\n");
1494 ast_settimeout(chan, 160, generator_force, chan);
1497 if (chan->fin & 0x80000000)
1498 ast_frame_dump(chan->name, f, "<<");
1499 if ((chan->fin & 0x7fffffff) == 0x7fffffff)
1500 chan->fin &= 0x80000000;
1503 ast_mutex_unlock(&chan->lock);
1507 int ast_indicate(struct ast_channel *chan, int condition)
1510 /* Stop if we're a zombie or need a soft hangup */
1511 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
1513 ast_mutex_lock(&chan->lock);
1514 if (chan->tech->indicate)
1515 res = chan->tech->indicate(chan, condition);
1516 ast_mutex_unlock(&chan->lock);
1517 if (!chan->tech->indicate || res) {
1519 * Device does not support (that) indication, lets fake
1520 * it by doing our own tone generation. (PM2002)
1522 if (condition >= 0) {
1523 const struct tone_zone_sound *ts = NULL;
1524 switch (condition) {
1525 case AST_CONTROL_RINGING:
1526 ts = ast_get_indication_tone(chan->zone, "ring");
1528 case AST_CONTROL_BUSY:
1529 ts = ast_get_indication_tone(chan->zone, "busy");
1531 case AST_CONTROL_CONGESTION:
1532 ts = ast_get_indication_tone(chan->zone, "congestion");
1535 if (ts && ts->data[0]) {
1536 ast_log(LOG_DEBUG, "Driver for channel '%s' does not support indication %d, emulating it\n", chan->name, condition);
1537 ast_playtones_start(chan,0,ts->data, 1);
1539 } else if (condition == AST_CONTROL_PROGRESS) {
1540 /* ast_playtones_stop(chan); */
1541 } else if (condition == AST_CONTROL_PROCEEDING) {
1542 /* Do nothing, really */
1543 } else if (condition == AST_CONTROL_HOLD) {
1544 /* Do nothing.... */
1545 } else if (condition == AST_CONTROL_UNHOLD) {
1546 /* Do nothing.... */
1549 ast_log(LOG_WARNING, "Unable to handle indication %d for '%s'\n", condition, chan->name);
1553 else ast_playtones_stop(chan);
1558 int ast_recvchar(struct ast_channel *chan, int timeout)
1561 struct ast_frame *f;
1566 if (ast_check_hangup(chan)) return -1;
1567 res = ast_waitfor(chan,ourto);
1568 if (res <= 0) /* if timeout */
1574 if (f == NULL) return -1; /* if hangup */
1575 if ((f->frametype == AST_FRAME_CONTROL) &&
1576 (f->subclass == AST_CONTROL_HANGUP)) return -1; /* if hangup */
1577 if (f->frametype == AST_FRAME_TEXT) /* if a text frame */
1579 c = *((char *)f->data); /* get the data */
1587 int ast_sendtext(struct ast_channel *chan, char *text)
1590 /* Stop if we're a zombie or need a soft hangup */
1591 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
1593 CHECK_BLOCKING(chan);
1594 if (chan->tech->send_text)
1595 res = chan->tech->send_text(chan, text);
1596 ast_clear_flag(chan, AST_FLAG_BLOCKING);
1600 static int do_senddigit(struct ast_channel *chan, char digit)
1604 if (chan->tech->send_digit)
1605 res = chan->tech->send_digit(chan, digit);
1606 if (!chan->tech->send_digit || res) {
1608 * Device does not support DTMF tones, lets fake
1609 * it by doing our own generation. (PM2002)
1611 static const char* dtmf_tones[] = {
1612 "!941+1336/100,!0/100", /* 0 */
1613 "!697+1209/100,!0/100", /* 1 */
1614 "!697+1336/100,!0/100", /* 2 */
1615 "!697+1477/100,!0/100", /* 3 */
1616 "!770+1209/100,!0/100", /* 4 */
1617 "!770+1336/100,!0/100", /* 5 */
1618 "!770+1477/100,!0/100", /* 6 */
1619 "!852+1209/100,!0/100", /* 7 */
1620 "!852+1336/100,!0/100", /* 8 */
1621 "!852+1477/100,!0/100", /* 9 */
1622 "!697+1633/100,!0/100", /* A */
1623 "!770+1633/100,!0/100", /* B */
1624 "!852+1633/100,!0/100", /* C */
1625 "!941+1633/100,!0/100", /* D */
1626 "!941+1209/100,!0/100", /* * */
1627 "!941+1477/100,!0/100" }; /* # */
1628 if (digit >= '0' && digit <='9')
1629 ast_playtones_start(chan,0,dtmf_tones[digit-'0'], 0);
1630 else if (digit >= 'A' && digit <= 'D')
1631 ast_playtones_start(chan,0,dtmf_tones[digit-'A'+10], 0);
1632 else if (digit == '*')
1633 ast_playtones_start(chan,0,dtmf_tones[14], 0);
1634 else if (digit == '#')
1635 ast_playtones_start(chan,0,dtmf_tones[15], 0);
1638 ast_log(LOG_DEBUG, "Unable to handle DTMF tone '%c' for '%s'\n", digit, chan->name);
1644 int ast_senddigit(struct ast_channel *chan, char digit)
1646 return do_senddigit(chan, digit);
1649 int ast_prod(struct ast_channel *chan)
1651 struct ast_frame a = { AST_FRAME_VOICE };
1653 /* Send an empty audio frame to get things moving */
1654 if (chan->_state != AST_STATE_UP) {
1655 ast_log(LOG_DEBUG, "Prodding channel '%s'\n", chan->name);
1656 a.subclass = chan->rawwriteformat;
1657 a.data = nothing + AST_FRIENDLY_OFFSET;
1659 if (ast_write(chan, &a))
1660 ast_log(LOG_WARNING, "Prodding channel '%s' failed\n", chan->name);
1665 int ast_write_video(struct ast_channel *chan, struct ast_frame *fr)
1668 if (!chan->tech->write_video)
1670 res = ast_write(chan, fr);
1676 int ast_write(struct ast_channel *chan, struct ast_frame *fr)
1679 struct ast_frame *f = NULL;
1680 /* Stop if we're a zombie or need a soft hangup */
1681 ast_mutex_lock(&chan->lock);
1682 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
1683 ast_mutex_unlock(&chan->lock);
1686 /* Handle any pending masquerades */
1688 if (ast_do_masquerade(chan)) {
1689 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1690 ast_mutex_unlock(&chan->lock);
1695 ast_mutex_unlock(&chan->lock);
1698 if (chan->generatordata) {
1699 if (ast_test_flag(chan, AST_FLAG_WRITE_INT))
1700 ast_deactivate_generator(chan);
1702 ast_mutex_unlock(&chan->lock);
1706 if (chan->fout & 0x80000000)
1707 ast_frame_dump(chan->name, fr, ">>");
1708 CHECK_BLOCKING(chan);
1709 switch(fr->frametype) {
1710 case AST_FRAME_CONTROL:
1711 /* XXX Interpret control frames XXX */
1712 ast_log(LOG_WARNING, "Don't know how to handle control frames yet\n");
1714 case AST_FRAME_DTMF:
1715 ast_clear_flag(chan, AST_FLAG_BLOCKING);
1716 ast_mutex_unlock(&chan->lock);
1717 res = do_senddigit(chan,fr->subclass);
1718 ast_mutex_lock(&chan->lock);
1719 CHECK_BLOCKING(chan);
1721 case AST_FRAME_TEXT:
1722 if (chan->tech->send_text)
1723 res = chan->tech->send_text(chan, (char *) fr->data);
1727 case AST_FRAME_HTML:
1728 if (chan->tech->send_html)
1729 res = chan->tech->send_html(chan, fr->subclass, (char *) fr->data, fr->datalen);
1733 case AST_FRAME_VIDEO:
1734 /* XXX Handle translation of video codecs one day XXX */
1735 if (chan->tech->write_video)
1736 res = chan->tech->write_video(chan, fr);
1741 if (chan->tech->write) {
1742 if (chan->writetrans) {
1743 f = ast_translate(chan->writetrans, fr, 0);
1747 res = chan->tech->write(chan, f);
1749 if (f->frametype == AST_FRAME_VOICE && chan->spiers) {
1750 struct ast_channel_spy *spying;
1751 for (spying = chan->spiers; spying; spying=spying->next) {
1752 ast_queue_spy_frame(spying, f, 1);
1756 if( chan->monitor &&
1757 chan->monitor->write_stream &&
1758 f && ( f->frametype == AST_FRAME_VOICE ) ) {
1759 #ifndef MONITOR_CONSTANT_DELAY
1760 int jump = chan->insmpl - chan->outsmpl - 2 * f->samples;
1762 if (ast_seekstream(chan->monitor->write_stream, jump + f->samples, SEEK_FORCECUR) == -1)
1763 ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
1764 chan->outsmpl += jump + 2 * f->samples;
1766 chan->outsmpl += f->samples;
1768 int jump = chan->insmpl - chan->outsmpl;
1769 if (jump - MONITOR_DELAY >= 0) {
1770 if (ast_seekstream(chan->monitor->write_stream, jump - f->samples, SEEK_FORCECUR) == -1)
1771 ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
1772 chan->outsmpl += jump;
1774 chan->outsmpl += f->samples;
1776 if (ast_writestream(chan->monitor->write_stream, f) < 0)
1777 ast_log(LOG_WARNING, "Failed to write data to channel monitor write stream\n");
1785 ast_clear_flag(chan, AST_FLAG_BLOCKING);
1786 /* Consider a write failure to force a soft hangup */
1788 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1790 if ((chan->fout & 0x7fffffff) == 0x7fffffff)
1791 chan->fout &= 0x80000000;
1796 ast_mutex_unlock(&chan->lock);
1800 int ast_set_write_format(struct ast_channel *chan, int fmts)
1806 ast_mutex_lock(&chan->lock);
1807 native = chan->nativeformats;
1810 res = ast_translator_best_choice(&native, &fmt);
1812 ast_log(LOG_NOTICE, "Unable to find a path from %s to %s\n",
1813 ast_getformatname(fmts), ast_getformatname(chan->nativeformats));
1814 ast_mutex_unlock(&chan->lock);
1818 /* Now we have a good choice for both. We'll write using our native format. */
1819 chan->rawwriteformat = native;
1820 /* User perspective is fmt */
1821 chan->writeformat = fmt;
1822 /* Free any write translation we have right now */
1823 if (chan->writetrans)
1824 ast_translator_free_path(chan->writetrans);
1825 /* Build a translation path from the user write format to the raw writing format */
1826 chan->writetrans = ast_translator_build_path(chan->rawwriteformat, chan->writeformat);
1828 ast_log(LOG_DEBUG, "Set channel %s to write format %s\n", chan->name, ast_getformatname(chan->writeformat));
1829 ast_mutex_unlock(&chan->lock);
1833 int ast_set_read_format(struct ast_channel *chan, int fmts)
1839 ast_mutex_lock(&chan->lock);
1840 native = chan->nativeformats;
1842 /* Find a translation path from the native read format to one of the user's read formats */
1843 res = ast_translator_best_choice(&fmt, &native);
1845 ast_log(LOG_NOTICE, "Unable to find a path from %s to %s\n",
1846 ast_getformatname(chan->nativeformats), ast_getformatname(fmts));
1847 ast_mutex_unlock(&chan->lock);
1851 /* Now we have a good choice for both. We'll write using our native format. */
1852 chan->rawreadformat = native;
1853 /* User perspective is fmt */
1854 chan->readformat = fmt;
1855 /* Free any read translation we have right now */
1856 if (chan->readtrans)
1857 ast_translator_free_path(chan->readtrans);
1858 /* Build a translation path from the raw read format to the user reading format */
1859 chan->readtrans = ast_translator_build_path(chan->readformat, chan->rawreadformat);
1861 ast_log(LOG_DEBUG, "Set channel %s to read format %s\n",
1862 chan->name, ast_getformatname(chan->readformat));
1863 ast_mutex_unlock(&chan->lock);
1867 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)
1871 struct ast_channel *chan;
1872 struct ast_frame *f;
1875 chan = ast_request(type, format, data, &cause);
1881 variable = ast_strdupa(oh->variable);
1885 /* FIXME replace this call with strsep NOT*/
1886 while( (var = strtok_r(NULL, "|", &tmp)) ) {
1887 pbx_builtin_setvar( chan, var );
1889 ast_set_callerid(chan, oh->cid_num, oh->cid_name, oh->cid_num);
1890 if (oh->account && *oh->account)
1891 ast_cdr_setaccount(chan, oh->account);
1893 ast_set_callerid(chan, cid_num, cid_name, cid_num);
1895 if (!ast_call(chan, data, 0)) {
1896 while(timeout && (chan->_state != AST_STATE_UP)) {
1897 res = ast_waitfor(chan, timeout);
1899 /* Something not cool, or timed out */
1902 /* If done, break out */
1909 state = AST_CONTROL_HANGUP;
1913 if (f->frametype == AST_FRAME_CONTROL) {
1914 if (f->subclass == AST_CONTROL_RINGING)
1915 state = AST_CONTROL_RINGING;
1916 else if ((f->subclass == AST_CONTROL_BUSY) || (f->subclass == AST_CONTROL_CONGESTION)) {
1917 state = f->subclass;
1920 } else if (f->subclass == AST_CONTROL_ANSWER) {
1921 state = f->subclass;
1924 } else if (f->subclass == AST_CONTROL_PROGRESS) {
1926 } else if (f->subclass == -1) {
1927 /* Ignore -- just stopping indications */
1929 ast_log(LOG_NOTICE, "Don't know what to do with control frame %d\n", f->subclass);
1935 ast_log(LOG_NOTICE, "Unable to call channel %s/%s\n", type, (char *)data);
1937 ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
1939 case AST_CAUSE_BUSY:
1940 state = AST_CONTROL_BUSY;
1942 case AST_CAUSE_CONGESTION:
1943 state = AST_CONTROL_CONGESTION;
1950 if (oh->context && *oh->context)
1951 strncpy(chan->context, oh->context, sizeof(chan->context) - 1);
1952 if (oh->exten && *oh->exten)
1953 strncpy(chan->exten, oh->exten, sizeof(chan->exten) - 1);
1954 chan->priority = oh->priority;
1956 if (chan->_state == AST_STATE_UP)
1957 state = AST_CONTROL_ANSWER;
1961 if (chan && res <= 0) {
1963 chan->cdr = ast_cdr_alloc();
1965 ast_cdr_init(chan->cdr, chan);
1969 snprintf(tmp, 256, "%s/%s", type, (char *)data);
1970 ast_cdr_setapp(chan->cdr,"Dial",tmp);
1971 ast_cdr_update(chan);
1972 ast_cdr_start(chan->cdr);
1973 ast_cdr_end(chan->cdr);
1974 /* If the cause wasn't handled properly */
1975 if (ast_cdr_disposition(chan->cdr,chan->hangupcause))
1976 ast_cdr_failed(chan->cdr);
1978 ast_log(LOG_WARNING, "Unable to create Call Detail Record\n");
1985 struct ast_channel *ast_request_and_dial(const char *type, int format, void *data, int timeout, int *outstate, const char *cidnum, const char *cidname)
1987 return __ast_request_and_dial(type, format, data, timeout, outstate, cidnum, cidname, NULL);
1990 struct ast_channel *ast_request(const char *type, int format, void *data, int *cause)
1992 struct chanlist *chan;
1993 struct ast_channel *c = NULL;
2000 *cause = AST_CAUSE_NOTDEFINED;
2001 if (ast_mutex_lock(&chlock)) {
2002 ast_log(LOG_WARNING, "Unable to lock channel list\n");
2007 if (!strcasecmp(type, chan->tech->type)) {
2008 capabilities = chan->tech->capabilities;
2010 res = ast_translator_best_choice(&fmt, &capabilities);
2012 ast_log(LOG_WARNING, "No translator path exists for channel type %s (native %d) to %d\n", type, chan->tech->capabilities, format);
2013 ast_mutex_unlock(&chlock);
2016 ast_mutex_unlock(&chlock);
2017 if (chan->tech->requester)
2018 c = chan->tech->requester(type, capabilities, data, cause);
2020 if (c->_state == AST_STATE_DOWN) {
2021 manager_event(EVENT_FLAG_CALL, "Newchannel",
2025 "CallerIDName: %s\r\n"
2027 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);
2035 ast_log(LOG_WARNING, "No channel type registered for '%s'\n", type);
2036 *cause = AST_CAUSE_NOSUCHDRIVER;
2038 ast_mutex_unlock(&chlock);
2042 int ast_parse_device_state(char *device)
2044 char name[AST_CHANNEL_NAME] = "";
2046 struct ast_channel *chan;
2048 chan = ast_channel_walk_locked(NULL);
2050 strncpy(name, chan->name, sizeof(name)-1);
2051 ast_mutex_unlock(&chan->lock);
2052 cut = strchr(name,'-');
2055 if (!strcmp(name, device))
2056 return AST_DEVICE_INUSE;
2057 chan = ast_channel_walk_locked(chan);
2059 return AST_DEVICE_UNKNOWN;
2062 int ast_device_state(char *device)
2064 char tech[AST_MAX_EXTENSION] = "";
2066 struct chanlist *chanls;
2069 strncpy(tech, device, sizeof(tech)-1);
2070 number = strchr(tech, '/');
2072 return AST_DEVICE_INVALID;
2077 if (ast_mutex_lock(&chlock)) {
2078 ast_log(LOG_WARNING, "Unable to lock channel list\n");
2083 if (!strcasecmp(tech, chanls->tech->type)) {
2084 ast_mutex_unlock(&chlock);
2085 if (!chanls->tech->devicestate)
2086 return ast_parse_device_state(device);
2088 res = chanls->tech->devicestate(number);
2089 if (res == AST_DEVICE_UNKNOWN)
2090 return ast_parse_device_state(device);
2095 chanls = chanls->next;
2097 ast_mutex_unlock(&chlock);
2098 return AST_DEVICE_INVALID;
2101 int ast_call(struct ast_channel *chan, char *addr, int timeout)
2103 /* Place an outgoing call, but don't wait any longer than timeout ms before returning.
2104 If the remote end does not answer within the timeout, then do NOT hang up, but
2107 /* Stop if we're a zombie or need a soft hangup */
2108 ast_mutex_lock(&chan->lock);
2109 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan))
2110 if (chan->tech->call)
2111 res = chan->tech->call(chan, addr, timeout);
2112 ast_mutex_unlock(&chan->lock);
2116 int ast_transfer(struct ast_channel *chan, char *dest)
2118 /* Place an outgoing call, but don't wait any longer than timeout ms before returning.
2119 If the remote end does not answer within the timeout, then do NOT hang up, but
2122 /* Stop if we're a zombie or need a soft hangup */
2123 ast_mutex_lock(&chan->lock);
2124 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
2125 if (chan->tech->transfer) {
2126 res = chan->tech->transfer(chan, dest);
2132 ast_mutex_unlock(&chan->lock);
2136 int ast_readstring(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders)
2141 /* XXX Merge with full version? XXX */
2142 /* Stop if we're a zombie or need a soft hangup */
2143 if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
2149 d = ast_waitstream(c, AST_DIGIT_ANY);
2153 d = ast_waitfordigit(c, to);
2155 d = ast_waitfordigit(c, to);
2163 if (!strchr(enders, d))
2165 if (strchr(enders, d) || (pos >= len)) {
2175 int ast_readstring_full(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders, int audiofd, int ctrlfd)
2180 /* Stop if we're a zombie or need a soft hangup */
2181 if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
2187 d = ast_waitstream_full(c, AST_DIGIT_ANY, audiofd, ctrlfd);
2191 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
2193 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
2205 if (!strchr(enders, d))
2207 if (strchr(enders, d) || (pos >= len)) {
2217 int ast_channel_supports_html(struct ast_channel *chan)
2219 if (chan->tech->send_html)
2224 int ast_channel_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
2226 if (chan->tech->send_html)
2227 return chan->tech->send_html(chan, subclass, data, datalen);
2231 int ast_channel_sendurl(struct ast_channel *chan, const char *url)
2233 if (chan->tech->send_html)
2234 return chan->tech->send_html(chan, AST_HTML_URL, url, strlen(url) + 1);
2238 int ast_channel_make_compatible(struct ast_channel *chan, struct ast_channel *peer)
2243 ast_mutex_lock(&peer->lock);
2244 peerf = peer->nativeformats;
2245 ast_mutex_unlock(&peer->lock);
2246 ast_mutex_lock(&chan->lock);
2247 chanf = chan->nativeformats;
2248 ast_mutex_unlock(&chan->lock);
2249 res = ast_translator_best_choice(&peerf, &chanf);
2251 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", chan->name, chan->nativeformats, peer->name, peer->nativeformats);
2254 /* Set read format on channel */
2255 res = ast_set_read_format(chan, peerf);
2257 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", chan->name, chanf);
2260 /* Set write format on peer channel */
2261 res = ast_set_write_format(peer, peerf);
2263 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", peer->name, peerf);
2266 /* Now we go the other way */
2267 peerf = peer->nativeformats;
2268 chanf = chan->nativeformats;
2269 res = ast_translator_best_choice(&chanf, &peerf);
2271 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", peer->name, peer->nativeformats, chan->name, chan->nativeformats);
2274 /* Set writeformat on channel */
2275 res = ast_set_write_format(chan, chanf);
2277 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", chan->name, chanf);
2280 /* Set read format on peer channel */
2281 res = ast_set_read_format(peer, chanf);
2283 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", peer->name, peerf);
2289 int ast_channel_masquerade(struct ast_channel *original, struct ast_channel *clone)
2291 struct ast_frame null = { AST_FRAME_NULL, };
2293 if (original == clone) {
2294 ast_log(LOG_WARNING, "Can't masquerade channel '%s' into itself!\n", original->name);
2297 ast_mutex_lock(&original->lock);
2298 while(ast_mutex_trylock(&clone->lock)) {
2299 ast_mutex_unlock(&original->lock);
2301 ast_mutex_lock(&original->lock);
2303 ast_log(LOG_DEBUG, "Planning to masquerade %s into the structure of %s\n",
2304 clone->name, original->name);
2305 if (original->masq) {
2306 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n",
2307 original->masq->name, original->name);
2308 } else if (clone->masqr) {
2309 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n",
2310 clone->name, clone->masqr->name);
2312 original->masq = clone;
2313 clone->masqr = original;
2314 ast_queue_frame(original, &null);
2315 ast_queue_frame(clone, &null);
2316 ast_log(LOG_DEBUG, "Done planning to masquerade %s into the structure of %s\n", original->name, clone->name);
2319 ast_mutex_unlock(&clone->lock);
2320 ast_mutex_unlock(&original->lock);
2324 void ast_change_name(struct ast_channel *chan, char *newname)
2327 strncpy(tmp, chan->name, sizeof(tmp) - 1);
2328 strncpy(chan->name, newname, sizeof(chan->name) - 1);
2329 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", tmp, chan->name, chan->uniqueid);
2332 void ast_channel_inherit_variables(const struct ast_channel *parent, struct ast_channel *child)
2334 struct ast_var_t *current, *newvar;
2337 AST_LIST_TRAVERSE(&parent->varshead, current, entries) {
2340 varname = ast_var_full_name(current);
2344 if (varname[0] == '_') {
2346 if (varname[1] == '_')
2352 newvar = ast_var_assign(&varname[1], ast_var_value(current));
2354 AST_LIST_INSERT_HEAD(&child->varshead, newvar, entries);
2356 ast_log(LOG_DEBUG, "Copying soft-transferable variable %s.\n", ast_var_name(newvar));
2360 newvar = ast_var_assign(ast_var_full_name(current), ast_var_value(current));
2362 AST_LIST_INSERT_HEAD(&child->varshead, newvar, entries);
2364 ast_log(LOG_DEBUG, "Copying hard-transferable variable %s.\n", ast_var_name(newvar));
2369 ast_log(LOG_DEBUG, "Not copying variable %s.\n", ast_var_name(current));
2375 /* Clone channel variables from 'clone' channel into 'original' channel
2376 All variables except those related to app_groupcount are cloned
2377 Variables are actually _removed_ from 'clone' channel, presumably
2378 because it will subsequently be destroyed.
2379 Assumes locks will be in place on both channels when called.
2382 static void clone_variables(struct ast_channel *original, struct ast_channel *clone)
2384 struct ast_var_t *varptr;
2386 /* we need to remove all app_groupcount related variables from the original
2387 channel before merging in the clone's variables; any groups assigned to the
2388 original channel should be released, only those assigned to the clone
2392 AST_LIST_TRAVERSE_SAFE_BEGIN(&original->varshead, varptr, entries) {
2393 if (!strncmp(ast_var_name(varptr), GROUP_CATEGORY_PREFIX, strlen(GROUP_CATEGORY_PREFIX))) {
2394 AST_LIST_REMOVE(&original->varshead, varptr, entries);
2395 ast_var_delete(varptr);
2398 AST_LIST_TRAVERSE_SAFE_END;
2400 /* Append variables from clone channel into original channel */
2401 /* XXX Is this always correct? We have to in order to keep MACROS working XXX */
2402 if (AST_LIST_FIRST(&clone->varshead))
2403 AST_LIST_INSERT_TAIL(&original->varshead, AST_LIST_FIRST(&clone->varshead), entries);
2406 /* Assumes channel will be locked when called */
2407 int ast_do_masquerade(struct ast_channel *original)
2412 struct ast_frame *cur, *prev;
2413 const struct ast_channel_tech *t;
2415 struct ast_callerid tmpcid;
2416 struct ast_channel *clone = original->masq;
2417 int rformat = original->readformat;
2418 int wformat = original->writeformat;
2425 ast_log(LOG_DEBUG, "Actually Masquerading %s(%d) into the structure of %s(%d)\n",
2426 clone->name, clone->_state, original->name, original->_state);
2428 /* XXX This is a seriously wacked out operation. We're essentially putting the guts of
2429 the clone channel into the original channel. Start by killing off the original
2430 channel's backend. I'm not sure we're going to keep this function, because
2431 while the features are nice, the cost is very high in terms of pure nastiness. XXX */
2433 /* We need the clone's lock, too */
2434 ast_mutex_lock(&clone->lock);
2436 ast_log(LOG_DEBUG, "Got clone lock on '%s' at %p\n", clone->name, &clone->lock);
2438 /* Having remembered the original read/write formats, we turn off any translation on either
2440 free_translation(clone);
2441 free_translation(original);
2444 /* Unlink the masquerade */
2445 original->masq = NULL;
2446 clone->masqr = NULL;
2448 /* Save the original name */
2449 strncpy(orig, original->name, sizeof(orig) - 1);
2450 /* Save the new name */
2451 strncpy(newn, clone->name, sizeof(newn) - 1);
2452 /* Create the masq name */
2453 snprintf(masqn, sizeof(masqn), "%s<MASQ>", newn);
2455 /* Copy the name from the clone channel */
2456 strncpy(original->name, newn, sizeof(original->name)-1);
2458 /* Mangle the name of the clone channel */
2459 strncpy(clone->name, masqn, sizeof(clone->name) - 1);
2461 /* Notify any managers of the change, first the masq then the other */
2462 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", newn, masqn, clone->uniqueid);
2463 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", orig, newn, original->uniqueid);
2465 /* Swap the technlogies */
2467 original->tech = clone->tech;
2470 t_pvt = original->tech_pvt;
2471 original->tech_pvt = clone->tech_pvt;
2472 clone->tech_pvt = t_pvt;
2474 /* Swap the readq's */
2475 cur = original->readq;
2476 original->readq = clone->readq;
2479 /* Swap the alertpipes */
2480 for (i = 0; i < 2; i++) {
2481 x = original->alertpipe[i];
2482 original->alertpipe[i] = clone->alertpipe[i];
2483 clone->alertpipe[i] = x;
2486 /* Swap the raw formats */
2487 x = original->rawreadformat;
2488 original->rawreadformat = clone->rawreadformat;
2489 clone->rawreadformat = x;
2490 x = original->rawwriteformat;
2491 original->rawwriteformat = clone->rawwriteformat;
2492 clone->rawwriteformat = x;
2494 /* Save any pending frames on both sides. Start by counting
2495 * how many we're going to need... */
2504 /* If we had any, prepend them to the ones already in the queue, and
2505 * load up the alertpipe */
2507 prev->next = original->readq;
2508 original->readq = clone->readq;
2509 clone->readq = NULL;
2510 if (original->alertpipe[1] > -1) {
2512 write(original->alertpipe[1], &x, sizeof(x));
2515 clone->_softhangup = AST_SOFTHANGUP_DEV;
2518 /* And of course, so does our current state. Note we need not
2519 call ast_setstate since the event manager doesn't really consider
2520 these separate. We do this early so that the clone has the proper
2521 state of the original channel. */
2522 origstate = original->_state;
2523 original->_state = clone->_state;
2524 clone->_state = origstate;
2526 if (clone->tech->fixup){
2527 res = clone->tech->fixup(original, clone);
2529 ast_log(LOG_WARNING, "Fixup failed on channel %s, strange things may happen.\n", clone->name);
2532 /* Start by disconnecting the original's physical side */
2533 if (clone->tech->hangup)
2534 res = clone->tech->hangup(clone);
2536 ast_log(LOG_WARNING, "Hangup failed! Strange things may happen!\n");
2537 ast_mutex_unlock(&clone->lock);
2541 snprintf(zombn, sizeof(zombn), "%s<ZOMBIE>", orig);
2542 /* Mangle the name of the clone channel */
2543 strncpy(clone->name, zombn, sizeof(clone->name) - 1);
2544 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", masqn, zombn, clone->uniqueid);
2546 /* Update the type. */
2547 original->type = clone->type;
2549 /* Keep the same language. */
2550 strncpy(original->language, clone->language, sizeof(original->language));
2552 for (x=0;x<AST_MAX_FDS;x++) {
2553 original->fds[x] = clone->fds[x];
2555 clone_variables(original, clone);
2556 clone->varshead.first = NULL;
2557 /* Presense of ADSI capable CPE follows clone */
2558 original->adsicpe = clone->adsicpe;
2559 /* Bridge remains the same */
2560 /* CDR fields remain the same */
2561 /* XXX What about blocking, softhangup, blocker, and lock and blockproc? XXX */
2562 /* Application and data remain the same */
2563 /* Clone exception becomes real one, as with fdno */
2564 ast_copy_flags(original, clone, AST_FLAG_EXCEPTION);
2565 original->fdno = clone->fdno;
2566 /* Schedule context remains the same */
2567 /* Stream stuff stays the same */
2568 /* Keep the original state. The fixup code will need to work with it most likely */
2570 /* Just swap the whole structures, nevermind the allocations, they'll work themselves
2572 tmpcid = original->cid;
2573 original->cid = clone->cid;
2574 clone->cid = tmpcid;
2576 /* Restore original timing file descriptor */
2577 original->fds[AST_MAX_FDS - 2] = original->timingfd;
2579 /* Our native formats are different now */
2580 original->nativeformats = clone->nativeformats;
2582 /* Context, extension, priority, app data, jump table, remain the same */
2583 /* pvt switches. pbx stays the same, as does next */
2585 /* Set the write format */
2586 ast_set_write_format(original, wformat);
2588 /* Set the read format */
2589 ast_set_read_format(original, rformat);
2591 /* Copy the music class */
2592 strncpy(original->musicclass, clone->musicclass, sizeof(original->musicclass) - 1);
2594 ast_log(LOG_DEBUG, "Putting channel %s in %d/%d formats\n", original->name, wformat, rformat);
2596 /* Okay. Last thing is to let the channel driver know about all this mess, so he
2597 can fix up everything as best as possible */
2598 if (original->tech->fixup) {
2599 res = original->tech->fixup(clone, original);
2601 ast_log(LOG_WARNING, "Driver for '%s' could not fixup channel %s\n",
2602 original->type, original->name);
2603 ast_mutex_unlock(&clone->lock);
2607 ast_log(LOG_WARNING, "Driver '%s' does not have a fixup routine (for %s)! Bad things may happen.\n",
2608 original->type, original->name);
2610 /* Now, at this point, the "clone" channel is totally F'd up. We mark it as
2611 a zombie so nothing tries to touch it. If it's already been marked as a
2612 zombie, then free it now (since it already is considered invalid). */
2613 if (ast_test_flag(clone, AST_FLAG_ZOMBIE)) {
2614 ast_log(LOG_DEBUG, "Destroying clone '%s'\n", clone->name);
2615 ast_mutex_unlock(&clone->lock);
2616 ast_channel_free(clone);
2617 manager_event(EVENT_FLAG_CALL, "Hangup", "Channel: %s\r\n", zombn);
2619 struct ast_frame null_frame = { AST_FRAME_NULL, };
2620 ast_log(LOG_DEBUG, "Released clone lock on '%s'\n", clone->name);
2621 ast_set_flag(clone, AST_FLAG_ZOMBIE);
2622 ast_queue_frame(clone, &null_frame);
2623 ast_mutex_unlock(&clone->lock);
2626 /* Signal any blocker */
2627 if (ast_test_flag(original, AST_FLAG_BLOCKING))
2628 pthread_kill(original->blocker, SIGURG);
2629 ast_log(LOG_DEBUG, "Done Masquerading %s (%d)\n",
2630 original->name, original->_state);
2634 void ast_set_callerid(struct ast_channel *chan, const char *callerid, const char *calleridname, const char *ani)
2637 if (chan->cid.cid_num)
2638 free(chan->cid.cid_num);
2639 if (ast_strlen_zero(callerid))
2640 chan->cid.cid_num = NULL;
2642 chan->cid.cid_num = strdup(callerid);
2645 if (chan->cid.cid_name)
2646 free(chan->cid.cid_name);
2647 if (ast_strlen_zero(calleridname))
2648 chan->cid.cid_name = NULL;
2650 chan->cid.cid_name = strdup(calleridname);
2653 if (chan->cid.cid_ani)
2654 free(chan->cid.cid_ani);
2655 if (ast_strlen_zero(ani))
2656 chan->cid.cid_ani = NULL;
2658 chan->cid.cid_ani = strdup(ani);
2661 ast_cdr_setcid(chan->cdr, chan);
2662 manager_event(EVENT_FLAG_CALL, "Newcallerid",
2665 "CallerIDName: %s\r\n"
2667 chan->name, chan->cid.cid_num ?
2668 chan->cid.cid_num : "<Unknown>",
2669 chan->cid.cid_name ?
2670 chan->cid.cid_name : "<Unknown>",
2674 int ast_setstate(struct ast_channel *chan, int state)
2676 if (chan->_state != state) {
2677 int oldstate = chan->_state;
2678 chan->_state = state;
2679 if (oldstate == AST_STATE_DOWN) {
2680 ast_device_state_changed(chan->name);
2681 manager_event(EVENT_FLAG_CALL, "Newchannel",
2685 "CallerIDName: %s\r\n"
2687 chan->name, ast_state2str(chan->_state),
2688 chan->cid.cid_num ? chan->cid.cid_num : "<unknown>",
2689 chan->cid.cid_name ? chan->cid.cid_name : "<unknown>",
2692 manager_event(EVENT_FLAG_CALL, "Newstate",
2696 "CallerIDName: %s\r\n"
2698 chan->name, ast_state2str(chan->_state),
2699 chan->cid.cid_num ? chan->cid.cid_num : "<unknown>",
2700 chan->cid.cid_name ? chan->cid.cid_name : "<unknown>",
2707 static long tvdiff(struct timeval *now, struct timeval *then)
2710 return (((now->tv_sec * 1000) + now->tv_usec / 1000) - ((then->tv_sec * 1000) + then->tv_usec / 1000));
2712 return (now->tv_sec - then->tv_sec) * 1000 + (now->tv_usec - then->tv_usec) / 1000;
2716 struct ast_channel *ast_bridged_channel(struct ast_channel *chan)
2718 struct ast_channel *bridged;
2719 bridged = chan->_bridge;
2720 if (bridged && bridged->tech->bridged_channel)
2721 bridged = bridged->tech->bridged_channel(chan, bridged);
2725 static void bridge_playfile(struct ast_channel *chan, struct ast_channel *peer, char *sound, int remain)
2727 int res=0, min=0, sec=0,check=0;
2729 check = ast_autoservice_start(peer);
2734 if (remain / 60 > 1) {
2742 if (!strcmp(sound,"timeleft")) {
2743 res = ast_streamfile(chan, "vm-youhave", chan->language);
2744 res = ast_waitstream(chan, "");
2746 res = ast_say_number(chan, min, AST_DIGIT_ANY, chan->language, (char *) NULL);
2747 res = ast_streamfile(chan, "queue-minutes", chan->language);
2748 res = ast_waitstream(chan, "");
2751 res = ast_say_number(chan, sec, AST_DIGIT_ANY, chan->language, (char *) NULL);
2752 res = ast_streamfile(chan, "queue-seconds", chan->language);
2753 res = ast_waitstream(chan, "");
2756 res = ast_streamfile(chan, sound, chan->language);
2757 res = ast_waitstream(chan, "");
2760 check = ast_autoservice_stop(peer);
2763 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)
2765 /* Copy voice back and forth between the two channels. Give the peer
2766 the ability to transfer calls with '#<extension' syntax. */
2767 struct ast_channel *cs[3];
2769 struct ast_frame *f;
2770 struct ast_channel *who = NULL;
2773 int o0nativeformats;
2774 int o1nativeformats;
2775 struct timeval precise_now;
2776 long elapsed_ms=0, time_left_ms=0;
2782 o0nativeformats = c0->nativeformats;
2783 o1nativeformats = c1->nativeformats;
2786 if ((c0->pvt != pvt0) || (c1->pvt != pvt1) ||
2787 (o0nativeformats != c0->nativeformats) ||
2788 (o1nativeformats != c1->nativeformats)) {
2789 /* Check for Masquerade, codec changes, etc */
2794 if (config->timelimit) {
2795 /* If there is a time limit, return now */
2796 gettimeofday(&precise_now,NULL);
2797 elapsed_ms = tvdiff(&precise_now,start_time);
2798 time_left_ms = config->timelimit - elapsed_ms;
2800 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)) {
2804 if (time_left_ms <= 0) {
2808 if (time_left_ms >= 5000 && *playit) {
2815 who = ast_waitfor_n(cs, 2, &to);
2817 ast_log(LOG_DEBUG, "Nobody there, continuing...\n");
2818 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE || c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE) {
2819 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
2820 c0->_softhangup = 0;
2821 if (c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
2822 c1->_softhangup = 0;
2835 ast_log(LOG_DEBUG, "Didn't get a frame from channel: %s\n",who->name);
2839 if ((f->frametype == AST_FRAME_CONTROL) && !(config->flags & AST_BRIDGE_IGNORE_SIGS)) {
2840 if ((f->subclass == AST_CONTROL_HOLD) || (f->subclass == AST_CONTROL_UNHOLD)) {
2841 ast_indicate(who == c0 ? c1 : c0, f->subclass);
2846 ast_log(LOG_DEBUG, "Got a FRAME_CONTROL (%d) frame on channel %s\n", f->subclass, who->name);
2850 if ((f->frametype == AST_FRAME_VOICE) ||
2851 (f->frametype == AST_FRAME_TEXT) ||
2852 (f->frametype == AST_FRAME_VIDEO) ||
2853 (f->frametype == AST_FRAME_IMAGE) ||
2854 (f->frametype == AST_FRAME_HTML) ||
2855 (f->frametype == AST_FRAME_DTMF)) {
2857 if ((f->frametype == AST_FRAME_DTMF) &&
2858 (config->flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))) {
2860 if ((config->flags & AST_BRIDGE_DTMF_CHANNEL_0)) {
2863 /* Take out of conference mode */
2865 ast_log(LOG_DEBUG, "Got AST_BRIDGE_DTMF_CHANNEL_0 on c0 (%s)\n",c0->name);
2871 if (config->flags & AST_BRIDGE_DTMF_CHANNEL_1) {
2875 ast_log(LOG_DEBUG, "Got AST_BRIDGE_DTMF_CHANNEL_1 on c1 (%s)\n",c1->name);
2882 ast_log(LOG_DEBUG, "Read from %s\n", who->name);
2884 ast_log(LOG_DEBUG, "Servicing channel %s twice in a row?\n", last->name);
2888 /* Don't copy packets if there is a generator on either one, since they're
2889 not supposed to be listening anyway */
2898 /* Swap who gets priority */
2906 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)
2908 /* Copy voice back and forth between the two channels. Give the peer
2909 the ability to transfer calls with '#<extension' syntax. */
2910 struct ast_channel *cs[3];
2911 struct ast_channel *who = NULL;
2915 int o0nativeformats;
2916 int o1nativeformats;
2917 struct timeval start_time,precise_now;
2918 long elapsed_ms=0, time_left_ms=0;
2919 int playit=0, playitagain=1, first_time=1;
2922 firstpass = config->firstpass;
2923 config->firstpass = 0;
2926 gettimeofday(&start_time,NULL);
2927 time_left_ms = config->timelimit;
2929 if ((ast_test_flag(&(config->features_caller), AST_FEATURE_PLAY_WARNING)) && config->start_sound && firstpass)
2930 bridge_playfile(c0,c1,config->start_sound,time_left_ms / 1000);
2931 if ((ast_test_flag(&(config->features_callee), AST_FEATURE_PLAY_WARNING)) && config->start_sound && firstpass)
2932 bridge_playfile(c1,c0,config->start_sound,time_left_ms / 1000);
2934 /* Stop if we're a zombie or need a soft hangup */
2935 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))
2938 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n",
2939 c0->name, c0->_bridge->name);
2943 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n",
2944 c1->name, c1->_bridge->name);
2948 /* Keep track of bridge */
2954 manager_event(EVENT_FLAG_CALL, "Link",
2958 "Uniqueid2: %s\r\n",
2959 c0->name, c1->name, c0->uniqueid, c1->uniqueid);
2960 o1nativeformats = c1->nativeformats;
2961 o0nativeformats = c0->nativeformats;
2962 for (/* ever */;;) {
2964 if (config->timelimit) {
2965 gettimeofday(&precise_now,NULL);
2966 elapsed_ms = tvdiff(&precise_now,&start_time);
2967 time_left_ms = config->timelimit - elapsed_ms;
2969 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)) {
2970 /* narrowing down to the end */
2971 if (config->warning_freq == 0) {
2975 } else if (first_time) {
2979 if ((time_left_ms % config->warning_freq) <= 50) {
2984 if (time_left_ms <= 0) {
2985 if ((ast_test_flag(&(config->features_caller), AST_FEATURE_PLAY_WARNING)) && config->end_sound)
2986 bridge_playfile(c0,c1,config->end_sound,0);
2987 if ((ast_test_flag(&(config->features_callee), AST_FEATURE_PLAY_WARNING)) && config->end_sound)
2988 bridge_playfile(c1,c0,config->end_sound,0);
2994 if (time_left_ms >= 5000 && playit) {
2995 if ((ast_test_flag(&(config->features_caller), AST_FEATURE_PLAY_WARNING)) && config->warning_sound && config->play_warning)
2996 bridge_playfile(c0,c1,config->warning_sound,time_left_ms / 1000);
2997 if ((ast_test_flag(&(config->features_callee), AST_FEATURE_PLAY_WARNING)) && config->warning_sound && config->play_warning)
2998 bridge_playfile(c1,c0,config->warning_sound,time_left_ms / 1000);
3004 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE || c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE) {
3005 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
3006 c0->_softhangup = 0;
3007 if (c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
3008 c1->_softhangup = 0;
3011 ast_log(LOG_DEBUG, "Unbridge signal received. Ending native bridge.\n");
3015 /* Stop if we're a zombie or need a soft hangup */
3016 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)) {
3020 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");
3023 if (c0->tech->bridge && config->timelimit==0 &&
3024 (c0->tech->bridge == c1->tech->bridge) && !nativefailed && !c0->monitor && !c1->monitor && !c0->spiers && !c1->spiers) {
3025 /* Looks like they share a bridge code */
3026 if (option_verbose > 2)
3027 ast_verbose(VERBOSE_PREFIX_3 "Attempting native bridge of %s and %s\n", c0->name, c1->name);
3028 ast_set_flag(c0, AST_FLAG_NBRIDGE);
3029 ast_set_flag(c1, AST_FLAG_NBRIDGE);
3030 if (!(res = c0->tech->bridge(c0, c1, config->flags, fo, rc))) {
3033 manager_event(EVENT_FLAG_CALL, "Unlink",
3037 "Uniqueid2: %s\r\n",
3038 c0->name, c1->name, c0->uniqueid, c1->uniqueid);
3039 ast_log(LOG_DEBUG, "Returning from native bridge, channels: %s, %s\n",c0->name ,c1->name);
3040 ast_clear_flag(c0, AST_FLAG_NBRIDGE);
3041 ast_clear_flag(c1, AST_FLAG_NBRIDGE);
3042 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE || c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE) {
3050 ast_clear_flag(c0, AST_FLAG_NBRIDGE);
3051 ast_clear_flag(c1, AST_FLAG_NBRIDGE);
3054 /* If they return non-zero then continue on normally. Let "-2" mean don't worry about
3055 my not wanting to bridge */
3056 if ((res != -2) && (res != -3))
3057 ast_log(LOG_WARNING, "Private bridge between %s and %s failed\n", c0->name, c1->name);
3058 if (res != -3) nativefailed++;
3061 if (((c0->writeformat != c1->readformat) || (c0->readformat != c1->writeformat) || (c0->nativeformats != o0nativeformats) || (c1->nativeformats != o1nativeformats)) &&
3062 !(c0->generator || c1->generator)) {
3063 if (ast_channel_make_compatible(c0, c1)) {
3064 ast_log(LOG_WARNING, "Can't make %s and %s compatible\n", c0->name, c1->name);
3065 manager_event(EVENT_FLAG_CALL, "Unlink",
3069 "Uniqueid2: %s\r\n",
3070 c0->name, c1->name, c0->uniqueid, c1->uniqueid);
3073 o0nativeformats = c0->nativeformats;
3074 o1nativeformats = c1->nativeformats;
3076 res = ast_generic_bridge(&playitagain, &playit, &start_time, c0, c1, config, fo, rc);
3082 manager_event(EVENT_FLAG_CALL, "Unlink",
3086 "Uniqueid2: %s\r\n",
3087 c0->name, c1->name, c0->uniqueid, c1->uniqueid);
3088 ast_log(LOG_DEBUG, "Bridge stops bridging channels %s and %s\n",c0->name,c1->name);