2 * Asterisk -- A telephony toolkit for Linux.
6 * Copyright (C) 1999, Mark Spencer
8 * Mark Spencer <markster@linux-support.net>
10 * This program is free software, distributed under the terms of
11 * the GNU General Public License
22 #include <math.h> /* For PI */
23 #include <asterisk/pbx.h>
24 #include <asterisk/frame.h>
25 #include <asterisk/sched.h>
26 #include <asterisk/options.h>
27 #include <asterisk/channel.h>
28 #include <asterisk/channel_pvt.h>
29 #include <asterisk/logger.h>
30 #include <asterisk/file.h>
31 #include <asterisk/translate.h>
32 #include <asterisk/manager.h>
33 #include <asterisk/chanvars.h>
34 #include <asterisk/linkedlists.h>
35 #include <asterisk/indications.h>
36 #include <asterisk/monitor.h>
37 #include <asterisk/causes.h>
38 #ifdef ZAPTEL_OPTIMIZATIONS
39 #include <sys/ioctl.h>
40 #include <linux/zaptel.h>
42 #error "You need newer zaptel! Please cvs update zaptel"
46 /* uncomment if you have problems with 'monitoring' synchronized files */
48 #define MONITOR_CONSTANT_DELAY
49 #define MONITOR_DELAY 150 * 8 /* 150 ms of MONITORING DELAY */
52 static int shutting_down = 0;
53 static int uniqueint = 0;
55 /* XXX Lock appropriately in more functions XXX */
61 struct ast_channel * (*requester)(char *type, int format, void *data);
62 int (*devicestate)(void *data);
63 struct chanlist *next;
65 struct ast_channel *channels = NULL;
67 /* Protect the channel list (highly unlikely that two things would change
68 it at the same time, but still! */
70 static ast_mutex_t chlock = AST_MUTEX_INITIALIZER;
72 int ast_check_hangup(struct ast_channel *chan)
76 /* if soft hangup flag, return true */
77 if (chan->_softhangup) return 1;
78 /* if no private structure, return true */
79 if (!chan->pvt->pvt) return 1;
80 /* if no hangup scheduled, just return here */
81 if (!chan->whentohangup) return 0;
82 time(&myt); /* get current time */
83 /* return, if not yet */
84 if (chan->whentohangup > myt) return 0;
85 chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
89 static int ast_check_hangup_locked(struct ast_channel *chan)
92 ast_mutex_lock(&chan->lock);
93 res = ast_check_hangup(chan);
94 ast_mutex_unlock(&chan->lock);
98 void ast_begin_shutdown(int hangup)
100 struct ast_channel *c;
103 ast_mutex_lock(&chlock);
106 ast_softhangup(c, AST_SOFTHANGUP_SHUTDOWN);
109 ast_mutex_unlock(&chlock);
113 int ast_active_channels(void)
115 struct ast_channel *c;
117 ast_mutex_lock(&chlock);
123 ast_mutex_unlock(&chlock);
127 void ast_cancel_shutdown(void)
132 int ast_shutting_down(void)
134 return shutting_down;
137 void ast_channel_setwhentohangup(struct ast_channel *chan, time_t offset)
143 chan->whentohangup = myt + offset;
145 chan->whentohangup = 0;
149 int ast_channel_register(char *type, char *description, int capabilities,
150 struct ast_channel *(*requester)(char *type, int format, void *data))
152 return ast_channel_register_ex(type, description, capabilities, requester, NULL);
155 int ast_channel_register_ex(char *type, char *description, int capabilities,
156 struct ast_channel *(*requester)(char *type, int format, void *data),
157 int (*devicestate)(void *data))
159 struct chanlist *chan, *last=NULL;
160 if (ast_mutex_lock(&chlock)) {
161 ast_log(LOG_WARNING, "Unable to lock channel list\n");
166 if (!strcasecmp(type, chan->type)) {
167 ast_log(LOG_WARNING, "Already have a handler for type '%s'\n", type);
168 ast_mutex_unlock(&chlock);
174 chan = malloc(sizeof(struct chanlist));
176 ast_log(LOG_WARNING, "Out of memory\n");
177 ast_mutex_unlock(&chlock);
180 strncpy(chan->type, type, sizeof(chan->type)-1);
181 strncpy(chan->description, description, sizeof(chan->description)-1);
182 chan->capabilities = capabilities;
183 chan->requester = requester;
184 chan->devicestate = devicestate;
191 ast_log(LOG_DEBUG, "Registered handler for '%s' (%s)\n", chan->type, chan->description);
192 else if (option_verbose > 1)
193 ast_verbose( VERBOSE_PREFIX_2 "Registered channel type '%s' (%s)\n", chan->type, chan->description);
194 ast_mutex_unlock(&chlock);
198 char *ast_state2str(int state)
200 /* XXX Not reentrant XXX */
201 static char localtmp[256];
205 case AST_STATE_RESERVED:
207 case AST_STATE_OFFHOOK:
209 case AST_STATE_DIALING:
213 case AST_STATE_RINGING:
220 snprintf(localtmp, sizeof(localtmp), "Unknown (%d)\n", state);
226 int ast_best_codec(int fmts)
228 /* This just our opinion, expressed in code. We are asked to choose
229 the best codec to use, given no information */
233 /* Okay, ulaw is used by all telephony equipment, so start with it */
235 /* Unless of course, you're a silly European, so then prefer ALAW */
237 /* Okay, well, signed linear is easy to translate into other stuff */
239 /* G.726 is standard ADPCM */
241 /* ADPCM has great sound quality and is still pretty easy to translate */
243 /* Okay, we're down to vocoders now, so pick GSM because it's small and easier to
244 translate and sounds pretty good */
246 /* iLBC is not too bad */
248 /* Speex is free, but computationally more expensive than GSM */
250 /* Ick, LPC10 sounds terrible, but at least we have code for it, if you're tacky enough
253 /* G.729a is faster than 723 and slightly less expensive */
255 /* Down to G.723.1 which is proprietary but at least designed for voice */
260 for (x=0;x<sizeof(prefs) / sizeof(prefs[0]); x++)
263 ast_log(LOG_WARNING, "Don't know any of 0x%x formats\n", fmts);
267 struct ast_channel *ast_channel_alloc(int needqueue)
269 struct ast_channel *tmp;
270 struct ast_channel_pvt *pvt;
273 struct varshead *headp;
276 /* If shutting down, don't allocate any new channels */
279 ast_mutex_lock(&chlock);
280 tmp = malloc(sizeof(struct ast_channel));
282 memset(tmp, 0, sizeof(struct ast_channel));
283 pvt = malloc(sizeof(struct ast_channel_pvt));
285 memset(pvt, 0, sizeof(struct ast_channel_pvt));
286 tmp->sched = sched_context_create();
288 for (x=0;x<AST_MAX_FDS - 1;x++)
290 #ifdef ZAPTEL_OPTIMIZATIONS
291 tmp->timingfd = open("/dev/zap/timer", O_RDWR);
292 if (tmp->timingfd > -1) {
293 /* Check if timing interface supports new
296 if (!ioctl(tmp->timingfd, ZT_TIMERPONG, &flags))
303 pipe(pvt->alertpipe)) {
304 ast_log(LOG_WARNING, "Alert pipe creation failed!\n");
311 flags = fcntl(pvt->alertpipe[0], F_GETFL);
312 fcntl(pvt->alertpipe[0], F_SETFL, flags | O_NONBLOCK);
313 flags = fcntl(pvt->alertpipe[1], F_GETFL);
314 fcntl(pvt->alertpipe[1], F_SETFL, flags | O_NONBLOCK);
316 /* Make sure we've got it done right if they don't */
317 pvt->alertpipe[0] = pvt->alertpipe[1] = -1;
318 /* Always watch the alertpipe */
319 tmp->fds[AST_MAX_FDS-1] = pvt->alertpipe[0];
320 /* And timing pipe */
321 tmp->fds[AST_MAX_FDS-2] = tmp->timingfd;
322 strncpy(tmp->name, "**Unknown**", sizeof(tmp->name)-1);
325 tmp->_state = AST_STATE_DOWN;
332 snprintf(tmp->uniqueid, sizeof(tmp->uniqueid), "%li.%d", (long)time(NULL), uniqueint++);
333 headp=&tmp->varshead;
334 ast_mutex_init(&tmp->lock);
335 AST_LIST_HEAD_INIT(headp);
336 tmp->vars=ast_var_assign("tempvar","tempval");
337 AST_LIST_INSERT_HEAD(headp,tmp->vars,entries);
338 strncpy(tmp->context, "default", sizeof(tmp->context)-1);
339 strncpy(tmp->language, defaultlanguage, sizeof(tmp->language)-1);
340 strncpy(tmp->exten, "s", sizeof(tmp->exten)-1);
342 tmp->amaflags = ast_default_amaflags;
343 strncpy(tmp->accountcode, ast_default_accountcode, sizeof(tmp->accountcode)-1);
344 tmp->next = channels;
348 ast_log(LOG_WARNING, "Unable to create schedule context\n");
353 ast_log(LOG_WARNING, "Out of memory\n");
358 ast_log(LOG_WARNING, "Out of memory\n");
359 ast_mutex_unlock(&chlock);
363 int ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin, int lock)
366 struct ast_frame *prev, *cur;
369 /* Build us a copy and free the original one */
372 ast_log(LOG_WARNING, "Unable to duplicate frame\n");
376 ast_mutex_lock(&chan->lock);
378 cur = chan->pvt->readq;
384 /* Allow up to 96 voice frames outstanding, and up to 128 total frames */
385 if (((fin->frametype == AST_FRAME_VOICE) && (qlen > 96)) || (qlen > 128)) {
386 if (fin->frametype != AST_FRAME_VOICE) {
387 ast_log(LOG_WARNING, "Exceptionally long queue length queuing to %s\n", chan->name);
390 ast_log(LOG_DEBUG, "Dropping voice to exceptionally long queue on %s\n", chan->name);
393 ast_mutex_unlock(&chan->lock);
400 chan->pvt->readq = f;
401 if (chan->pvt->alertpipe[1] > -1) {
402 if (write(chan->pvt->alertpipe[1], &blah, sizeof(blah)) != sizeof(blah))
403 ast_log(LOG_WARNING, "Unable to write to alert pipe on %s, frametype/subclass %d/%d (qlen = %d): %s!\n",
404 chan->name, f->frametype, f->subclass, qlen, strerror(errno));
405 #ifdef ZAPTEL_OPTIMIZATIONS
406 } else if (chan->timingfd > -1) {
407 ioctl(chan->timingfd, ZT_TIMERPING, &blah);
409 } else if (chan->blocking) {
410 pthread_kill(chan->blocker, SIGURG);
413 ast_mutex_unlock(&chan->lock);
417 int ast_queue_hangup(struct ast_channel *chan, int lock)
419 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_HANGUP };
420 chan->_softhangup |= AST_SOFTHANGUP_DEV;
421 return ast_queue_frame(chan, &f, lock);
424 int ast_queue_control(struct ast_channel *chan, int control, int lock)
426 struct ast_frame f = { AST_FRAME_CONTROL, };
427 f.subclass = control;
428 return ast_queue_frame(chan, &f, lock);
431 int ast_channel_defer_dtmf(struct ast_channel *chan)
435 pre = chan->deferdtmf;
441 void ast_channel_undefer_dtmf(struct ast_channel *chan)
447 struct ast_channel *ast_channel_walk(struct ast_channel *prev)
449 struct ast_channel *l, *ret=NULL;
450 ast_mutex_lock(&chlock);
453 ast_mutex_unlock(&chlock);
461 ast_mutex_unlock(&chlock);
466 int ast_safe_sleep_conditional( struct ast_channel *chan, int ms,
467 int (*cond)(void*), void *data )
472 if( cond && ((*cond)(data) == 0 ) )
474 ms = ast_waitfor(chan, ms);
487 int ast_safe_sleep(struct ast_channel *chan, int ms)
491 ms = ast_waitfor(chan, ms);
504 void ast_channel_free(struct ast_channel *chan)
506 struct ast_channel *last=NULL, *cur;
508 struct ast_var_t *vardata;
509 struct ast_frame *f, *fp;
510 struct varshead *headp;
511 char name[AST_CHANNEL_NAME];
513 headp=&chan->varshead;
515 ast_mutex_lock(&chlock);
520 last->next = cur->next;
522 channels = cur->next;
529 ast_log(LOG_WARNING, "Unable to find channel in list\n");
531 ast_log(LOG_WARNING, "Channel '%s' may not have been hung up properly\n", chan->name);
533 strncpy(name, chan->name, sizeof(name)-1);
535 /* Stop monitoring */
537 chan->monitor->stop( chan, 0 );
540 /* Free translatosr */
541 if (chan->pvt->readtrans)
542 ast_translator_free_path(chan->pvt->readtrans);
543 if (chan->pvt->writetrans)
544 ast_translator_free_path(chan->pvt->writetrans);
546 ast_log(LOG_WARNING, "PBX may not have been terminated properly on '%s'\n", chan->name);
550 free(chan->callerid);
555 ast_mutex_destroy(&chan->lock);
556 /* Close pipes if appropriate */
557 if ((fd = chan->pvt->alertpipe[0]) > -1)
559 if ((fd = chan->pvt->alertpipe[1]) > -1)
561 if ((fd = chan->timingfd) > -1)
563 f = chan->pvt->readq;
564 chan->pvt->readq = NULL;
571 /* loop over the variables list, freeing all data and deleting list items */
572 /* no need to lock the list, as the channel is already locked */
574 while (!AST_LIST_EMPTY(headp)) { /* List Deletion. */
575 vardata = AST_LIST_FIRST(headp);
576 AST_LIST_REMOVE_HEAD(headp, entries);
577 // printf("deleting var %s=%s\n",ast_var_name(vardata),ast_var_value(vardata));
578 ast_var_delete(vardata);
585 ast_mutex_unlock(&chlock);
587 ast_device_state_changed(name);
590 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
593 struct ast_frame f = { AST_FRAME_NULL };
595 ast_log(LOG_DEBUG, "Soft-Hanging up channel '%s'\n", chan->name);
596 /* Inform channel driver that we need to be hung up, if it cares */
597 chan->_softhangup |= cause;
598 ast_queue_frame(chan, &f, 0);
599 /* Interrupt any select call or such */
601 pthread_kill(chan->blocker, SIGURG);
605 int ast_softhangup(struct ast_channel *chan, int cause)
608 ast_mutex_lock(&chan->lock);
609 res = ast_softhangup_nolock(chan, cause);
610 ast_mutex_unlock(&chan->lock);
614 static void free_translation(struct ast_channel *clone)
616 if (clone->pvt->writetrans)
617 ast_translator_free_path(clone->pvt->writetrans);
618 if (clone->pvt->readtrans)
619 ast_translator_free_path(clone->pvt->readtrans);
620 clone->pvt->writetrans = NULL;
621 clone->pvt->readtrans = NULL;
622 clone->pvt->rawwriteformat = clone->nativeformats;
623 clone->pvt->rawreadformat = clone->nativeformats;
626 int ast_hangup(struct ast_channel *chan)
629 /* Don't actually hang up a channel that will masquerade as someone else, or
630 if someone is going to masquerade as us */
631 ast_mutex_lock(&chan->lock);
633 if (ast_do_masquerade(chan, 1))
634 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
638 ast_log(LOG_WARNING, "%s getting hung up, but someone is trying to masq into us?!?\n", chan->name);
639 ast_mutex_unlock(&chan->lock);
642 /* If this channel is one which will be masqueraded into something,
643 mark it as a zombie already, so we know to free it later */
646 ast_mutex_unlock(&chan->lock);
649 free_translation(chan);
651 ast_stopstream(chan);
653 sched_context_destroy(chan->sched);
654 /* Clear any tone stuff remaining */
655 if (chan->generatordata)
656 chan->generator->release(chan, chan->generatordata);
657 chan->generatordata = NULL;
658 chan->generator = NULL;
660 /* End the CDR if it hasn't already */
661 ast_cdr_end(chan->cdr);
662 /* Post and Free the CDR */
663 ast_cdr_post(chan->cdr);
664 ast_cdr_free(chan->cdr);
666 if (chan->blocking) {
667 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
668 "is blocked by thread %ld in procedure %s! Expect a failure\n",
669 (long)pthread_self(), chan->name, (long)chan->blocker, chan->blockproc);
674 ast_log(LOG_DEBUG, "Hanging up channel '%s'\n", chan->name);
675 if (chan->pvt->hangup)
676 res = chan->pvt->hangup(chan);
679 ast_log(LOG_DEBUG, "Hanging up zombie '%s'\n", chan->name);
681 ast_mutex_unlock(&chan->lock);
682 manager_event(EVENT_FLAG_CALL, "Hangup",
686 chan->name, chan->uniqueid, chan->hangupcause);
687 ast_channel_free(chan);
691 void ast_channel_unregister(char *type)
693 struct chanlist *chan, *last=NULL;
695 ast_log(LOG_DEBUG, "Unregistering channel type '%s'\n", type);
696 if (ast_mutex_lock(&chlock)) {
697 ast_log(LOG_WARNING, "Unable to lock channel list\n");
700 if (option_verbose > 1)
701 ast_verbose( VERBOSE_PREFIX_2 "Unregistered channel type '%s'\n", type);
705 if (!strcasecmp(chan->type, type)) {
707 last->next = chan->next;
709 backends = backends->next;
711 ast_mutex_unlock(&chlock);
717 ast_mutex_unlock(&chlock);
720 int ast_answer(struct ast_channel *chan)
723 /* Stop if we're a zombie or need a soft hangup */
724 if (chan->zombie || ast_check_hangup(chan))
726 switch(chan->_state) {
727 case AST_STATE_RINGING:
729 ast_mutex_lock(&chan->lock);
730 if (chan->pvt->answer)
731 res = chan->pvt->answer(chan);
732 ast_mutex_unlock(&chan->lock);
733 ast_setstate(chan, AST_STATE_UP);
735 ast_cdr_answer(chan->cdr);
740 ast_cdr_answer(chan->cdr);
746 void ast_deactivate_generator(struct ast_channel *chan)
748 if (chan->generatordata) {
749 if (chan->generator && chan->generator->release)
750 chan->generator->release(chan, chan->generatordata);
751 chan->generatordata = NULL;
752 chan->generator = NULL;
753 chan->writeinterrupt = 0;
757 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
759 if (chan->generatordata) {
760 if (chan->generator && chan->generator->release)
761 chan->generator->release(chan, chan->generatordata);
762 chan->generatordata = NULL;
765 if ((chan->generatordata = gen->alloc(chan, params))) {
766 chan->generator = gen;
773 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
775 /* Wait for x amount of time on a file descriptor to have input. */
782 tv.tv_sec = *ms / 1000;
783 tv.tv_usec = (*ms % 1000) * 1000;
788 FD_SET(fds[x], &rfds);
789 FD_SET(fds[x], &efds);
795 res = ast_select(max + 1, &rfds, NULL, &efds, &tv);
797 res = ast_select(max + 1, &rfds, NULL, &efds, NULL);
800 /* Simulate a timeout if we were interrupted */
809 if ((fds[x] > -1) && (FD_ISSET(fds[x], &rfds) || FD_ISSET(fds[x], &efds)) && (winner < 0)) {
811 *exception = FD_ISSET(fds[x], &efds);
815 *ms = tv.tv_sec * 1000 + tv.tv_usec / 1000;
819 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
820 int *exception, int *outfd, int *ms)
822 /* Wait for x amount of time on a file descriptor to have input. */
828 long whentohangup = 0, havewhen = 0, diff;
829 struct ast_channel *winner = NULL;
835 /* Perform any pending masquerades */
837 ast_mutex_lock(&c[x]->lock);
838 if (c[x]->whentohangup) {
841 diff = c[x]->whentohangup - now;
842 if (!havewhen || (diff < whentohangup)) {
848 if (ast_do_masquerade(c[x], 1)) {
849 ast_log(LOG_WARNING, "Masquerade failed\n");
851 ast_mutex_unlock(&c[x]->lock);
855 ast_mutex_unlock(&c[x]->lock);
858 tv.tv_sec = *ms / 1000;
859 tv.tv_usec = (*ms % 1000) * 1000;
862 if ((*ms < 0) || (whentohangup * 1000 < *ms)) {
863 tv.tv_sec = whentohangup;
871 for (y=0;y<AST_MAX_FDS;y++) {
872 if (c[x]->fds[y] > -1) {
873 FD_SET(c[x]->fds[y], &rfds);
874 FD_SET(c[x]->fds[y], &efds);
875 if (c[x]->fds[y] > max)
879 CHECK_BLOCKING(c[x]);
881 for (x=0;x<nfds; x++) {
882 FD_SET(fds[x], &rfds);
883 FD_SET(fds[x], &efds);
887 if ((*ms >= 0) || (havewhen))
888 res = ast_select(max + 1, &rfds, NULL, &efds, &tv);
890 res = ast_select(max + 1, &rfds, NULL, &efds, NULL);
895 /* Simulate a timeout if we were interrupted */
899 /* Just an interrupt */
911 if (havewhen && c[x]->whentohangup && (now > c[x]->whentohangup)) {
912 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
916 for (y=0;y<AST_MAX_FDS;y++) {
917 if (c[x]->fds[y] > -1) {
918 if ((FD_ISSET(c[x]->fds[y], &rfds) || FD_ISSET(c[x]->fds[y], &efds)) && !winner) {
919 /* Set exception flag if appropriate */
920 if (FD_ISSET(c[x]->fds[y], &efds))
928 for (x=0;x<nfds;x++) {
929 if ((FD_ISSET(fds[x], &rfds) || FD_ISSET(fds[x], &efds)) && !winner) {
932 if (FD_ISSET(fds[x], &efds) && exception)
937 *ms = tv.tv_sec * 1000 + tv.tv_usec / 1000;
941 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
943 return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
946 int ast_waitfor(struct ast_channel *c, int ms)
948 struct ast_channel *chan;
950 chan = ast_waitfor_n(&c, 1, &ms);
960 char ast_waitfordigit(struct ast_channel *c, int ms)
962 /* XXX Should I be merged with waitfordigit_full XXX */
965 /* Stop if we're a zombie or need a soft hangup */
966 if (c->zombie || ast_check_hangup(c))
968 /* Wait for a digit, no more than ms milliseconds total. */
969 while(ms && !result) {
970 ms = ast_waitfor(c, ms);
971 if (ms < 0) /* Error */
977 if (f->frametype == AST_FRAME_DTMF)
978 result = f->subclass;
987 int ast_settimeout(struct ast_channel *c, int samples, int (*func)(void *data), void *data)
990 #ifdef ZAPTEL_OPTIMIZATIONS
991 if (c->timingfd > -1) {
996 ast_log(LOG_DEBUG, "Scheduling timer at %d sample intervals\n", samples);
997 res = ioctl(c->timingfd, ZT_TIMERCONFIG, &samples);
998 c->timingfunc = func;
999 c->timingdata = data;
1004 char ast_waitfordigit_full(struct ast_channel *c, int ms, int audio, int ctrl)
1006 struct ast_frame *f;
1008 struct ast_channel *rchan;
1010 /* Stop if we're a zombie or need a soft hangup */
1011 if (c->zombie || ast_check_hangup(c))
1013 /* Wait for a digit, no more than ms milliseconds total. */
1014 while(ms && !result) {
1015 rchan = ast_waitfor_nandfds(&c, 1, &audio, (audio > -1) ? 1 : 0, NULL, &outfd, &ms);
1016 if ((!rchan) && (outfd < 0) && (ms)) /* Error */
1018 else if (outfd > -1) {
1021 /* Read something */
1024 if (f->frametype == AST_FRAME_DTMF)
1025 result = f->subclass;
1034 struct ast_frame *ast_read(struct ast_channel *chan)
1036 struct ast_frame *f = NULL;
1038 #ifdef ZAPTEL_OPTIMIZATIONS
1039 int (*func)(void *);
1043 static struct ast_frame null_frame =
1048 ast_mutex_lock(&chan->lock);
1050 if (ast_do_masquerade(chan, 1)) {
1051 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1055 ast_mutex_unlock(&chan->lock);
1059 /* Stop if we're a zombie or need a soft hangup */
1060 if (chan->zombie || ast_check_hangup(chan)) {
1061 if (chan->generator)
1062 ast_deactivate_generator(chan);
1063 ast_mutex_unlock(&chan->lock);
1067 if (!chan->deferdtmf && strlen(chan->dtmfq)) {
1068 /* We have DTMF that has been deferred. Return it now */
1069 chan->dtmff.frametype = AST_FRAME_DTMF;
1070 chan->dtmff.subclass = chan->dtmfq[0];
1071 /* Drop first digit */
1072 memmove(chan->dtmfq, chan->dtmfq + 1, sizeof(chan->dtmfq) - 1);
1073 ast_mutex_unlock(&chan->lock);
1074 return &chan->dtmff;
1077 /* Read and ignore anything on the alertpipe, but read only
1078 one sizeof(blah) per frame that we send from it */
1079 if (chan->pvt->alertpipe[0] > -1) {
1080 read(chan->pvt->alertpipe[0], &blah, sizeof(blah));
1082 #ifdef ZAPTEL_OPTIMIZATIONS
1083 if ((chan->timingfd > -1) && (chan->fdno == AST_MAX_FDS - 2) && chan->exception) {
1084 chan->exception = 0;
1086 /* IF we can't get event, assume it's an expired as-per the old interface */
1087 res = ioctl(chan->timingfd, ZT_GETEVENT, &blah);
1089 blah = ZT_EVENT_TIMER_EXPIRED;
1091 if (blah == ZT_EVENT_TIMER_PING) {
1093 ast_log(LOG_NOTICE, "Oooh, there's a PING!\n");
1095 if (!chan->pvt->readq || !chan->pvt->readq->next) {
1096 /* Acknowledge PONG unless we need it again */
1098 ast_log(LOG_NOTICE, "Sending a PONG!\n");
1100 if (ioctl(chan->timingfd, ZT_TIMERPONG, &blah)) {
1101 ast_log(LOG_WARNING, "Failed to pong timer on '%s': %s\n", chan->name, strerror(errno));
1104 } else if (blah == ZT_EVENT_TIMER_EXPIRED) {
1105 ioctl(chan->timingfd, ZT_TIMERACK, &blah);
1106 func = chan->timingfunc;
1107 data = chan->timingdata;
1108 ast_mutex_unlock(&chan->lock);
1111 ast_log(LOG_DEBUG, "Calling private function\n");
1116 ast_mutex_lock(&chan->lock);
1117 ioctl(chan->timingfd, ZT_TIMERCONFIG, &blah);
1118 chan->timingdata = NULL;
1119 ast_mutex_unlock(&chan->lock);
1124 ast_log(LOG_NOTICE, "No/unknown event '%d' on timer for '%s'?\n", blah, chan->name);
1127 /* Check for pending read queue */
1128 if (chan->pvt->readq) {
1129 f = chan->pvt->readq;
1130 chan->pvt->readq = f->next;
1131 /* Interpret hangup and return NULL */
1132 if ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_HANGUP)) {
1137 chan->blocker = pthread_self();
1138 if (chan->exception) {
1139 if (chan->pvt->exception)
1140 f = chan->pvt->exception(chan);
1142 ast_log(LOG_WARNING, "Exception flag set on '%s', but no exception handler\n", chan->name);
1145 /* Clear the exception flag */
1146 chan->exception = 0;
1148 if (chan->pvt->read)
1149 f = chan->pvt->read(chan);
1151 ast_log(LOG_WARNING, "No read routine on channel %s\n", chan->name);
1155 if (f && (f->frametype == AST_FRAME_VOICE)) {
1156 if (!(f->subclass & chan->nativeformats)) {
1157 /* This frame can't be from the current native formats -- drop it on the
1159 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));
1163 if (chan->monitor && chan->monitor->read_stream ) {
1164 #ifndef MONITOR_CONSTANT_DELAY
1165 int jump = chan->outsmpl - chan->insmpl - 2 * f->samples;
1167 if (ast_seekstream(chan->monitor->read_stream, jump + f->samples, SEEK_FORCECUR) == -1)
1168 ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
1169 chan->insmpl += jump + 2 * f->samples;
1171 chan->insmpl+= f->samples;
1173 int jump = chan->outsmpl - chan->insmpl;
1174 if (jump - MONITOR_DELAY >= 0) {
1175 if (ast_seekstream(chan->monitor->read_stream, jump - f->samples, SEEK_FORCECUR) == -1)
1176 ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
1177 chan->insmpl += jump;
1179 chan->insmpl += f->samples;
1181 if (ast_writestream(chan->monitor->read_stream, f) < 0)
1182 ast_log(LOG_WARNING, "Failed to write data to channel monitor read stream\n");
1184 if (chan->pvt->readtrans) {
1185 f = ast_translate(chan->pvt->readtrans, f, 1);
1192 /* Make sure we always return NULL in the future */
1194 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1195 if (chan->generator)
1196 ast_deactivate_generator(chan);
1197 /* End the CDR if appropriate */
1199 ast_cdr_end(chan->cdr);
1200 } else if (chan->deferdtmf && f->frametype == AST_FRAME_DTMF) {
1201 if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2)
1202 chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
1204 ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
1206 } else if ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_ANSWER)) {
1207 /* Answer the CDR */
1208 ast_setstate(chan, AST_STATE_UP);
1209 ast_cdr_answer(chan->cdr);
1211 ast_mutex_unlock(&chan->lock);
1213 /* Run any generator sitting on the line */
1214 if (f && (f->frametype == AST_FRAME_VOICE) && chan->generatordata) {
1215 /* Mask generator data temporarily */
1218 tmp = chan->generatordata;
1219 chan->generatordata = NULL;
1220 res = chan->generator->generate(chan, tmp, f->datalen, f->samples);
1221 chan->generatordata = tmp;
1223 ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
1224 ast_deactivate_generator(chan);
1227 if (chan->fin & 0x80000000)
1228 ast_frame_dump(chan->name, f, "<<");
1229 if ((chan->fin & 0x7fffffff) == 0x7fffffff)
1230 chan->fin &= 0x80000000;
1236 int ast_indicate(struct ast_channel *chan, int condition)
1239 /* Stop if we're a zombie or need a soft hangup */
1240 if (chan->zombie || ast_check_hangup(chan))
1242 ast_mutex_lock(&chan->lock);
1243 if (chan->pvt->indicate)
1244 res = chan->pvt->indicate(chan, condition);
1245 ast_mutex_unlock(&chan->lock);
1246 if (!chan->pvt->indicate || res) {
1248 * Device does not support (that) indication, lets fake
1249 * it by doing our own tone generation. (PM2002)
1251 if (condition >= 0) {
1252 const struct tone_zone_sound *ts = NULL;
1253 switch (condition) {
1254 case AST_CONTROL_RINGING:
1255 ts = ast_get_indication_tone(chan->zone, "ring");
1257 case AST_CONTROL_BUSY:
1258 ts = ast_get_indication_tone(chan->zone, "busy");
1260 case AST_CONTROL_CONGESTION:
1261 ts = ast_get_indication_tone(chan->zone, "congestion");
1264 if (ts && ts->data[0]) {
1265 ast_log(LOG_DEBUG, "Driver for channel '%s' does not support indication %d, emulating it\n", chan->name, condition);
1266 ast_playtones_start(chan,0,ts->data, 1);
1268 } else if (condition == AST_CONTROL_PROGRESS) {
1269 /* ast_playtones_stop(chan); */
1272 ast_log(LOG_WARNING, "Unable to handle indication %d for '%s'\n", condition, chan->name);
1276 else ast_playtones_stop(chan);
1281 int ast_recvchar(struct ast_channel *chan, int timeout)
1284 struct ast_frame *f;
1289 if (ast_check_hangup(chan)) return -1;
1290 res = ast_waitfor(chan,ourto);
1291 if (res <= 0) /* if timeout */
1297 if (f == NULL) return -1; /* if hangup */
1298 if ((f->frametype == AST_FRAME_CONTROL) &&
1299 (f->subclass == AST_CONTROL_HANGUP)) return -1; /* if hangup */
1300 if (f->frametype == AST_FRAME_TEXT) /* if a text frame */
1302 c = *((char *)f->data); /* get the data */
1310 int ast_sendtext(struct ast_channel *chan, char *text)
1313 /* Stop if we're a zombie or need a soft hangup */
1314 if (chan->zombie || ast_check_hangup(chan))
1316 CHECK_BLOCKING(chan);
1317 if (chan->pvt->send_text)
1318 res = chan->pvt->send_text(chan, text);
1323 static int do_senddigit(struct ast_channel *chan, char digit)
1327 if (chan->pvt->send_digit)
1328 res = chan->pvt->send_digit(chan, digit);
1329 if (!chan->pvt->send_digit || res) {
1331 * Device does not support DTMF tones, lets fake
1332 * it by doing our own generation. (PM2002)
1334 static const char* dtmf_tones[] = {
1335 "!941+1336/100,!0/100", /* 0 */
1336 "!697+1209/100,!0/100", /* 1 */
1337 "!697+1336/100,!0/100", /* 2 */
1338 "!697+1477/100,!0/100", /* 3 */
1339 "!770+1209/100,!0/100", /* 4 */
1340 "!770+1336/100,!0/100", /* 5 */
1341 "!770+1477/100,!0/100", /* 6 */
1342 "!852+1209/100,!0/100", /* 7 */
1343 "!852+1336/100,!0/100", /* 8 */
1344 "!852+1477/100,!0/100", /* 9 */
1345 "!697+1633/100,!0/100", /* A */
1346 "!770+1633/100,!0/100", /* B */
1347 "!852+1633/100,!0/100", /* C */
1348 "!941+1633/100,!0/100", /* D */
1349 "!941+1209/100,!0/100", /* * */
1350 "!941+1477/100,!0/100" }; /* # */
1351 if (digit >= '0' && digit <='9')
1352 ast_playtones_start(chan,0,dtmf_tones[digit-'0'], 0);
1353 else if (digit >= 'A' && digit <= 'D')
1354 ast_playtones_start(chan,0,dtmf_tones[digit-'A'+10], 0);
1355 else if (digit == '*')
1356 ast_playtones_start(chan,0,dtmf_tones[14], 0);
1357 else if (digit == '#')
1358 ast_playtones_start(chan,0,dtmf_tones[15], 0);
1361 ast_log(LOG_WARNING, "Unable to handle DTMF tone '%c' for '%s'\n", digit, chan->name);
1368 int ast_prod(struct ast_channel *chan)
1370 struct ast_frame a = { AST_FRAME_VOICE };
1372 /* Send an empty audio frame to get things moving */
1373 if (chan->_state != AST_STATE_UP) {
1374 ast_log(LOG_DEBUG, "Prodding channel '%s'\n", chan->name);
1375 a.subclass = chan->pvt->rawwriteformat;
1376 a.data = nothing + AST_FRIENDLY_OFFSET;
1377 if (ast_write(chan, &a))
1378 ast_log(LOG_WARNING, "Prodding channel '%s' failed\n", chan->name);
1383 int ast_write_video(struct ast_channel *chan, struct ast_frame *fr)
1386 if (!chan->pvt->write_video)
1388 res = ast_write(chan, fr);
1394 int ast_write(struct ast_channel *chan, struct ast_frame *fr)
1397 struct ast_frame *f = NULL;
1398 /* Stop if we're a zombie or need a soft hangup */
1399 ast_mutex_lock(&chan->lock);
1400 if (chan->zombie || ast_check_hangup(chan)) {
1401 ast_mutex_unlock(&chan->lock);
1404 /* Handle any pending masquerades */
1406 if (ast_do_masquerade(chan, 1)) {
1407 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1408 ast_mutex_unlock(&chan->lock);
1413 ast_mutex_unlock(&chan->lock);
1416 if (chan->generatordata) {
1417 if (chan->writeinterrupt)
1418 ast_deactivate_generator(chan);
1420 ast_mutex_unlock(&chan->lock);
1424 if (chan->fout & 0x80000000)
1425 ast_frame_dump(chan->name, fr, ">>");
1426 CHECK_BLOCKING(chan);
1427 switch(fr->frametype) {
1428 case AST_FRAME_CONTROL:
1429 /* XXX Interpret control frames XXX */
1430 ast_log(LOG_WARNING, "Don't know how to handle control frames yet\n");
1432 case AST_FRAME_DTMF:
1434 ast_mutex_unlock(&chan->lock);
1435 res = do_senddigit(chan,fr->subclass);
1436 ast_mutex_lock(&chan->lock);
1437 CHECK_BLOCKING(chan);
1439 case AST_FRAME_TEXT:
1440 if (chan->pvt->send_text)
1441 res = chan->pvt->send_text(chan, (char *) fr->data);
1443 case AST_FRAME_VIDEO:
1444 /* XXX Handle translation of video codecs one day XXX */
1445 if (chan->pvt->write_video)
1446 res = chan->pvt->write_video(chan, fr);
1451 if (chan->pvt->write) {
1452 if (chan->pvt->writetrans) {
1453 f = ast_translate(chan->pvt->writetrans, fr, 0);
1457 res = chan->pvt->write(chan, f);
1458 if( chan->monitor &&
1459 chan->monitor->write_stream &&
1460 f && ( f->frametype == AST_FRAME_VOICE ) ) {
1461 #ifndef MONITOR_CONSTANT_DELAY
1462 int jump = chan->insmpl - chan->outsmpl - 2 * f->samples;
1464 if (ast_seekstream(chan->monitor->write_stream, jump + f->samples, SEEK_FORCECUR) == -1)
1465 ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
1466 chan->outsmpl += jump + 2 * f->samples;
1468 chan->outsmpl += f->samples;
1470 int jump = chan->insmpl - chan->outsmpl;
1471 if (jump - MONITOR_DELAY >= 0) {
1472 if (ast_seekstream(chan->monitor->write_stream, jump - f->samples, SEEK_FORCECUR) == -1)
1473 ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
1474 chan->outsmpl += jump;
1476 chan->outsmpl += f->samples;
1478 if (ast_writestream(chan->monitor->write_stream, f) < 0)
1479 ast_log(LOG_WARNING, "Failed to write data to channel monitor write stream\n");
1488 /* Consider a write failure to force a soft hangup */
1490 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1492 if ((chan->fout & 0x7fffffff) == 0x7fffffff)
1493 chan->fout &= 0x80000000;
1498 ast_mutex_unlock(&chan->lock);
1502 int ast_set_write_format(struct ast_channel *chan, int fmts, int needlock)
1509 ast_mutex_lock(&chan->lock);
1510 native = chan->nativeformats;
1513 res = ast_translator_best_choice(&native, &fmt);
1515 ast_log(LOG_NOTICE, "Unable to find a path from %s to %s\n",
1516 ast_getformatname(fmts), ast_getformatname(chan->nativeformats));
1518 ast_mutex_unlock(&chan->lock);
1522 /* Now we have a good choice for both. We'll write using our native format. */
1523 chan->pvt->rawwriteformat = native;
1524 /* User perspective is fmt */
1525 chan->writeformat = fmt;
1526 /* Free any write translation we have right now */
1527 if (chan->pvt->writetrans)
1528 ast_translator_free_path(chan->pvt->writetrans);
1529 /* Build a translation path from the user write format to the raw writing format */
1530 chan->pvt->writetrans = ast_translator_build_path(chan->pvt->rawwriteformat, chan->writeformat);
1532 ast_log(LOG_DEBUG, "Set channel %s to write format %s\n", chan->name, ast_getformatname(chan->writeformat));
1534 ast_mutex_unlock(&chan->lock);
1538 int ast_set_read_format(struct ast_channel *chan, int fmts, int needlock)
1545 ast_mutex_lock(&chan->lock);
1546 native = chan->nativeformats;
1548 /* Find a translation path from the native read format to one of the user's read formats */
1549 res = ast_translator_best_choice(&fmt, &native);
1551 ast_log(LOG_NOTICE, "Unable to find a path from %s to %s\n",
1552 ast_getformatname(chan->nativeformats), ast_getformatname(fmts));
1554 ast_mutex_unlock(&chan->lock);
1558 /* Now we have a good choice for both. We'll write using our native format. */
1559 chan->pvt->rawreadformat = native;
1560 /* User perspective is fmt */
1561 chan->readformat = fmt;
1562 /* Free any read translation we have right now */
1563 if (chan->pvt->readtrans)
1564 ast_translator_free_path(chan->pvt->readtrans);
1565 /* Build a translation path from the raw read format to the user reading format */
1566 chan->pvt->readtrans = ast_translator_build_path(chan->readformat, chan->pvt->rawreadformat);
1568 ast_log(LOG_DEBUG, "Set channel %s to read format %s\n",
1569 chan->name, ast_getformatname(chan->readformat));
1571 ast_mutex_unlock(&chan->lock);
1575 struct ast_channel *__ast_request_and_dial(char *type, int format, void *data, int timeout, int *outstate, char *callerid, struct outgoing_helper *oh)
1578 struct ast_channel *chan;
1579 struct ast_frame *f;
1581 chan = ast_request(type, format, data);
1587 /* FIXME replace this call with strsep NOT*/
1588 while( (var = strtok_r(NULL, "|", &tmp)) ) {
1589 pbx_builtin_setvar( chan, var );
1591 if (oh->callerid && *oh->callerid)
1592 ast_set_callerid(chan, oh->callerid, 1);
1593 if (oh->account && *oh->account)
1594 ast_cdr_setaccount(chan, oh->account);
1596 if (callerid && strlen(callerid))
1597 ast_set_callerid(chan, callerid, 1);
1599 if (!ast_call(chan, data, 0)) {
1600 while(timeout && (chan->_state != AST_STATE_UP)) {
1601 res = ast_waitfor(chan, timeout);
1603 /* Something not cool, or timed out */
1606 /* If done, break out */
1613 state = AST_CONTROL_HANGUP;
1617 if (f->frametype == AST_FRAME_CONTROL) {
1618 if (f->subclass == AST_CONTROL_RINGING)
1619 state = AST_CONTROL_RINGING;
1620 else if ((f->subclass == AST_CONTROL_BUSY) || (f->subclass == AST_CONTROL_CONGESTION)) {
1621 state = f->subclass;
1624 } else if (f->subclass == AST_CONTROL_ANSWER) {
1625 state = f->subclass;
1628 } else if (f->subclass == -1) {
1629 /* Ignore -- just stopping indications */
1631 ast_log(LOG_NOTICE, "Don't know what to do with control frame %d\n", f->subclass);
1637 ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
1639 ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
1643 if (oh->context && *oh->context)
1644 strncpy(chan->context, oh->context, sizeof(chan->context) - 1);
1645 if (oh->exten && *oh->exten)
1646 strncpy(chan->exten, oh->exten, sizeof(chan->exten) - 1);
1647 chan->priority = oh->priority;
1649 if (chan->_state == AST_STATE_UP)
1650 state = AST_CONTROL_ANSWER;
1654 if (chan && res <= 0) {
1656 chan->cdr = ast_cdr_alloc();
1658 ast_cdr_init(chan->cdr, chan);
1662 sprintf(tmp, "%s/%s",type,(char *)data);
1663 ast_cdr_setapp(chan->cdr,"Dial",tmp);
1664 ast_cdr_update(chan);
1665 ast_cdr_start(chan->cdr);
1666 ast_cdr_end(chan->cdr);
1667 /* If the cause wasn't handled properly */
1668 if (ast_cdr_disposition(chan->cdr,chan->hangupcause))
1669 ast_cdr_failed(chan->cdr);
1671 ast_log(LOG_WARNING, "Unable to create Call Detail Record\n");
1678 struct ast_channel *ast_request_and_dial(char *type, int format, void *data, int timeout, int *outstate, char *callerid)
1680 return __ast_request_and_dial(type, format, data, timeout, outstate, callerid, NULL);
1683 struct ast_channel *ast_request(char *type, int format, void *data)
1685 struct chanlist *chan;
1686 struct ast_channel *c = NULL;
1690 if (ast_mutex_lock(&chlock)) {
1691 ast_log(LOG_WARNING, "Unable to lock channel list\n");
1696 if (!strcasecmp(type, chan->type)) {
1697 capabilities = chan->capabilities;
1699 res = ast_translator_best_choice(&fmt, &capabilities);
1701 ast_log(LOG_WARNING, "No translator path exists for channel type %s (native %d) to %d\n", type, chan->capabilities, format);
1702 ast_mutex_unlock(&chlock);
1705 ast_mutex_unlock(&chlock);
1706 if (chan->requester)
1707 c = chan->requester(type, capabilities, data);
1709 if (c->_state == AST_STATE_DOWN) {
1710 manager_event(EVENT_FLAG_CALL, "Newchannel",
1715 c->name, ast_state2str(c->_state), c->callerid ? c->callerid : "<unknown>", c->uniqueid);
1723 ast_log(LOG_WARNING, "No channel type registered for '%s'\n", type);
1724 ast_mutex_unlock(&chlock);
1728 int ast_parse_device_state(char *device)
1730 char name[AST_CHANNEL_NAME] = "";
1732 struct ast_channel *chan;
1734 chan = ast_channel_walk(NULL);
1736 strncpy(name, chan->name, sizeof(name)-1);
1737 cut = strchr(name,'-');
1740 if (!strcmp(name, device))
1741 return AST_DEVICE_INUSE;
1742 chan = ast_channel_walk(chan);
1744 return AST_DEVICE_UNKNOWN;
1747 int ast_device_state(char *device)
1749 char tech[AST_MAX_EXTENSION] = "";
1751 struct chanlist *chanls;
1754 strncpy(tech, device, sizeof(tech)-1);
1755 number = strchr(tech, '/');
1757 return AST_DEVICE_INVALID;
1762 if (ast_mutex_lock(&chlock)) {
1763 ast_log(LOG_WARNING, "Unable to lock channel list\n");
1768 if (!strcasecmp(tech, chanls->type)) {
1769 ast_mutex_unlock(&chlock);
1770 if (!chanls->devicestate)
1771 return ast_parse_device_state(device);
1773 res = chanls->devicestate(number);
1774 if (res == AST_DEVICE_UNKNOWN)
1775 return ast_parse_device_state(device);
1780 chanls = chanls->next;
1782 ast_mutex_unlock(&chlock);
1783 return AST_DEVICE_INVALID;
1786 int ast_call(struct ast_channel *chan, char *addr, int timeout)
1788 /* Place an outgoing call, but don't wait any longer than timeout ms before returning.
1789 If the remote end does not answer within the timeout, then do NOT hang up, but
1792 /* Stop if we're a zombie or need a soft hangup */
1793 ast_mutex_lock(&chan->lock);
1794 if (!chan->zombie && !ast_check_hangup(chan))
1795 if (chan->pvt->call)
1796 res = chan->pvt->call(chan, addr, timeout);
1797 ast_mutex_unlock(&chan->lock);
1801 int ast_transfer(struct ast_channel *chan, char *dest)
1803 /* Place an outgoing call, but don't wait any longer than timeout ms before returning.
1804 If the remote end does not answer within the timeout, then do NOT hang up, but
1807 /* Stop if we're a zombie or need a soft hangup */
1808 ast_mutex_lock(&chan->lock);
1809 if (!chan->zombie && !ast_check_hangup(chan)) {
1810 if (chan->pvt->transfer) {
1811 res = chan->pvt->transfer(chan, dest);
1817 ast_mutex_unlock(&chan->lock);
1821 int ast_readstring(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders)
1826 /* XXX Merge with full version? XXX */
1827 /* Stop if we're a zombie or need a soft hangup */
1828 if (c->zombie || ast_check_hangup(c))
1834 d = ast_waitstream(c, AST_DIGIT_ANY);
1838 d = ast_waitfordigit(c, to);
1840 d = ast_waitfordigit(c, to);
1848 if (!strchr(enders, d))
1850 if (strchr(enders, d) || (pos >= len)) {
1860 int ast_readstring_full(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders, int audiofd, int ctrlfd)
1865 /* Stop if we're a zombie or need a soft hangup */
1866 if (c->zombie || ast_check_hangup(c))
1872 d = ast_waitstream_full(c, AST_DIGIT_ANY, audiofd, ctrlfd);
1876 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
1878 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
1890 if (!strchr(enders, d))
1892 if (strchr(enders, d) || (pos >= len)) {
1902 int ast_channel_supports_html(struct ast_channel *chan)
1904 if (chan->pvt->send_html)
1909 int ast_channel_sendhtml(struct ast_channel *chan, int subclass, char *data, int datalen)
1911 if (chan->pvt->send_html)
1912 return chan->pvt->send_html(chan, subclass, data, datalen);
1916 int ast_channel_sendurl(struct ast_channel *chan, char *url)
1918 if (chan->pvt->send_html)
1919 return chan->pvt->send_html(chan, AST_HTML_URL, url, strlen(url) + 1);
1923 int ast_channel_make_compatible(struct ast_channel *chan, struct ast_channel *peer)
1928 ast_mutex_lock(&peer->lock);
1929 peerf = peer->nativeformats;
1930 ast_mutex_unlock(&peer->lock);
1931 ast_mutex_lock(&chan->lock);
1932 chanf = chan->nativeformats;
1933 ast_mutex_unlock(&chan->lock);
1934 res = ast_translator_best_choice(&peerf, &chanf);
1936 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", chan->name, chan->nativeformats, peer->name, peer->nativeformats);
1939 /* Set read format on channel */
1940 res = ast_set_read_format(chan, peerf, 1);
1942 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", chan->name, chanf);
1945 /* Set write format on peer channel */
1946 res = ast_set_write_format(peer, peerf, 1);
1948 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", peer->name, peerf);
1951 /* Now we go the other way */
1952 peerf = peer->nativeformats;
1953 chanf = chan->nativeformats;
1954 res = ast_translator_best_choice(&chanf, &peerf);
1956 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", peer->name, peer->nativeformats, chan->name, chan->nativeformats);
1959 /* Set writeformat on channel */
1960 res = ast_set_write_format(chan, chanf, 1);
1962 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", chan->name, chanf);
1965 /* Set read format on peer channel */
1966 res = ast_set_read_format(peer, chanf, 1);
1968 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", peer->name, peerf);
1974 int ast_channel_masquerade(struct ast_channel *original, struct ast_channel *clone)
1976 struct ast_frame null = { AST_FRAME_NULL, };
1977 ast_log(LOG_DEBUG, "Planning to masquerade %s into the structure of %s\n",
1978 clone->name, original->name);
1979 if (original->masq) {
1980 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n",
1981 original->masq->name, original->name);
1985 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n",
1986 clone->name, clone->masqr->name);
1989 original->masq = clone;
1990 clone->masqr = original;
1991 /* XXX can't really hold the lock here, but at the same time, it' s
1992 not really safe not to XXX */
1993 ast_queue_frame(original, &null, 0);
1994 ast_queue_frame(clone, &null, 0);
1995 ast_log(LOG_DEBUG, "Done planning to masquerade %s into the structure of %s\n", original->name, clone->name);
1999 void ast_change_name(struct ast_channel *chan, char *newname)
2002 strncpy(tmp, chan->name, 256);
2003 strncpy(chan->name, newname, sizeof(chan->name) - 1);
2004 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", tmp, chan->name, chan->uniqueid);
2007 int ast_do_masquerade(struct ast_channel *original, int needlock)
2012 struct ast_var_t *varptr;
2013 struct ast_frame *cur, *prev;
2014 struct ast_channel_pvt *p;
2015 struct ast_channel *clone = original->masq;
2016 int rformat = original->readformat;
2017 int wformat = original->writeformat;
2024 ast_log(LOG_DEBUG, "Actually Masquerading %s(%d) into the structure of %s(%d)\n",
2025 clone->name, clone->_state, original->name, original->_state);
2027 /* XXX This is a seriously wacked out operation. We're essentially putting the guts of
2028 the clone channel into the original channel. Start by killing off the original
2029 channel's backend. I'm not sure we're going to keep this function, because
2030 while the features are nice, the cost is very high in terms of pure nastiness. XXX */
2033 /* We need the clone's lock, too */
2034 ast_mutex_lock(&clone->lock);
2036 ast_log(LOG_DEBUG, "Got clone lock on '%s' at %p\n", clone->name, &clone->lock);
2038 /* Having remembered the original read/write formats, we turn off any translation on either
2040 free_translation(clone);
2041 free_translation(original);
2044 /* Unlink the masquerade */
2045 original->masq = NULL;
2046 clone->masqr = NULL;
2048 /* Save the original name */
2049 strncpy(orig, original->name, sizeof(orig) - 1);
2050 /* Save the new name */
2051 strncpy(newn, clone->name, sizeof(newn) - 1);
2052 /* Create the masq name */
2053 snprintf(masqn, sizeof(masqn), "%s<MASQ>", newn);
2055 /* Copy the name from the clone channel */
2056 strncpy(original->name, newn, sizeof(original->name)-1);
2058 /* Mangle the name of the clone channel */
2059 strncpy(clone->name, masqn, sizeof(clone->name) - 1);
2061 /* Notify any managers of the change, first the masq then the other */
2062 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\n", newn, masqn);
2063 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\n", orig, newn);
2067 original->pvt = clone->pvt;
2070 /* Save any pending frames on both sides. Start by counting
2071 * how many we're going to need... */
2073 cur = clone->pvt->readq;
2080 /* If we had any, prepend them to the ones already in the queue, and
2081 * load up the alertpipe */
2083 prev->next = original->pvt->readq;
2084 original->pvt->readq = clone->pvt->readq;
2085 clone->pvt->readq = NULL;
2086 if (original->pvt->alertpipe[1] > -1) {
2088 write(original->pvt->alertpipe[1], &x, sizeof(x));
2091 clone->_softhangup = AST_SOFTHANGUP_DEV;
2094 if (clone->pvt->fixup){
2095 res = clone->pvt->fixup(original, clone, needlock);
2097 ast_log(LOG_WARNING, "Fixup failed on channel %s, strange things may happen.\n", clone->name);
2100 /* Start by disconnecting the original's physical side */
2101 if (clone->pvt->hangup)
2102 res = clone->pvt->hangup(clone);
2104 ast_log(LOG_WARNING, "Hangup failed! Strange things may happen!\n");
2106 ast_mutex_unlock(&clone->lock);
2110 snprintf(zombn, sizeof(zombn), "%s<ZOMBIE>", orig);
2111 /* Mangle the name of the clone channel */
2112 strncpy(clone->name, zombn, sizeof(clone->name) - 1);
2113 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\n", masqn, zombn);
2115 /* Keep the same language. */
2116 /* Update the type. */
2117 original->type = clone->type;
2119 for (x=0;x<AST_MAX_FDS;x++) {
2120 original->fds[x] = clone->fds[x];
2122 /* Append variables from clone channel into original channel */
2123 /* XXX Is this always correct? We have to in order to keep MACROS working XXX */
2124 varptr = original->varshead.first;
2126 while(varptr->entries.next) {
2127 varptr = varptr->entries.next;
2129 varptr->entries.next = clone->varshead.first;
2131 original->varshead.first = clone->varshead.first;
2133 clone->varshead.first = NULL;
2134 /* Presense of ADSI capable CPE follows clone */
2135 original->adsicpe = clone->adsicpe;
2136 /* Bridge remains the same */
2137 /* CDR fields remain the same */
2138 /* XXX What about blocking, softhangup, blocker, and lock and blockproc? XXX */
2139 /* Application and data remain the same */
2140 /* Clone exception becomes real one, as with fdno */
2141 original->exception = clone->exception;
2142 original->fdno = clone->fdno;
2143 /* Schedule context remains the same */
2144 /* Stream stuff stays the same */
2145 /* Keep the original state. The fixup code will need to work with it most likely */
2147 /* dnid and callerid change to become the new, HOWEVER, we also link the original's
2148 fields back into the defunct 'clone' so that they will be freed when
2149 ast_frfree is eventually called */
2150 tmp = original->dnid;
2151 original->dnid = clone->dnid;
2154 tmp = original->callerid;
2155 original->callerid = clone->callerid;
2156 clone->callerid = tmp;
2158 /* Restore original timing file descriptor */
2159 original->fds[AST_MAX_FDS - 2] = original->timingfd;
2161 /* Our native formats are different now */
2162 original->nativeformats = clone->nativeformats;
2164 /* And of course, so does our current state. Note we need not
2165 call ast_setstate since the event manager doesn't really consider
2167 original->_state = clone->_state;
2169 /* Context, extension, priority, app data, jump table, remain the same */
2170 /* pvt switches. pbx stays the same, as does next */
2172 /* Set the write format */
2173 ast_set_write_format(original, wformat, 0);
2175 /* Set the read format */
2176 ast_set_read_format(original, rformat, 0);
2178 ast_log(LOG_DEBUG, "Putting channel %s in %d/%d formats\n", original->name, wformat, rformat);
2180 /* Okay. Last thing is to let the channel driver know about all this mess, so he
2181 can fix up everything as best as possible */
2182 if (original->pvt->fixup) {
2183 res = original->pvt->fixup(clone, original, needlock);
2185 ast_log(LOG_WARNING, "Driver for '%s' could not fixup channel %s\n",
2186 original->type, original->name);
2190 ast_log(LOG_WARNING, "Driver '%s' does not have a fixup routine (for %s)! Bad things may happen.\n",
2191 original->type, original->name);
2193 /* Now, at this point, the "clone" channel is totally F'd up. We mark it as
2194 a zombie so nothing tries to touch it. If it's already been marked as a
2195 zombie, then free it now (since it already is considered invalid). */
2196 if (clone->zombie) {
2197 ast_log(LOG_DEBUG, "Destroying clone '%s'\n", clone->name);
2199 ast_mutex_unlock(&clone->lock);
2200 ast_channel_free(clone);
2201 manager_event(EVENT_FLAG_CALL, "Hangup", "Channel: %s\r\n", zombn);
2203 ast_log(LOG_DEBUG, "Released clone lock on '%s'\n", clone->name);
2206 ast_mutex_unlock(&clone->lock);
2209 /* Signal any blocker */
2210 if (original->blocking)
2211 pthread_kill(original->blocker, SIGURG);
2212 ast_log(LOG_DEBUG, "Done Masquerading %s (%d)\n",
2213 original->name, original->_state);
2217 void ast_set_callerid(struct ast_channel *chan, char *callerid, int anitoo)
2220 free(chan->callerid);
2221 if (anitoo && chan->ani)
2224 chan->callerid = strdup(callerid);
2226 chan->ani = strdup(callerid);
2228 chan->callerid = NULL;
2233 ast_cdr_setcid(chan->cdr, chan);
2234 manager_event(EVENT_FLAG_CALL, "Newcallerid",
2238 chan->name, chan->callerid ?
2239 chan->callerid : "<Unknown>",
2243 int ast_setstate(struct ast_channel *chan, int state)
2245 if (chan->_state != state) {
2246 int oldstate = chan->_state;
2247 chan->_state = state;
2248 if (oldstate == AST_STATE_DOWN) {
2249 ast_device_state_changed(chan->name);
2250 manager_event(EVENT_FLAG_CALL, "Newchannel",
2255 chan->name, ast_state2str(chan->_state), chan->callerid ? chan->callerid : "<unknown>", chan->uniqueid);
2257 manager_event(EVENT_FLAG_CALL, "Newstate",
2262 chan->name, ast_state2str(chan->_state), chan->callerid ? chan->callerid : "<unknown>", chan->uniqueid);
2268 int ast_channel_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
2270 /* Copy voice back and forth between the two channels. Give the peer
2271 the ability to transfer calls with '#<extension' syntax. */
2272 struct ast_channel *cs[3];
2274 struct ast_frame *f;
2275 struct ast_channel *who = NULL;
2279 /* Stop if we're a zombie or need a soft hangup */
2280 if (c0->zombie || ast_check_hangup_locked(c0) || c1->zombie || ast_check_hangup_locked(c1))
2283 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n",
2284 c0->name, c0->bridge->name);
2288 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n",
2289 c1->name, c1->bridge->name);
2293 /* Keep track of bridge */
2299 manager_event(EVENT_FLAG_CALL, "Link",
2302 c0->name, c1->name);
2304 for (/* ever */;;) {
2305 /* Stop if we're a zombie or need a soft hangup */
2306 if (c0->zombie || ast_check_hangup_locked(c0) || c1->zombie || ast_check_hangup_locked(c1)) {
2310 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,c0->zombie?"Yes":"No",ast_check_hangup(c0)?"Yes":"No",c1->zombie?"Yes":"No",ast_check_hangup(c1)?"Yes":"No");
2313 if (c0->pvt->bridge &&
2314 (c0->pvt->bridge == c1->pvt->bridge) && !nativefailed && !c0->monitor && !c1->monitor) {
2315 /* Looks like they share a bridge code */
2316 if (option_verbose > 2)
2317 ast_verbose(VERBOSE_PREFIX_3 "Attempting native bridge of %s and %s\n", c0->name, c1->name);
2318 if (!(res = c0->pvt->bridge(c0, c1, flags, fo, rc))) {
2321 manager_event(EVENT_FLAG_CALL, "Unlink",
2324 c0->name, c1->name);
2325 ast_log(LOG_DEBUG, "Returning from native bridge, channels: %s, %s\n",c0->name ,c1->name);
2328 /* If they return non-zero then continue on normally. Let "-2" mean don't worry about
2329 my not wanting to bridge */
2330 if ((res != -2) && (res != -3))
2331 ast_log(LOG_WARNING, "Private bridge between %s and %s failed\n", c0->name, c1->name);
2332 if (res != -3) nativefailed++;
2336 if (((c0->writeformat != c1->readformat) || (c0->readformat != c1->writeformat)) &&
2337 !(c0->generator || c1->generator)) {
2338 if (ast_channel_make_compatible(c0, c1)) {
2339 ast_log(LOG_WARNING, "Can't make %s and %s compatible\n", c0->name, c1->name);
2340 manager_event(EVENT_FLAG_CALL, "Unlink",
2343 c0->name, c1->name);
2347 who = ast_waitfor_n(cs, 2, &to);
2349 ast_log(LOG_DEBUG, "Nobody there, continuing...\n");
2357 ast_log(LOG_DEBUG, "Didn't get a frame from channel: %s\n",who->name);
2361 if ((f->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
2365 ast_log(LOG_DEBUG, "Got a FRAME_CONTROL (%d) frame on channel %s\n", f->subclass, who->name);
2368 if ((f->frametype == AST_FRAME_VOICE) ||
2369 (f->frametype == AST_FRAME_TEXT) ||
2370 (f->frametype == AST_FRAME_VIDEO) ||
2371 (f->frametype == AST_FRAME_IMAGE) ||
2372 (f->frametype == AST_FRAME_DTMF)) {
2373 if ((f->frametype == AST_FRAME_DTMF) &&
2374 (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))) {
2376 if ((flags & AST_BRIDGE_DTMF_CHANNEL_0)) {
2379 /* Take out of conference mode */
2381 ast_log(LOG_DEBUG, "Got AST_BRIDGE_DTMF_CHANNEL_0 on c0 (%s)\n",c0->name);
2387 if (flags & AST_BRIDGE_DTMF_CHANNEL_1) {
2391 ast_log(LOG_DEBUG, "Got AST_BRIDGE_DTMF_CHANNEL_1 on c1 (%s)\n",c1->name);
2398 ast_log(LOG_DEBUG, "Read from %s\n", who->name);
2400 ast_log(LOG_DEBUG, "Servicing channel %s twice in a row?\n", last->name);
2404 /* Don't copy packets if there is a generator on either one, since they're
2405 not supposed to be listening anyway */
2414 /* Swap who gets priority */
2421 manager_event(EVENT_FLAG_CALL, "Unlink",
2424 c0->name, c1->name);
2425 ast_log(LOG_DEBUG, "Bridge stops bridging channels %s and %s\n",c0->name,c1->name);
2429 int ast_channel_setoption(struct ast_channel *chan, int option, void *data, int datalen, int block)
2432 if (chan->pvt->setoption) {
2433 res = chan->pvt->setoption(chan, option, data, datalen);
2441 /* XXX Implement blocking -- just wait for our option frame reply, discarding
2442 intermediate packets. XXX */
2443 ast_log(LOG_ERROR, "XXX Blocking not implemented yet XXX\n");
2449 struct tonepair_def {
2456 struct tonepair_state {
2464 unsigned char offset[AST_FRIENDLY_OFFSET];
2468 static void tonepair_release(struct ast_channel *chan, void *params)
2470 struct tonepair_state *ts = params;
2472 ast_set_write_format(chan, ts->origwfmt, 0);
2477 static void * tonepair_alloc(struct ast_channel *chan, void *params)
2479 struct tonepair_state *ts;
2480 struct tonepair_def *td = params;
2481 ts = malloc(sizeof(struct tonepair_state));
2484 memset(ts, 0, sizeof(struct tonepair_state));
2485 ts->origwfmt = chan->writeformat;
2486 if (ast_set_write_format(chan, AST_FORMAT_SLINEAR, 1)) {
2487 ast_log(LOG_WARNING, "Unable to set '%s' to signed linear format (write)\n", chan->name);
2488 tonepair_release(NULL, ts);
2491 ts->freq1 = td->freq1;
2492 ts->freq2 = td->freq2;
2493 ts->duration = td->duration;
2496 /* Let interrupts interrupt :) */
2497 chan->writeinterrupt = 1;
2501 static int tonepair_generator(struct ast_channel *chan, void *data, int len, int samples)
2503 struct tonepair_state *ts = data;
2506 /* we need to prepare a frame with 16 * timelen samples as we're
2507 * generating SLIN audio
2511 if (len > sizeof(ts->data) / 2 - 1) {
2512 ast_log(LOG_WARNING, "Can't generate that much data!\n");
2515 memset(&ts->f, 0, sizeof(ts->f));
2516 for (x=0;x<len/2;x++) {
2517 ts->data[x] = ts->vol * (
2518 sin((ts->freq1 * 2.0 * M_PI / 8000.0) * (ts->pos + x)) +
2519 sin((ts->freq2 * 2.0 * M_PI / 8000.0) * (ts->pos + x))
2522 ts->f.frametype = AST_FRAME_VOICE;
2523 ts->f.subclass = AST_FORMAT_SLINEAR;
2524 ts->f.datalen = len;
2525 ts->f.samples = samples;
2526 ts->f.offset = AST_FRIENDLY_OFFSET;
2527 ts->f.data = ts->data;
2528 ast_write(chan, &ts->f);
2530 if (ts->duration > 0) {
2531 if (ts->pos >= ts->duration * 8)
2537 static struct ast_generator tonepair = {
2538 alloc: tonepair_alloc,
2539 release: tonepair_release,
2540 generate: tonepair_generator,
2543 int ast_tonepair_start(struct ast_channel *chan, int freq1, int freq2, int duration, int vol)
2545 struct tonepair_def d = { 0, };
2548 d.duration = duration;
2553 if (ast_activate_generator(chan, &tonepair, &d))
2558 void ast_tonepair_stop(struct ast_channel *chan)
2560 ast_deactivate_generator(chan);
2563 int ast_tonepair(struct ast_channel *chan, int freq1, int freq2, int duration, int vol)
2565 struct ast_frame *f;
2567 if ((res = ast_tonepair_start(chan, freq1, freq2, duration, vol)))
2570 /* Give us some wiggle room */
2571 while(chan->generatordata && (ast_waitfor(chan, 100) >= 0)) {
2581 unsigned int ast_get_group(char *s)
2586 int start=0, finish=0,x;
2587 unsigned int group = 0;
2588 copy = ast_strdupa(s);
2590 ast_log(LOG_ERROR, "Out of memory\n");
2595 while((piece = strsep(&c, ","))) {
2596 if (sscanf(piece, "%d-%d", &start, &finish) == 2) {
2598 } else if (sscanf(piece, "%d", &start)) {
2602 ast_log(LOG_ERROR, "Syntax error parsing '%s' at '%s'. Using '0'\n", s,piece);
2605 for (x=start;x<=finish;x++) {
2606 if ((x > 31) || (x < 0)) {
2607 ast_log(LOG_WARNING, "Ignoring invalid group %d (maximum group is 31)\n", x);