2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2005, Digium, Inc.
6 * Mark Spencer <markster@digium.com>
8 * See http://www.asterisk.org for more information about
9 * the Asterisk project. Please do not directly contact
10 * any of the maintainers of this project for assistance;
11 * the project provides a web site, mailing lists and IRC
12 * channels for your use.
14 * This program is free software, distributed under the terms of
15 * the GNU General Public License Version 2. See the LICENSE file
16 * at the top of the source tree.
32 #include <math.h> /* For PI */
34 #ifdef ZAPTEL_OPTIMIZATIONS
35 #include <sys/ioctl.h>
37 #include <linux/zaptel.h>
40 #endif /* __linux__ */
42 #error "You need newer zaptel! Please cvs update zaptel"
48 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
50 #include "asterisk/pbx.h"
51 #include "asterisk/frame.h"
52 #include "asterisk/sched.h"
53 #include "asterisk/options.h"
54 #include "asterisk/channel.h"
55 #include "asterisk/musiconhold.h"
56 #include "asterisk/logger.h"
57 #include "asterisk/say.h"
58 #include "asterisk/file.h"
59 #include "asterisk/cli.h"
60 #include "asterisk/translate.h"
61 #include "asterisk/manager.h"
62 #include "asterisk/chanvars.h"
63 #include "asterisk/linkedlists.h"
64 #include "asterisk/indications.h"
65 #include "asterisk/monitor.h"
66 #include "asterisk/causes.h"
67 #include "asterisk/callerid.h"
68 #include "asterisk/utils.h"
69 #include "asterisk/lock.h"
70 #include "asterisk/app.h"
71 #include "asterisk/transcap.h"
72 #include "asterisk/devicestate.h"
74 /* uncomment if you have problems with 'monitoring' synchronized files */
76 #define MONITOR_CONSTANT_DELAY
77 #define MONITOR_DELAY 150 * 8 /* 150 ms of MONITORING DELAY */
81 * Prevent new channel allocation if shutting down.
83 static int shutting_down = 0;
85 static int uniqueint = 0;
87 unsigned long global_fin = 0, global_fout = 0;
89 /* XXX Lock appropriately in more functions XXX */
92 const struct ast_channel_tech *tech;
93 struct chanlist *next;
96 static struct chanlist *backends = NULL;
99 * the list of channels we have
101 static struct ast_channel *channels = NULL;
103 /* Protect the channel list, both backends and channels.
105 AST_MUTEX_DEFINE_STATIC(chlock);
107 const struct ast_cause {
111 { AST_CAUSE_UNALLOCATED, "Unallocated (unassigned) number" },
112 { AST_CAUSE_NO_ROUTE_TRANSIT_NET, "No route to specified transmit network" },
113 { AST_CAUSE_NO_ROUTE_DESTINATION, "No route to destination" },
114 { AST_CAUSE_CHANNEL_UNACCEPTABLE, "Channel unacceptable" },
115 { AST_CAUSE_CALL_AWARDED_DELIVERED, "Call awarded and being delivered in an established channel" },
116 { AST_CAUSE_NORMAL_CLEARING, "Normal Clearing" },
117 { AST_CAUSE_USER_BUSY, "User busy" },
118 { AST_CAUSE_NO_USER_RESPONSE, "No user responding" },
119 { AST_CAUSE_NO_ANSWER, "User alerting, no answer" },
120 { AST_CAUSE_CALL_REJECTED, "Call Rejected" },
121 { AST_CAUSE_NUMBER_CHANGED, "Number changed" },
122 { AST_CAUSE_DESTINATION_OUT_OF_ORDER, "Destination out of order" },
123 { AST_CAUSE_INVALID_NUMBER_FORMAT, "Invalid number format" },
124 { AST_CAUSE_FACILITY_REJECTED, "Facility rejected" },
125 { AST_CAUSE_RESPONSE_TO_STATUS_ENQUIRY, "Response to STATus ENQuiry" },
126 { AST_CAUSE_NORMAL_UNSPECIFIED, "Normal, unspecified" },
127 { AST_CAUSE_NORMAL_CIRCUIT_CONGESTION, "Circuit/channel congestion" },
128 { AST_CAUSE_NETWORK_OUT_OF_ORDER, "Network out of order" },
129 { AST_CAUSE_NORMAL_TEMPORARY_FAILURE, "Temporary failure" },
130 { AST_CAUSE_SWITCH_CONGESTION, "Switching equipment congestion" },
131 { AST_CAUSE_ACCESS_INFO_DISCARDED, "Access information discarded" },
132 { AST_CAUSE_REQUESTED_CHAN_UNAVAIL, "Requested channel not available" },
133 { AST_CAUSE_PRE_EMPTED, "Pre-empted" },
134 { AST_CAUSE_FACILITY_NOT_SUBSCRIBED, "Facility not subscribed" },
135 { AST_CAUSE_OUTGOING_CALL_BARRED, "Outgoing call barred" },
136 { AST_CAUSE_INCOMING_CALL_BARRED, "Incoming call barred" },
137 { AST_CAUSE_BEARERCAPABILITY_NOTAUTH, "Bearer capability not authorized" },
138 { AST_CAUSE_BEARERCAPABILITY_NOTAVAIL, "Bearer capability not available" },
139 { AST_CAUSE_BEARERCAPABILITY_NOTIMPL, "Bearer capability not implemented" },
140 { AST_CAUSE_CHAN_NOT_IMPLEMENTED, "Channel not implemented" },
141 { AST_CAUSE_FACILITY_NOT_IMPLEMENTED, "Facility not implemented" },
142 { AST_CAUSE_INVALID_CALL_REFERENCE, "Invalid call reference value" },
143 { AST_CAUSE_INCOMPATIBLE_DESTINATION, "Incompatible destination" },
144 { AST_CAUSE_INVALID_MSG_UNSPECIFIED, "Invalid message unspecified" },
145 { AST_CAUSE_MANDATORY_IE_MISSING, "Mandatory information element is missing" },
146 { AST_CAUSE_MESSAGE_TYPE_NONEXIST, "Message type nonexist." },
147 { AST_CAUSE_WRONG_MESSAGE, "Wrong message" },
148 { AST_CAUSE_IE_NONEXIST, "Info. element nonexist or not implemented" },
149 { AST_CAUSE_INVALID_IE_CONTENTS, "Invalid information element contents" },
150 { AST_CAUSE_WRONG_CALL_STATE, "Message not compatible with call state" },
151 { AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE, "Recover on timer expiry" },
152 { AST_CAUSE_MANDATORY_IE_LENGTH_ERROR, "Mandatory IE length error" },
153 { AST_CAUSE_PROTOCOL_ERROR, "Protocol error, unspecified" },
154 { AST_CAUSE_INTERWORKING, "Interworking, unspecified" },
158 static int show_channeltypes(int fd, int argc, char *argv[])
160 #define FORMAT "%-10.10s %-30.30s %-12.12s %-12.12s %-12.12s\n"
161 struct chanlist *cl = backends;
162 ast_cli(fd, FORMAT, "Type", "Description", "Devicestate", "Indications", "Transfer");
163 ast_cli(fd, FORMAT, "----------", "-----------", "-----------", "-----------", "--------");
164 if (ast_mutex_lock(&chlock)) {
165 ast_log(LOG_WARNING, "Unable to lock channel list\n");
169 ast_cli(fd, FORMAT, cl->tech->type, cl->tech->description,
170 (cl->tech->devicestate) ? "yes" : "no",
171 (cl->tech->indicate) ? "yes" : "no",
172 (cl->tech->transfer) ? "yes" : "no");
175 ast_mutex_unlock(&chlock);
176 return RESULT_SUCCESS;
182 static char show_channeltypes_usage[] =
183 "Usage: show channeltypes\n"
184 " Shows available channel types registered in your Asterisk server.\n";
186 static struct ast_cli_entry cli_show_channeltypes =
187 { { "show", "channeltypes", NULL }, show_channeltypes, "Show available channel types", show_channeltypes_usage };
189 /*--- ast_check_hangup: Checks to see if a channel is needing hang up */
190 int ast_check_hangup(struct ast_channel *chan)
194 /* if soft hangup flag, return true */
195 if (chan->_softhangup)
197 /* if no technology private data, return true */
200 /* if no hangup scheduled, just return here */
201 if (!chan->whentohangup)
203 time(&myt); /* get current time */
204 /* return, if not yet */
205 if (chan->whentohangup > myt)
207 chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
211 static int ast_check_hangup_locked(struct ast_channel *chan)
214 ast_mutex_lock(&chan->lock);
215 res = ast_check_hangup(chan);
216 ast_mutex_unlock(&chan->lock);
220 /*--- ast_begin_shutdown: Initiate system shutdown */
221 void ast_begin_shutdown(int hangup)
223 struct ast_channel *c;
226 ast_mutex_lock(&chlock);
229 ast_softhangup(c, AST_SOFTHANGUP_SHUTDOWN);
232 ast_mutex_unlock(&chlock);
236 /*--- ast_active_channels: returns number of active/allocated channels */
237 int ast_active_channels(void)
239 struct ast_channel *c;
241 ast_mutex_lock(&chlock);
247 ast_mutex_unlock(&chlock);
251 /*--- ast_cancel_shutdown: Cancel a shutdown in progress */
252 void ast_cancel_shutdown(void)
257 /*--- ast_shutting_down: Returns non-zero if Asterisk is being shut down */
258 int ast_shutting_down(void)
260 return shutting_down;
263 /*--- ast_channel_setwhentohangup: Set when to hangup channel */
264 void ast_channel_setwhentohangup(struct ast_channel *chan, time_t offset)
267 struct ast_frame fr = { AST_FRAME_NULL, };
271 chan->whentohangup = myt + offset;
273 chan->whentohangup = 0;
274 ast_queue_frame(chan, &fr);
278 /*--- ast_channel_cmpwhentohangup: Compare a offset with when to hangup channel */
279 int ast_channel_cmpwhentohangup(struct ast_channel *chan, time_t offset)
283 if (chan->whentohangup == 0) {
292 whentohangup = offset + time (NULL);
293 if (chan->whentohangup < whentohangup)
295 else if (chan->whentohangup == whentohangup)
303 /*--- ast_channel_register: Register a new telephony channel in Asterisk */
304 int ast_channel_register(const struct ast_channel_tech *tech)
306 struct chanlist *chan;
308 ast_mutex_lock(&chlock);
312 if (!strcasecmp(tech->type, chan->tech->type)) {
313 ast_log(LOG_WARNING, "Already have a handler for type '%s'\n", tech->type);
314 ast_mutex_unlock(&chlock);
320 chan = malloc(sizeof(*chan));
322 ast_log(LOG_WARNING, "Out of memory\n");
323 ast_mutex_unlock(&chlock);
327 chan->next = backends;
331 ast_log(LOG_DEBUG, "Registered handler for '%s' (%s)\n", chan->tech->type, chan->tech->description);
333 if (option_verbose > 1)
334 ast_verbose(VERBOSE_PREFIX_2 "Registered channel type '%s' (%s)\n", chan->tech->type,
335 chan->tech->description);
337 ast_mutex_unlock(&chlock);
341 void ast_channel_unregister(const struct ast_channel_tech *tech)
343 struct chanlist *chan, *last=NULL;
346 ast_log(LOG_DEBUG, "Unregistering channel type '%s'\n", tech->type);
348 ast_mutex_lock(&chlock);
352 if (chan->tech == tech) {
354 last->next = chan->next;
356 backends = backends->next;
358 ast_mutex_unlock(&chlock);
360 if (option_verbose > 1)
361 ast_verbose( VERBOSE_PREFIX_2 "Unregistered channel type '%s'\n", tech->type);
369 ast_mutex_unlock(&chlock);
372 const struct ast_channel_tech *ast_get_channel_tech(const char *name)
374 struct chanlist *chanls;
376 if (ast_mutex_lock(&chlock)) {
377 ast_log(LOG_WARNING, "Unable to lock channel tech list\n");
381 for (chanls = backends; chanls; chanls = chanls->next) {
382 if (strcasecmp(name, chanls->tech->type))
385 ast_mutex_unlock(&chlock);
389 ast_mutex_unlock(&chlock);
393 /*--- ast_cause2str: Gives the string form of a given hangup cause */
394 const char *ast_cause2str(int cause)
398 for (x=0; x < sizeof(causes) / sizeof(causes[0]); x++)
399 if (causes[x].cause == cause)
400 return causes[x].desc;
405 /*--- ast_state2str: Gives the string form of a given channel state */
406 char *ast_state2str(int state)
408 /* XXX Not reentrant XXX */
409 static char localtmp[256];
413 case AST_STATE_RESERVED:
415 case AST_STATE_OFFHOOK:
417 case AST_STATE_DIALING:
421 case AST_STATE_RINGING:
428 snprintf(localtmp, sizeof(localtmp), "Unknown (%d)\n", state);
433 /*--- ast_transfercapability2str: Gives the string form of a given transfer capability */
434 char *ast_transfercapability2str(int transfercapability)
436 switch(transfercapability) {
437 case AST_TRANS_CAP_SPEECH:
439 case AST_TRANS_CAP_DIGITAL:
441 case AST_TRANS_CAP_RESTRICTED_DIGITAL:
442 return "RESTRICTED_DIGITAL";
443 case AST_TRANS_CAP_3_1K_AUDIO:
445 case AST_TRANS_CAP_DIGITAL_W_TONES:
446 return "DIGITAL_W_TONES";
447 case AST_TRANS_CAP_VIDEO:
454 /*--- ast_best_codec: Pick the best codec */
455 int ast_best_codec(int fmts)
457 /* This just our opinion, expressed in code. We are asked to choose
458 the best codec to use, given no information */
462 /* Okay, ulaw is used by all telephony equipment, so start with it */
464 /* Unless of course, you're a silly European, so then prefer ALAW */
466 /* Okay, well, signed linear is easy to translate into other stuff */
468 /* G.726 is standard ADPCM */
470 /* ADPCM has great sound quality and is still pretty easy to translate */
472 /* Okay, we're down to vocoders now, so pick GSM because it's small and easier to
473 translate and sounds pretty good */
475 /* iLBC is not too bad */
477 /* Speex is free, but computationally more expensive than GSM */
479 /* Ick, LPC10 sounds terrible, but at least we have code for it, if you're tacky enough
482 /* G.729a is faster than 723 and slightly less expensive */
484 /* Down to G.723.1 which is proprietary but at least designed for voice */
489 /* Find the first prefered codec in the format given */
490 for (x=0; x < (sizeof(prefs) / sizeof(prefs[0]) ); x++)
493 ast_log(LOG_WARNING, "Don't know any of 0x%x formats\n", fmts);
497 static const struct ast_channel_tech null_tech = {
499 .description = "Null channel (should not see this)",
502 /*--- ast_channel_alloc: Create a new channel structure */
503 struct ast_channel *ast_channel_alloc(int needqueue)
505 struct ast_channel *tmp;
508 struct varshead *headp;
511 /* If shutting down, don't allocate any new channels */
513 ast_log(LOG_WARNING, "Channel allocation failed: Refusing due to active shutdown\n");
517 tmp = malloc(sizeof(struct ast_channel));
519 ast_log(LOG_WARNING, "Channel allocation failed: Out of memory\n");
523 memset(tmp, 0, sizeof(struct ast_channel));
524 tmp->sched = sched_context_create();
526 ast_log(LOG_WARNING, "Channel allocation failed: Unable to create schedule context\n");
531 for (x=0; x<AST_MAX_FDS - 1; x++)
534 #ifdef ZAPTEL_OPTIMIZATIONS
535 tmp->timingfd = open("/dev/zap/timer", O_RDWR);
536 if (tmp->timingfd > -1) {
537 /* Check if timing interface supports new
540 if (!ioctl(tmp->timingfd, ZT_TIMERPONG, &flags))
548 if (pipe(tmp->alertpipe)) {
549 ast_log(LOG_WARNING, "Channel allocation failed: Can't create alert pipe!\n");
553 flags = fcntl(tmp->alertpipe[0], F_GETFL);
554 fcntl(tmp->alertpipe[0], F_SETFL, flags | O_NONBLOCK);
555 flags = fcntl(tmp->alertpipe[1], F_GETFL);
556 fcntl(tmp->alertpipe[1], F_SETFL, flags | O_NONBLOCK);
559 /* Make sure we've got it done right if they don't */
560 tmp->alertpipe[0] = tmp->alertpipe[1] = -1;
562 /* Always watch the alertpipe */
563 tmp->fds[AST_MAX_FDS-1] = tmp->alertpipe[0];
564 /* And timing pipe */
565 tmp->fds[AST_MAX_FDS-2] = tmp->timingfd;
566 strcpy(tmp->name, "**Unkown**");
568 tmp->_state = AST_STATE_DOWN;
572 tmp->fin = global_fin;
573 tmp->fout = global_fout;
574 snprintf(tmp->uniqueid, sizeof(tmp->uniqueid), "%li.%d", (long) time(NULL), uniqueint++);
575 headp = &tmp->varshead;
576 ast_mutex_init(&tmp->lock);
577 AST_LIST_HEAD_INIT(headp);
578 strcpy(tmp->context, "default");
579 ast_copy_string(tmp->language, defaultlanguage, sizeof(tmp->language));
580 strcpy(tmp->exten, "s");
582 tmp->amaflags = ast_default_amaflags;
583 ast_copy_string(tmp->accountcode, ast_default_accountcode, sizeof(tmp->accountcode));
585 tmp->tech = &null_tech;
587 ast_mutex_lock(&chlock);
588 tmp->next = channels;
591 ast_mutex_unlock(&chlock);
595 /*--- ast_queue_frame: Queue an outgoing media frame */
596 int ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin)
599 struct ast_frame *prev, *cur;
603 /* Build us a copy and free the original one */
606 ast_log(LOG_WARNING, "Unable to duplicate frame\n");
609 ast_mutex_lock(&chan->lock);
613 if ((cur->frametype == AST_FRAME_CONTROL) && (cur->subclass == AST_CONTROL_HANGUP)) {
614 /* Don't bother actually queueing anything after a hangup */
616 ast_mutex_unlock(&chan->lock);
623 /* Allow up to 96 voice frames outstanding, and up to 128 total frames */
624 if (((fin->frametype == AST_FRAME_VOICE) && (qlen > 96)) || (qlen > 128)) {
625 if (fin->frametype != AST_FRAME_VOICE) {
626 ast_log(LOG_WARNING, "Exceptionally long queue length queuing to %s\n", chan->name);
629 ast_log(LOG_DEBUG, "Dropping voice to exceptionally long queue on %s\n", chan->name);
631 ast_mutex_unlock(&chan->lock);
639 if (chan->alertpipe[1] > -1) {
640 if (write(chan->alertpipe[1], &blah, sizeof(blah)) != sizeof(blah))
641 ast_log(LOG_WARNING, "Unable to write to alert pipe on %s, frametype/subclass %d/%d (qlen = %d): %s!\n",
642 chan->name, f->frametype, f->subclass, qlen, strerror(errno));
643 #ifdef ZAPTEL_OPTIMIZATIONS
644 } else if (chan->timingfd > -1) {
645 ioctl(chan->timingfd, ZT_TIMERPING, &blah);
647 } else if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
648 pthread_kill(chan->blocker, SIGURG);
650 ast_mutex_unlock(&chan->lock);
654 /*--- ast_queue_hangup: Queue a hangup frame for channel */
655 int ast_queue_hangup(struct ast_channel *chan)
657 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_HANGUP };
658 chan->_softhangup |= AST_SOFTHANGUP_DEV;
659 return ast_queue_frame(chan, &f);
662 /*--- ast_queue_control: Queue a control frame */
663 int ast_queue_control(struct ast_channel *chan, int control)
665 struct ast_frame f = { AST_FRAME_CONTROL, };
666 f.subclass = control;
667 return ast_queue_frame(chan, &f);
670 /*--- ast_channel_defer_dtmf: Set defer DTMF flag on channel */
671 int ast_channel_defer_dtmf(struct ast_channel *chan)
676 pre = ast_test_flag(chan, AST_FLAG_DEFER_DTMF);
677 ast_set_flag(chan, AST_FLAG_DEFER_DTMF);
682 /*--- ast_channel_undefer_dtmf: Unset defer DTMF flag on channel */
683 void ast_channel_undefer_dtmf(struct ast_channel *chan)
686 ast_clear_flag(chan, AST_FLAG_DEFER_DTMF);
690 * Helper function to find channels. It supports these modes:
692 * prev != NULL : get channel next in list after prev
693 * name != NULL : get channel with matching name
694 * name != NULL && namelen != 0 : get channel whose name starts with prefix
695 * exten != NULL : get channel whose exten or macroexten matches
696 * context != NULL && exten != NULL : get channel whose context or macrocontext
698 * It returns with the channel's lock held. If getting the individual lock fails,
699 * unlock and retry quickly up to 10 times, then give up.
701 * XXX Note that this code has cost O(N) because of the need to verify
702 * that the object is still on the global list.
704 * XXX also note that accessing fields (e.g. c->name in ast_log())
705 * can only be done with the lock held or someone could delete the
706 * object while we work on it. This causes some ugliness in the code.
707 * Note that removing the first ast_log() may be harmful, as it would
708 * shorten the retry period and possibly cause failures.
709 * We should definitely go for a better scheme that is deadlock-free.
711 static struct ast_channel *channel_find_locked(const struct ast_channel *prev,
712 const char *name, const int namelen,
713 const char *context, const char *exten)
715 const char *msg = prev ? "deadlock" : "initial deadlock";
717 struct ast_channel *c;
719 for (retries = 0; retries < 10; retries++) {
720 ast_mutex_lock(&chlock);
721 for (c = channels; c; c = c->next) {
723 /* want head of list */
727 /* want match by full name */
729 if (!strcasecmp(c->name, name))
734 /* want match by name prefix */
735 if (!strncasecmp(c->name, name, namelen))
738 /* want match by context and exten */
739 if (context && (strcasecmp(c->context, context) &&
740 strcasecmp(c->macrocontext, context)))
743 if (strcasecmp(c->exten, exten) &&
744 strcasecmp(c->macroexten, exten))
749 } else if (c == prev) { /* found, return c->next */
754 /* exit if chan not found or mutex acquired successfully */
755 done = (c == NULL) || (ast_mutex_trylock(&c->lock) == 0);
756 /* this is slightly unsafe, as we _should_ hold the lock to access c->name */
758 ast_log(LOG_DEBUG, "Avoiding %s for '%s'\n", msg, c->name);
759 ast_mutex_unlock(&chlock);
765 * c is surely not null, but we don't have the lock so cannot
768 ast_log(LOG_WARNING, "Avoided %s for '%p', %d retries!\n",
774 /*--- ast_channel_walk_locked: Browse channels in use */
775 struct ast_channel *ast_channel_walk_locked(const struct ast_channel *prev)
777 return channel_find_locked(prev, NULL, 0, NULL, NULL);
780 /*--- ast_get_channel_by_name_locked: Get channel by name and lock it */
781 struct ast_channel *ast_get_channel_by_name_locked(const char *name)
783 return channel_find_locked(NULL, name, 0, NULL, NULL);
786 /*--- ast_get_channel_by_name_prefix_locked: Get channel by name prefix and lock it */
787 struct ast_channel *ast_get_channel_by_name_prefix_locked(const char *name, const int namelen)
789 return channel_find_locked(NULL, name, namelen, NULL, NULL);
792 /*--- ast_get_channel_by_exten_locked: Get channel by exten (and optionally context) and lock it */
793 struct ast_channel *ast_get_channel_by_exten_locked(const char *exten, const char *context)
795 return channel_find_locked(NULL, NULL, 0, context, exten);
798 /*--- ast_safe_sleep_conditional: Wait, look for hangups and condition arg */
799 int ast_safe_sleep_conditional( struct ast_channel *chan, int ms,
800 int (*cond)(void*), void *data )
805 if( cond && ((*cond)(data) == 0 ) )
807 ms = ast_waitfor(chan, ms);
820 /*--- ast_safe_sleep: Wait, look for hangups */
821 int ast_safe_sleep(struct ast_channel *chan, int ms)
825 ms = ast_waitfor(chan, ms);
838 static void free_cid(struct ast_callerid *cid)
849 free(cid->cid_rdnis);
852 /*--- ast_channel_free: Free a channel structure */
853 void ast_channel_free(struct ast_channel *chan)
855 struct ast_channel *last=NULL, *cur;
857 struct ast_var_t *vardata;
858 struct ast_frame *f, *fp;
859 struct varshead *headp;
860 char name[AST_CHANNEL_NAME];
862 headp=&chan->varshead;
864 ast_mutex_lock(&chlock);
869 last->next = cur->next;
871 channels = cur->next;
878 ast_log(LOG_WARNING, "Unable to find channel in list\n");
880 /* Lock and unlock the channel just to be sure nobody
881 has it locked still */
882 ast_mutex_lock(&cur->lock);
883 ast_mutex_unlock(&cur->lock);
885 if (chan->tech_pvt) {
886 ast_log(LOG_WARNING, "Channel '%s' may not have been hung up properly\n", chan->name);
887 free(chan->tech_pvt);
890 ast_copy_string(name, chan->name, sizeof(name));
892 /* Stop monitoring */
894 chan->monitor->stop( chan, 0 );
897 /* If there is native format music-on-hold state, free it */
898 if(chan->music_state)
899 ast_moh_cleanup(chan);
901 /* Free translatosr */
903 ast_translator_free_path(chan->readtrans);
904 if (chan->writetrans)
905 ast_translator_free_path(chan->writetrans);
907 ast_log(LOG_WARNING, "PBX may not have been terminated properly on '%s'\n", chan->name);
908 free_cid(&chan->cid);
909 ast_mutex_destroy(&chan->lock);
910 /* Close pipes if appropriate */
911 if ((fd = chan->alertpipe[0]) > -1)
913 if ((fd = chan->alertpipe[1]) > -1)
915 if ((fd = chan->timingfd) > -1)
925 /* loop over the variables list, freeing all data and deleting list items */
926 /* no need to lock the list, as the channel is already locked */
928 while (!AST_LIST_EMPTY(headp)) { /* List Deletion. */
929 vardata = AST_LIST_REMOVE_HEAD(headp, entries);
930 ast_var_delete(vardata);
934 ast_mutex_unlock(&chlock);
936 ast_device_state_changed(name);
939 static void ast_spy_detach(struct ast_channel *chan)
941 struct ast_channel_spy *chanspy;
945 for (chanspy = chan->spiers; chanspy; chanspy = chanspy->next) {
946 if (chanspy->status == CHANSPY_RUNNING) {
947 chanspy->status = CHANSPY_DONE;
951 /* signal all the spys to get lost and allow them time to unhook themselves
952 god help us if they don't......
954 while (chan->spiers && to >= 0) {
955 ast_safe_sleep(chan, sleepms);
962 /*--- ast_softhangup_nolock: Softly hangup a channel, don't lock */
963 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
966 struct ast_frame f = { AST_FRAME_NULL };
968 ast_log(LOG_DEBUG, "Soft-Hanging up channel '%s'\n", chan->name);
969 /* Inform channel driver that we need to be hung up, if it cares */
970 chan->_softhangup |= cause;
971 ast_queue_frame(chan, &f);
972 /* Interrupt any poll call or such */
973 if (ast_test_flag(chan, AST_FLAG_BLOCKING))
974 pthread_kill(chan->blocker, SIGURG);
978 /*--- ast_softhangup_nolock: Softly hangup a channel, lock */
979 int ast_softhangup(struct ast_channel *chan, int cause)
982 ast_mutex_lock(&chan->lock);
983 res = ast_softhangup_nolock(chan, cause);
984 ast_mutex_unlock(&chan->lock);
988 static void ast_queue_spy_frame(struct ast_channel_spy *spy, struct ast_frame *f, int pos)
990 struct ast_frame *tmpf = NULL;
993 ast_mutex_lock(&spy->lock);
994 for (tmpf=spy->queue[pos]; tmpf && tmpf->next; tmpf=tmpf->next) {
998 struct ast_frame *freef, *headf;
1000 ast_log(LOG_ERROR, "Too many frames queued at once, flushing cache.\n");
1001 headf = spy->queue[pos];
1002 /* deref the queue right away so it looks empty */
1003 spy->queue[pos] = NULL;
1005 /* free the wasted frames */
1011 ast_mutex_unlock(&spy->lock);
1016 tmpf->next = ast_frdup(f);
1018 spy->queue[pos] = ast_frdup(f);
1021 ast_mutex_unlock(&spy->lock);
1024 static void free_translation(struct ast_channel *clone)
1026 if (clone->writetrans)
1027 ast_translator_free_path(clone->writetrans);
1028 if (clone->readtrans)
1029 ast_translator_free_path(clone->readtrans);
1030 clone->writetrans = NULL;
1031 clone->readtrans = NULL;
1032 clone->rawwriteformat = clone->nativeformats;
1033 clone->rawreadformat = clone->nativeformats;
1036 /*--- ast_hangup: Hangup a channel */
1037 int ast_hangup(struct ast_channel *chan)
1041 /* Don't actually hang up a channel that will masquerade as someone else, or
1042 if someone is going to masquerade as us */
1043 ast_mutex_lock(&chan->lock);
1045 ast_spy_detach(chan); /* get rid of spies */
1048 if (ast_do_masquerade(chan))
1049 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1053 ast_log(LOG_WARNING, "%s getting hung up, but someone is trying to masq into us?!?\n", chan->name);
1054 ast_mutex_unlock(&chan->lock);
1057 /* If this channel is one which will be masqueraded into something,
1058 mark it as a zombie already, so we know to free it later */
1060 ast_set_flag(chan, AST_FLAG_ZOMBIE);
1061 ast_mutex_unlock(&chan->lock);
1064 free_translation(chan);
1065 if (chan->stream) /* Close audio stream */
1066 ast_closestream(chan->stream);
1067 if (chan->vstream) /* Close video stream */
1068 ast_closestream(chan->vstream);
1070 sched_context_destroy(chan->sched);
1072 if (chan->generatordata) /* Clear any tone stuff remaining */
1073 chan->generator->release(chan, chan->generatordata);
1074 chan->generatordata = NULL;
1075 chan->generator = NULL;
1076 if (chan->cdr) { /* End the CDR if it hasn't already */
1077 ast_cdr_end(chan->cdr);
1078 ast_cdr_detach(chan->cdr); /* Post and Free the CDR */
1081 if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
1082 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
1083 "is blocked by thread %ld in procedure %s! Expect a failure\n",
1084 (long)pthread_self(), chan->name, (long)chan->blocker, chan->blockproc);
1087 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE)) {
1089 ast_log(LOG_DEBUG, "Hanging up channel '%s'\n", chan->name);
1090 if (chan->tech->hangup)
1091 res = chan->tech->hangup(chan);
1094 ast_log(LOG_DEBUG, "Hanging up zombie '%s'\n", chan->name);
1097 ast_mutex_unlock(&chan->lock);
1098 manager_event(EVENT_FLAG_CALL, "Hangup",
1102 "Cause-txt: %s\r\n",
1106 ast_cause2str(chan->hangupcause)
1108 ast_channel_free(chan);
1112 int ast_answer(struct ast_channel *chan)
1115 ast_mutex_lock(&chan->lock);
1116 /* Stop if we're a zombie or need a soft hangup */
1117 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
1118 ast_mutex_unlock(&chan->lock);
1121 switch(chan->_state) {
1122 case AST_STATE_RINGING:
1123 case AST_STATE_RING:
1124 if (chan->tech->answer)
1125 res = chan->tech->answer(chan);
1126 ast_setstate(chan, AST_STATE_UP);
1128 ast_cdr_answer(chan->cdr);
1129 ast_mutex_unlock(&chan->lock);
1134 ast_cdr_answer(chan->cdr);
1137 ast_mutex_unlock(&chan->lock);
1143 void ast_deactivate_generator(struct ast_channel *chan)
1145 ast_mutex_lock(&chan->lock);
1146 if (chan->generatordata) {
1147 if (chan->generator && chan->generator->release)
1148 chan->generator->release(chan, chan->generatordata);
1149 chan->generatordata = NULL;
1150 chan->generator = NULL;
1151 ast_clear_flag(chan, AST_FLAG_WRITE_INT);
1152 ast_settimeout(chan, 0, NULL, NULL);
1154 ast_mutex_unlock(&chan->lock);
1157 static int generator_force(void *data)
1159 /* Called if generator doesn't have data */
1162 int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples);
1163 struct ast_channel *chan = data;
1164 tmp = chan->generatordata;
1165 chan->generatordata = NULL;
1166 generate = chan->generator->generate;
1167 res = generate(chan, tmp, 0, 160);
1168 chan->generatordata = tmp;
1170 ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
1171 ast_deactivate_generator(chan);
1176 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
1179 ast_mutex_lock(&chan->lock);
1180 if (chan->generatordata) {
1181 if (chan->generator && chan->generator->release)
1182 chan->generator->release(chan, chan->generatordata);
1183 chan->generatordata = NULL;
1186 if ((chan->generatordata = gen->alloc(chan, params))) {
1187 ast_settimeout(chan, 160, generator_force, chan);
1188 chan->generator = gen;
1192 ast_mutex_unlock(&chan->lock);
1196 /*--- ast_waitfor_n_fd: Wait for x amount of time on a file descriptor to have input. */
1197 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
1199 struct timeval start = { 0 , 0 };
1204 struct pollfd *pfds;
1206 pfds = alloca(sizeof(struct pollfd) * n);
1208 ast_log(LOG_ERROR, "Out of memory\n");
1212 start = ast_tvnow();
1214 for (x=0; x < n; x++) {
1216 pfds[y].fd = fds[x];
1217 pfds[y].events = POLLIN | POLLPRI;
1221 res = poll(pfds, y, *ms);
1223 /* Simulate a timeout if we were interrupted */
1231 for (x=0; x < n; x++) {
1233 if ((res = ast_fdisset(pfds, fds[x], y, &spoint))) {
1245 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
1252 /*--- ast_waitfor_nanfds: Wait for x amount of time on a file descriptor to have input. */
1253 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
1254 int *exception, int *outfd, int *ms)
1256 struct timeval start = { 0 , 0 };
1257 struct pollfd *pfds;
1263 long whentohangup = 0, havewhen = 0, diff;
1264 struct ast_channel *winner = NULL;
1266 pfds = alloca(sizeof(struct pollfd) * (n * AST_MAX_FDS + nfds));
1268 ast_log(LOG_ERROR, "Out of memory\n");
1278 /* Perform any pending masquerades */
1279 for (x=0; x < n; x++) {
1280 ast_mutex_lock(&c[x]->lock);
1281 if (c[x]->whentohangup) {
1284 diff = c[x]->whentohangup - now;
1285 if (!havewhen || (diff < whentohangup)) {
1287 whentohangup = diff;
1291 if (ast_do_masquerade(c[x])) {
1292 ast_log(LOG_WARNING, "Masquerade failed\n");
1294 ast_mutex_unlock(&c[x]->lock);
1298 ast_mutex_unlock(&c[x]->lock);
1304 if ((*ms < 0) || (whentohangup * 1000 < *ms)) {
1305 rms = whentohangup * 1000;
1309 for (x=0; x < n; x++) {
1310 for (y=0; y< AST_MAX_FDS; y++) {
1311 if (c[x]->fds[y] > -1) {
1312 pfds[max].fd = c[x]->fds[y];
1313 pfds[max].events = POLLIN | POLLPRI;
1314 pfds[max].revents = 0;
1318 CHECK_BLOCKING(c[x]);
1320 for (x=0; x < nfds; x++) {
1322 pfds[max].fd = fds[x];
1323 pfds[max].events = POLLIN | POLLPRI;
1324 pfds[max].revents = 0;
1329 start = ast_tvnow();
1330 res = poll(pfds, max, rms);
1332 for (x=0; x < n; x++)
1333 ast_clear_flag(c[x], AST_FLAG_BLOCKING);
1334 /* Simulate a timeout if we were interrupted */
1338 /* Just an interrupt */
1345 /* If no fds signalled, then timeout. So set ms = 0
1346 since we may not have an exact timeout.
1355 for (x=0; x < n; x++) {
1356 ast_clear_flag(c[x], AST_FLAG_BLOCKING);
1357 if (havewhen && c[x]->whentohangup && (now > c[x]->whentohangup)) {
1358 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1362 for (y=0; y < AST_MAX_FDS; y++) {
1363 if (c[x]->fds[y] > -1) {
1364 if ((res = ast_fdisset(pfds, c[x]->fds[y], max, &spoint))) {
1366 ast_set_flag(c[x], AST_FLAG_EXCEPTION);
1368 ast_clear_flag(c[x], AST_FLAG_EXCEPTION);
1375 for (x=0; x < nfds; x++) {
1377 if ((res = ast_fdisset(pfds, fds[x], max, &spoint))) {
1391 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
1398 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
1400 return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
1403 int ast_waitfor(struct ast_channel *c, int ms)
1405 struct ast_channel *chan;
1408 chan = ast_waitfor_n(&c, 1, &ms);
1418 int ast_waitfordigit(struct ast_channel *c, int ms)
1420 /* XXX Should I be merged with waitfordigit_full XXX */
1421 struct ast_frame *f;
1424 /* Stop if we're a zombie or need a soft hangup */
1425 if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
1428 /* Wait for a digit, no more than ms milliseconds total. */
1429 while(ms && !result) {
1430 ms = ast_waitfor(c, ms);
1431 if (ms < 0) /* Error */
1434 /* Read something */
1437 if (f->frametype == AST_FRAME_DTMF)
1438 result = f->subclass;
1447 int ast_settimeout(struct ast_channel *c, int samples, int (*func)(void *data), void *data)
1450 #ifdef ZAPTEL_OPTIMIZATIONS
1451 if (c->timingfd > -1) {
1456 ast_log(LOG_DEBUG, "Scheduling timer at %d sample intervals\n", samples);
1457 res = ioctl(c->timingfd, ZT_TIMERCONFIG, &samples);
1458 c->timingfunc = func;
1459 c->timingdata = data;
1465 int ast_waitfordigit_full(struct ast_channel *c, int ms, int audiofd, int cmdfd)
1467 struct ast_frame *f;
1468 struct ast_channel *rchan;
1472 /* Stop if we're a zombie or need a soft hangup */
1473 if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
1475 /* Wait for a digit, no more than ms milliseconds total. */
1478 rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
1479 if ((!rchan) && (outfd < 0) && (ms)) {
1480 if (errno == 0 || errno == EINTR)
1482 ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
1484 } else if (outfd > -1) {
1485 /* The FD we were watching has something waiting */
1493 switch(f->frametype) {
1494 case AST_FRAME_DTMF:
1498 case AST_FRAME_CONTROL:
1499 switch(f->subclass) {
1500 case AST_CONTROL_HANGUP:
1503 case AST_CONTROL_RINGING:
1504 case AST_CONTROL_ANSWER:
1508 ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", f->subclass);
1510 case AST_FRAME_VOICE:
1511 /* Write audio if appropriate */
1513 write(audiofd, f->data, f->datalen);
1519 return 0; /* Time is up */
1522 struct ast_frame *ast_read(struct ast_channel *chan)
1524 struct ast_frame *f = NULL;
1527 #ifdef ZAPTEL_OPTIMIZATIONS
1528 int (*func)(void *);
1532 static struct ast_frame null_frame = {
1536 ast_mutex_lock(&chan->lock);
1538 if (ast_do_masquerade(chan)) {
1539 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1543 ast_mutex_unlock(&chan->lock);
1547 /* Stop if we're a zombie or need a soft hangup */
1548 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
1549 if (chan->generator)
1550 ast_deactivate_generator(chan);
1551 ast_mutex_unlock(&chan->lock);
1554 prestate = chan->_state;
1556 if (!ast_test_flag(chan, AST_FLAG_DEFER_DTMF) && !ast_strlen_zero(chan->dtmfq)) {
1557 /* We have DTMF that has been deferred. Return it now */
1558 chan->dtmff.frametype = AST_FRAME_DTMF;
1559 chan->dtmff.subclass = chan->dtmfq[0];
1560 /* Drop first digit */
1561 memmove(chan->dtmfq, chan->dtmfq + 1, sizeof(chan->dtmfq) - 1);
1562 ast_mutex_unlock(&chan->lock);
1563 return &chan->dtmff;
1566 /* Read and ignore anything on the alertpipe, but read only
1567 one sizeof(blah) per frame that we send from it */
1568 if (chan->alertpipe[0] > -1) {
1569 read(chan->alertpipe[0], &blah, sizeof(blah));
1571 #ifdef ZAPTEL_OPTIMIZATIONS
1572 if ((chan->timingfd > -1) && (chan->fdno == AST_MAX_FDS - 2) && ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
1573 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
1575 /* IF we can't get event, assume it's an expired as-per the old interface */
1576 res = ioctl(chan->timingfd, ZT_GETEVENT, &blah);
1578 blah = ZT_EVENT_TIMER_EXPIRED;
1580 if (blah == ZT_EVENT_TIMER_PING) {
1582 ast_log(LOG_NOTICE, "Oooh, there's a PING!\n");
1584 if (!chan->readq || !chan->readq->next) {
1585 /* Acknowledge PONG unless we need it again */
1587 ast_log(LOG_NOTICE, "Sending a PONG!\n");
1589 if (ioctl(chan->timingfd, ZT_TIMERPONG, &blah)) {
1590 ast_log(LOG_WARNING, "Failed to pong timer on '%s': %s\n", chan->name, strerror(errno));
1593 } else if (blah == ZT_EVENT_TIMER_EXPIRED) {
1594 ioctl(chan->timingfd, ZT_TIMERACK, &blah);
1595 func = chan->timingfunc;
1596 data = chan->timingdata;
1597 ast_mutex_unlock(&chan->lock);
1600 ast_log(LOG_DEBUG, "Calling private function\n");
1605 ast_mutex_lock(&chan->lock);
1606 ioctl(chan->timingfd, ZT_TIMERCONFIG, &blah);
1607 chan->timingdata = NULL;
1608 ast_mutex_unlock(&chan->lock);
1613 ast_log(LOG_NOTICE, "No/unknown event '%d' on timer for '%s'?\n", blah, chan->name);
1616 /* Check for pending read queue */
1619 chan->readq = f->next;
1620 /* Interpret hangup and return NULL */
1621 if ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_HANGUP)) {
1626 chan->blocker = pthread_self();
1627 if (ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
1628 if (chan->tech->exception)
1629 f = chan->tech->exception(chan);
1631 ast_log(LOG_WARNING, "Exception flag set on '%s', but no exception handler\n", chan->name);
1634 /* Clear the exception flag */
1635 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
1637 if (chan->tech->read)
1638 f = chan->tech->read(chan);
1640 ast_log(LOG_WARNING, "No read routine on channel %s\n", chan->name);
1645 if (f && (f->frametype == AST_FRAME_VOICE)) {
1646 if (!(f->subclass & chan->nativeformats)) {
1647 /* This frame can't be from the current native formats -- drop it on the
1649 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));
1654 struct ast_channel_spy *spying;
1655 for (spying = chan->spiers; spying; spying=spying->next) {
1656 ast_queue_spy_frame(spying, f, 0);
1659 if (chan->monitor && chan->monitor->read_stream ) {
1660 #ifndef MONITOR_CONSTANT_DELAY
1661 int jump = chan->outsmpl - chan->insmpl - 2 * f->samples;
1663 if (ast_seekstream(chan->monitor->read_stream, jump + f->samples, SEEK_FORCECUR) == -1)
1664 ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
1665 chan->insmpl += jump + 2 * f->samples;
1667 chan->insmpl+= f->samples;
1669 int jump = chan->outsmpl - chan->insmpl;
1670 if (jump - MONITOR_DELAY >= 0) {
1671 if (ast_seekstream(chan->monitor->read_stream, jump - f->samples, SEEK_FORCECUR) == -1)
1672 ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
1673 chan->insmpl += jump;
1675 chan->insmpl += f->samples;
1677 if (ast_writestream(chan->monitor->read_stream, f) < 0)
1678 ast_log(LOG_WARNING, "Failed to write data to channel monitor read stream\n");
1680 if (chan->readtrans) {
1681 f = ast_translate(chan->readtrans, f, 1);
1688 /* Make sure we always return NULL in the future */
1690 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1691 if (chan->generator)
1692 ast_deactivate_generator(chan);
1693 /* End the CDR if appropriate */
1695 ast_cdr_end(chan->cdr);
1696 } else if (ast_test_flag(chan, AST_FLAG_DEFER_DTMF) && f->frametype == AST_FRAME_DTMF) {
1697 if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2)
1698 chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
1700 ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
1702 } else if ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_ANSWER)) {
1703 if (prestate == AST_STATE_UP) {
1704 ast_log(LOG_DEBUG, "Dropping duplicate answer!\n");
1707 /* Answer the CDR */
1708 ast_setstate(chan, AST_STATE_UP);
1709 ast_cdr_answer(chan->cdr);
1712 /* Run any generator sitting on the line */
1713 if (f && (f->frametype == AST_FRAME_VOICE) && chan->generatordata) {
1714 /* Mask generator data temporarily and apply. If there is a timing function, it
1715 will be calling the generator instead */
1718 int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples);
1720 if (chan->timingfunc) {
1721 ast_log(LOG_DEBUG, "Generator got voice, switching to phase locked mode\n");
1722 ast_settimeout(chan, 0, NULL, NULL);
1724 tmp = chan->generatordata;
1725 chan->generatordata = NULL;
1726 generate = chan->generator->generate;
1727 res = generate(chan, tmp, f->datalen, f->samples);
1728 chan->generatordata = tmp;
1730 ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
1731 ast_deactivate_generator(chan);
1733 } else if (f && (f->frametype == AST_FRAME_CNG)) {
1734 if (chan->generator && !chan->timingfunc && (chan->timingfd > -1)) {
1735 ast_log(LOG_DEBUG, "Generator got CNG, switching to zap timed mode\n");
1736 ast_settimeout(chan, 160, generator_force, chan);
1739 /* High bit prints debugging */
1740 if (chan->fin & 0x80000000)
1741 ast_frame_dump(chan->name, f, "<<");
1742 if ((chan->fin & 0x7fffffff) == 0x7fffffff)
1743 chan->fin &= 0x80000000;
1746 ast_mutex_unlock(&chan->lock);
1750 int ast_indicate(struct ast_channel *chan, int condition)
1754 /* Stop if we're a zombie or need a soft hangup */
1755 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
1757 ast_mutex_lock(&chan->lock);
1758 if (chan->tech->indicate)
1759 res = chan->tech->indicate(chan, condition);
1760 ast_mutex_unlock(&chan->lock);
1761 if (!chan->tech->indicate || res) {
1763 * Device does not support (that) indication, lets fake
1764 * it by doing our own tone generation. (PM2002)
1766 if (condition >= 0) {
1767 const struct tone_zone_sound *ts = NULL;
1768 switch (condition) {
1769 case AST_CONTROL_RINGING:
1770 ts = ast_get_indication_tone(chan->zone, "ring");
1772 case AST_CONTROL_BUSY:
1773 ts = ast_get_indication_tone(chan->zone, "busy");
1775 case AST_CONTROL_CONGESTION:
1776 ts = ast_get_indication_tone(chan->zone, "congestion");
1779 if (ts && ts->data[0]) {
1780 ast_log(LOG_DEBUG, "Driver for channel '%s' does not support indication %d, emulating it\n", chan->name, condition);
1781 ast_playtones_start(chan,0,ts->data, 1);
1783 } else if (condition == AST_CONTROL_PROGRESS) {
1784 /* ast_playtones_stop(chan); */
1785 } else if (condition == AST_CONTROL_PROCEEDING) {
1786 /* Do nothing, really */
1787 } else if (condition == AST_CONTROL_HOLD) {
1788 /* Do nothing.... */
1789 } else if (condition == AST_CONTROL_UNHOLD) {
1790 /* Do nothing.... */
1791 } else if (condition == AST_CONTROL_VIDUPDATE) {
1792 /* Do nothing.... */
1795 ast_log(LOG_WARNING, "Unable to handle indication %d for '%s'\n", condition, chan->name);
1799 else ast_playtones_stop(chan);
1804 int ast_recvchar(struct ast_channel *chan, int timeout)
1807 char *buf = ast_recvtext(chan, timeout);
1809 return -1; /* error or timeout */
1810 c = *(unsigned char *)buf;
1815 char *ast_recvtext(struct ast_channel *chan, int timeout)
1821 struct ast_frame *f;
1822 if (ast_check_hangup(chan))
1824 res = ast_waitfor(chan, timeout);
1825 if (res <= 0) /* timeout or error */
1827 timeout = res; /* update timeout */
1830 break; /* no frame */
1831 if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP)
1832 done = 1; /* force a break */
1833 else if (f->frametype == AST_FRAME_TEXT) { /* what we want */
1834 buf = strndup((char *) f->data, f->datalen); /* dup and break */
1842 int ast_sendtext(struct ast_channel *chan, char *text)
1845 /* Stop if we're a zombie or need a soft hangup */
1846 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
1848 CHECK_BLOCKING(chan);
1849 if (chan->tech->send_text)
1850 res = chan->tech->send_text(chan, text);
1851 ast_clear_flag(chan, AST_FLAG_BLOCKING);
1855 static int do_senddigit(struct ast_channel *chan, char digit)
1859 if (chan->tech->send_digit)
1860 res = chan->tech->send_digit(chan, digit);
1861 if (!chan->tech->send_digit || res) {
1863 * Device does not support DTMF tones, lets fake
1864 * it by doing our own generation. (PM2002)
1866 static const char* dtmf_tones[] = {
1867 "!941+1336/100,!0/100", /* 0 */
1868 "!697+1209/100,!0/100", /* 1 */
1869 "!697+1336/100,!0/100", /* 2 */
1870 "!697+1477/100,!0/100", /* 3 */
1871 "!770+1209/100,!0/100", /* 4 */
1872 "!770+1336/100,!0/100", /* 5 */
1873 "!770+1477/100,!0/100", /* 6 */
1874 "!852+1209/100,!0/100", /* 7 */
1875 "!852+1336/100,!0/100", /* 8 */
1876 "!852+1477/100,!0/100", /* 9 */
1877 "!697+1633/100,!0/100", /* A */
1878 "!770+1633/100,!0/100", /* B */
1879 "!852+1633/100,!0/100", /* C */
1880 "!941+1633/100,!0/100", /* D */
1881 "!941+1209/100,!0/100", /* * */
1882 "!941+1477/100,!0/100" }; /* # */
1883 if (digit >= '0' && digit <='9')
1884 ast_playtones_start(chan, 0, dtmf_tones[digit-'0'], 0);
1885 else if (digit >= 'A' && digit <= 'D')
1886 ast_playtones_start(chan, 0, dtmf_tones[digit-'A'+10], 0);
1887 else if (digit == '*')
1888 ast_playtones_start(chan, 0, dtmf_tones[14], 0);
1889 else if (digit == '#')
1890 ast_playtones_start(chan, 0, dtmf_tones[15], 0);
1893 ast_log(LOG_DEBUG, "Unable to generate DTMF tone '%c' for '%s'\n", digit, chan->name);
1899 int ast_senddigit(struct ast_channel *chan, char digit)
1901 return do_senddigit(chan, digit);
1904 int ast_prod(struct ast_channel *chan)
1906 struct ast_frame a = { AST_FRAME_VOICE };
1909 /* Send an empty audio frame to get things moving */
1910 if (chan->_state != AST_STATE_UP) {
1911 ast_log(LOG_DEBUG, "Prodding channel '%s'\n", chan->name);
1912 a.subclass = chan->rawwriteformat;
1913 a.data = nothing + AST_FRIENDLY_OFFSET;
1915 if (ast_write(chan, &a))
1916 ast_log(LOG_WARNING, "Prodding channel '%s' failed\n", chan->name);
1921 int ast_write_video(struct ast_channel *chan, struct ast_frame *fr)
1924 if (!chan->tech->write_video)
1926 res = ast_write(chan, fr);
1932 int ast_write(struct ast_channel *chan, struct ast_frame *fr)
1935 struct ast_frame *f = NULL;
1936 /* Stop if we're a zombie or need a soft hangup */
1937 ast_mutex_lock(&chan->lock);
1938 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
1939 ast_mutex_unlock(&chan->lock);
1942 /* Handle any pending masquerades */
1944 if (ast_do_masquerade(chan)) {
1945 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1946 ast_mutex_unlock(&chan->lock);
1951 ast_mutex_unlock(&chan->lock);
1954 if (chan->generatordata) {
1955 if (ast_test_flag(chan, AST_FLAG_WRITE_INT))
1956 ast_deactivate_generator(chan);
1958 ast_mutex_unlock(&chan->lock);
1962 /* High bit prints debugging */
1963 if (chan->fout & 0x80000000)
1964 ast_frame_dump(chan->name, fr, ">>");
1965 CHECK_BLOCKING(chan);
1966 switch(fr->frametype) {
1967 case AST_FRAME_CONTROL:
1968 /* XXX Interpret control frames XXX */
1969 ast_log(LOG_WARNING, "Don't know how to handle control frames yet\n");
1971 case AST_FRAME_DTMF:
1972 ast_clear_flag(chan, AST_FLAG_BLOCKING);
1973 ast_mutex_unlock(&chan->lock);
1974 res = do_senddigit(chan,fr->subclass);
1975 ast_mutex_lock(&chan->lock);
1976 CHECK_BLOCKING(chan);
1978 case AST_FRAME_TEXT:
1979 if (chan->tech->send_text)
1980 res = chan->tech->send_text(chan, (char *) fr->data);
1984 case AST_FRAME_HTML:
1985 if (chan->tech->send_html)
1986 res = chan->tech->send_html(chan, fr->subclass, (char *) fr->data, fr->datalen);
1990 case AST_FRAME_VIDEO:
1991 /* XXX Handle translation of video codecs one day XXX */
1992 if (chan->tech->write_video)
1993 res = chan->tech->write_video(chan, fr);
1998 if (chan->tech->write) {
1999 if (chan->writetrans)
2000 f = ast_translate(chan->writetrans, fr, 0);
2004 if (f->frametype == AST_FRAME_VOICE && chan->spiers) {
2005 struct ast_channel_spy *spying;
2006 for (spying = chan->spiers; spying; spying=spying->next) {
2007 ast_queue_spy_frame(spying, f, 1);
2011 if( chan->monitor && chan->monitor->write_stream &&
2012 f && ( f->frametype == AST_FRAME_VOICE ) ) {
2013 #ifndef MONITOR_CONSTANT_DELAY
2014 int jump = chan->insmpl - chan->outsmpl - 2 * f->samples;
2016 if (ast_seekstream(chan->monitor->write_stream, jump + f->samples, SEEK_FORCECUR) == -1)
2017 ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
2018 chan->outsmpl += jump + 2 * f->samples;
2020 chan->outsmpl += f->samples;
2022 int jump = chan->insmpl - chan->outsmpl;
2023 if (jump - MONITOR_DELAY >= 0) {
2024 if (ast_seekstream(chan->monitor->write_stream, jump - f->samples, SEEK_FORCECUR) == -1)
2025 ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
2026 chan->outsmpl += jump;
2028 chan->outsmpl += f->samples;
2030 if (ast_writestream(chan->monitor->write_stream, f) < 0)
2031 ast_log(LOG_WARNING, "Failed to write data to channel monitor write stream\n");
2034 res = chan->tech->write(chan, f);
2040 /* It's possible this is a translated frame */
2041 if (f && f->frametype == AST_FRAME_DTMF) {
2042 ast_log(LOG_DTMF, "%s : %c\n", chan->name, f->subclass);
2043 } else if (fr->frametype == AST_FRAME_DTMF) {
2044 ast_log(LOG_DTMF, "%s : %c\n", chan->name, fr->subclass);
2049 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2050 /* Consider a write failure to force a soft hangup */
2052 chan->_softhangup |= AST_SOFTHANGUP_DEV;
2054 if ((chan->fout & 0x7fffffff) == 0x7fffffff)
2055 chan->fout &= 0x80000000;
2059 ast_mutex_unlock(&chan->lock);
2063 static int set_format(struct ast_channel *chan, int fmt, int *rawformat, int *format,
2064 struct ast_trans_pvt **trans, const int direction)
2069 native = chan->nativeformats;
2070 /* Find a translation path from the native format to one of the desired formats */
2073 res = ast_translator_best_choice(&fmt, &native);
2076 res = ast_translator_best_choice(&native, &fmt);
2079 ast_log(LOG_WARNING, "Unable to find a codec translation path from %s to %s\n",
2080 ast_getformatname(native), ast_getformatname(fmt));
2084 /* Now we have a good choice for both. */
2085 ast_mutex_lock(&chan->lock);
2086 *rawformat = native;
2087 /* User perspective is fmt */
2089 /* Free any read translation we have right now */
2091 ast_translator_free_path(*trans);
2092 /* Build a translation path from the raw format to the desired format */
2095 *trans = ast_translator_build_path(*format, *rawformat);
2098 *trans = ast_translator_build_path(*rawformat, *format);
2099 ast_mutex_unlock(&chan->lock);
2101 ast_log(LOG_DEBUG, "Set channel %s to %s format %s\n", chan->name,
2102 direction ? "write" : "read", ast_getformatname(fmt));
2106 int ast_set_read_format(struct ast_channel *chan, int fmt)
2108 return set_format(chan, fmt, &chan->rawreadformat, &chan->readformat,
2109 &chan->readtrans, 0);
2112 int ast_set_write_format(struct ast_channel *chan, int fmt)
2114 return set_format(chan, fmt, &chan->rawwriteformat, &chan->writeformat,
2115 &chan->writetrans, 1);
2118 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)
2122 struct ast_channel *chan;
2123 struct ast_frame *f;
2126 chan = ast_request(type, format, data, &cause);
2129 ast_set_variables(chan, oh->vars);
2130 ast_set_callerid(chan, oh->cid_num, oh->cid_name, oh->cid_num);
2132 ast_set_callerid(chan, cid_num, cid_name, cid_num);
2134 if (!ast_call(chan, data, 0)) {
2135 while(timeout && (chan->_state != AST_STATE_UP)) {
2136 res = ast_waitfor(chan, timeout);
2138 /* Something not cool, or timed out */
2141 /* If done, break out */
2148 state = AST_CONTROL_HANGUP;
2152 if (f->frametype == AST_FRAME_CONTROL) {
2153 if (f->subclass == AST_CONTROL_RINGING)
2154 state = AST_CONTROL_RINGING;
2155 else if ((f->subclass == AST_CONTROL_BUSY) || (f->subclass == AST_CONTROL_CONGESTION)) {
2156 state = f->subclass;
2159 } else if (f->subclass == AST_CONTROL_ANSWER) {
2160 state = f->subclass;
2163 } else if (f->subclass == AST_CONTROL_PROGRESS) {
2165 } else if (f->subclass == -1) {
2166 /* Ignore -- just stopping indications */
2168 ast_log(LOG_NOTICE, "Don't know what to do with control frame %d\n", f->subclass);
2174 ast_log(LOG_NOTICE, "Unable to call channel %s/%s\n", type, (char *)data);
2176 ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
2178 case AST_CAUSE_BUSY:
2179 state = AST_CONTROL_BUSY;
2181 case AST_CAUSE_CONGESTION:
2182 state = AST_CONTROL_CONGESTION;
2189 if (oh->context && *oh->context)
2190 ast_copy_string(chan->context, oh->context, sizeof(chan->context));
2191 if (oh->exten && *oh->exten)
2192 ast_copy_string(chan->exten, oh->exten, sizeof(chan->exten));
2194 chan->priority = oh->priority;
2196 if (chan->_state == AST_STATE_UP)
2197 state = AST_CONTROL_ANSWER;
2201 if (chan && res <= 0) {
2203 chan->cdr = ast_cdr_alloc();
2205 ast_cdr_init(chan->cdr, chan);
2209 snprintf(tmp, 256, "%s/%s", type, (char *)data);
2210 ast_cdr_setapp(chan->cdr,"Dial",tmp);
2211 ast_cdr_update(chan);
2212 ast_cdr_start(chan->cdr);
2213 ast_cdr_end(chan->cdr);
2214 /* If the cause wasn't handled properly */
2215 if (ast_cdr_disposition(chan->cdr,chan->hangupcause))
2216 ast_cdr_failed(chan->cdr);
2218 ast_log(LOG_WARNING, "Unable to create Call Detail Record\n");
2225 struct ast_channel *ast_request_and_dial(const char *type, int format, void *data, int timeout, int *outstate, const char *cidnum, const char *cidname)
2227 return __ast_request_and_dial(type, format, data, timeout, outstate, cidnum, cidname, NULL);
2230 struct ast_channel *ast_request(const char *type, int format, void *data, int *cause)
2232 struct chanlist *chan;
2233 struct ast_channel *c;
2241 *cause = AST_CAUSE_NOTDEFINED;
2243 if (ast_mutex_lock(&chlock)) {
2244 ast_log(LOG_WARNING, "Unable to lock channel list\n");
2248 for (chan = backends; chan; chan = chan->next) {
2249 if (strcasecmp(type, chan->tech->type))
2252 capabilities = chan->tech->capabilities;
2254 res = ast_translator_best_choice(&fmt, &capabilities);
2256 ast_log(LOG_WARNING, "No translator path exists for channel type %s (native %d) to %d\n", type, chan->tech->capabilities, format);
2257 ast_mutex_unlock(&chlock);
2260 ast_mutex_unlock(&chlock);
2261 if (!chan->tech->requester)
2264 if (!(c = chan->tech->requester(type, capabilities, data, cause)))
2267 if (c->_state == AST_STATE_DOWN) {
2268 manager_event(EVENT_FLAG_CALL, "Newchannel",
2272 "CallerIDName: %s\r\n"
2274 c->name, ast_state2str(c->_state),
2275 c->cid.cid_num ? c->cid.cid_num : "<unknown>",
2276 c->cid.cid_name ? c->cid.cid_name : "<unknown>",
2282 ast_log(LOG_WARNING, "No channel type registered for '%s'\n", type);
2283 *cause = AST_CAUSE_NOSUCHDRIVER;
2284 ast_mutex_unlock(&chlock);
2289 int ast_call(struct ast_channel *chan, char *addr, int timeout)
2291 /* Place an outgoing call, but don't wait any longer than timeout ms before returning.
2292 If the remote end does not answer within the timeout, then do NOT hang up, but
2295 /* Stop if we're a zombie or need a soft hangup */
2296 ast_mutex_lock(&chan->lock);
2297 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan))
2298 if (chan->tech->call)
2299 res = chan->tech->call(chan, addr, timeout);
2300 ast_mutex_unlock(&chan->lock);
2304 /*--- ast_transfer: Transfer a call to dest, if the channel supports transfer */
2305 /* called by app_transfer or the manager interface */
2306 int ast_transfer(struct ast_channel *chan, char *dest)
2310 /* Stop if we're a zombie or need a soft hangup */
2311 ast_mutex_lock(&chan->lock);
2312 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
2313 if (chan->tech->transfer) {
2314 res = chan->tech->transfer(chan, dest);
2320 ast_mutex_unlock(&chan->lock);
2324 int ast_readstring(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders)
2330 /* XXX Merge with full version? XXX */
2331 /* Stop if we're a zombie or need a soft hangup */
2332 if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
2338 d = ast_waitstream(c, AST_DIGIT_ANY);
2342 d = ast_waitfordigit(c, to);
2344 d = ast_waitfordigit(c, to);
2352 if (!strchr(enders, d))
2354 if (strchr(enders, d) || (pos >= len)) {
2364 int ast_readstring_full(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders, int audiofd, int ctrlfd)
2370 /* Stop if we're a zombie or need a soft hangup */
2371 if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
2377 d = ast_waitstream_full(c, AST_DIGIT_ANY, audiofd, ctrlfd);
2381 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
2383 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
2395 if (!strchr(enders, d))
2397 if (strchr(enders, d) || (pos >= len)) {
2407 int ast_channel_supports_html(struct ast_channel *chan)
2409 if (chan->tech->send_html)
2414 int ast_channel_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
2416 if (chan->tech->send_html)
2417 return chan->tech->send_html(chan, subclass, data, datalen);
2421 int ast_channel_sendurl(struct ast_channel *chan, const char *url)
2423 if (chan->tech->send_html)
2424 return chan->tech->send_html(chan, AST_HTML_URL, url, strlen(url) + 1);
2428 int ast_channel_make_compatible(struct ast_channel *chan, struct ast_channel *peer)
2433 /* Set up translation from the chan to the peer */
2434 src = chan->nativeformats;
2435 dst = peer->nativeformats;
2436 if (ast_translator_best_choice(&dst, &src) < 0) {
2437 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", chan->name, src, peer->name, dst);
2441 /* if the best path is not 'pass through', then
2442 transcoding is needed; if desired, force transcode path
2443 to use SLINEAR between channels */
2444 if ((src != dst) && option_transcode_slin)
2445 dst = AST_FORMAT_SLINEAR;
2446 if (ast_set_read_format(chan, dst) < 0) {
2447 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", chan->name, dst);
2450 if (ast_set_write_format(peer, dst) < 0) {
2451 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", peer->name, dst);
2455 /* Set up translation from the peer to the chan */
2456 src = peer->nativeformats;
2457 dst = chan->nativeformats;
2458 if (ast_translator_best_choice(&dst, &src) < 0) {
2459 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", peer->name, src, chan->name, dst);
2462 /* if the best path is not 'pass through', then
2463 transcoding is needed; if desired, force transcode path
2464 to use SLINEAR between channels */
2465 if ((src != dst) && option_transcode_slin)
2466 dst = AST_FORMAT_SLINEAR;
2467 if (ast_set_read_format(peer, dst) < 0) {
2468 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", peer->name, dst);
2471 if (ast_set_write_format(chan, dst) < 0) {
2472 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", chan->name, dst);
2478 int ast_channel_masquerade(struct ast_channel *original, struct ast_channel *clone)
2480 struct ast_frame null = { AST_FRAME_NULL, };
2483 if (original == clone) {
2484 ast_log(LOG_WARNING, "Can't masquerade channel '%s' into itself!\n", original->name);
2487 ast_mutex_lock(&original->lock);
2488 while(ast_mutex_trylock(&clone->lock)) {
2489 ast_mutex_unlock(&original->lock);
2491 ast_mutex_lock(&original->lock);
2493 ast_log(LOG_DEBUG, "Planning to masquerade channel %s into the structure of %s\n",
2494 clone->name, original->name);
2495 if (original->masq) {
2496 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n",
2497 original->masq->name, original->name);
2498 } else if (clone->masqr) {
2499 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n",
2500 clone->name, clone->masqr->name);
2502 original->masq = clone;
2503 clone->masqr = original;
2504 ast_queue_frame(original, &null);
2505 ast_queue_frame(clone, &null);
2506 ast_log(LOG_DEBUG, "Done planning to masquerade channel %s into the structure of %s\n", clone->name, original->name);
2509 ast_mutex_unlock(&clone->lock);
2510 ast_mutex_unlock(&original->lock);
2514 void ast_change_name(struct ast_channel *chan, char *newname)
2517 ast_copy_string(tmp, chan->name, sizeof(tmp));
2518 ast_copy_string(chan->name, newname, sizeof(chan->name));
2519 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", tmp, chan->name, chan->uniqueid);
2522 void ast_channel_inherit_variables(const struct ast_channel *parent, struct ast_channel *child)
2524 struct ast_var_t *current, *newvar;
2527 AST_LIST_TRAVERSE(&parent->varshead, current, entries) {
2530 varname = ast_var_full_name(current);
2534 if (varname[0] == '_') {
2536 if (varname[1] == '_')
2542 newvar = ast_var_assign(&varname[1], ast_var_value(current));
2544 AST_LIST_INSERT_TAIL(&child->varshead, newvar, entries);
2546 ast_log(LOG_DEBUG, "Copying soft-transferable variable %s.\n", ast_var_name(newvar));
2550 newvar = ast_var_assign(ast_var_full_name(current), ast_var_value(current));
2552 AST_LIST_INSERT_TAIL(&child->varshead, newvar, entries);
2554 ast_log(LOG_DEBUG, "Copying hard-transferable variable %s.\n", ast_var_name(newvar));
2559 ast_log(LOG_DEBUG, "Not copying variable %s.\n", ast_var_name(current));
2565 /* Clone channel variables from 'clone' channel into 'original' channel
2566 All variables except those related to app_groupcount are cloned
2567 Variables are actually _removed_ from 'clone' channel, presumably
2568 because it will subsequently be destroyed.
2569 Assumes locks will be in place on both channels when called.
2572 static void clone_variables(struct ast_channel *original, struct ast_channel *clone)
2574 struct ast_var_t *varptr;
2576 /* we need to remove all app_groupcount related variables from the original
2577 channel before merging in the clone's variables; any groups assigned to the
2578 original channel should be released, only those assigned to the clone
2582 AST_LIST_TRAVERSE_SAFE_BEGIN(&original->varshead, varptr, entries) {
2583 if (!strncmp(ast_var_name(varptr), GROUP_CATEGORY_PREFIX, strlen(GROUP_CATEGORY_PREFIX))) {
2584 AST_LIST_REMOVE(&original->varshead, varptr, entries);
2585 ast_var_delete(varptr);
2588 AST_LIST_TRAVERSE_SAFE_END;
2590 /* Append variables from clone channel into original channel */
2591 /* XXX Is this always correct? We have to in order to keep MACROS working XXX */
2592 if (AST_LIST_FIRST(&clone->varshead))
2593 AST_LIST_INSERT_TAIL(&original->varshead, AST_LIST_FIRST(&clone->varshead), entries);
2596 /*--- ast_do_masquerade: Masquerade a channel */
2597 /* Assumes channel will be locked when called */
2598 int ast_do_masquerade(struct ast_channel *original)
2603 struct ast_frame *cur, *prev;
2604 const struct ast_channel_tech *t;
2606 struct ast_callerid tmpcid;
2607 struct ast_channel *clone = original->masq;
2608 int rformat = original->readformat;
2609 int wformat = original->writeformat;
2615 if (option_debug > 3)
2616 ast_log(LOG_DEBUG, "Actually Masquerading %s(%d) into the structure of %s(%d)\n",
2617 clone->name, clone->_state, original->name, original->_state);
2619 /* XXX This is a seriously wacked out operation. We're essentially putting the guts of
2620 the clone channel into the original channel. Start by killing off the original
2621 channel's backend. I'm not sure we're going to keep this function, because
2622 while the features are nice, the cost is very high in terms of pure nastiness. XXX */
2624 /* We need the clone's lock, too */
2625 ast_mutex_lock(&clone->lock);
2627 ast_log(LOG_DEBUG, "Got clone lock for masquerade on '%s' at %p\n", clone->name, &clone->lock);
2629 /* Having remembered the original read/write formats, we turn off any translation on either
2631 free_translation(clone);
2632 free_translation(original);
2635 /* Unlink the masquerade */
2636 original->masq = NULL;
2637 clone->masqr = NULL;
2639 /* Save the original name */
2640 ast_copy_string(orig, original->name, sizeof(orig));
2641 /* Save the new name */
2642 ast_copy_string(newn, clone->name, sizeof(newn));
2643 /* Create the masq name */
2644 snprintf(masqn, sizeof(masqn), "%s<MASQ>", newn);
2646 /* Copy the name from the clone channel */
2647 ast_copy_string(original->name, newn, sizeof(original->name));
2649 /* Mangle the name of the clone channel */
2650 ast_copy_string(clone->name, masqn, sizeof(clone->name));
2652 /* Notify any managers of the change, first the masq then the other */
2653 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", newn, masqn, clone->uniqueid);
2654 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", orig, newn, original->uniqueid);
2656 /* Swap the technlogies */
2658 original->tech = clone->tech;
2661 t_pvt = original->tech_pvt;
2662 original->tech_pvt = clone->tech_pvt;
2663 clone->tech_pvt = t_pvt;
2665 /* Swap the readq's */
2666 cur = original->readq;
2667 original->readq = clone->readq;
2670 /* Swap the alertpipes */
2671 for (i = 0; i < 2; i++) {
2672 x = original->alertpipe[i];
2673 original->alertpipe[i] = clone->alertpipe[i];
2674 clone->alertpipe[i] = x;
2677 /* Swap the raw formats */
2678 x = original->rawreadformat;
2679 original->rawreadformat = clone->rawreadformat;
2680 clone->rawreadformat = x;
2681 x = original->rawwriteformat;
2682 original->rawwriteformat = clone->rawwriteformat;
2683 clone->rawwriteformat = x;
2685 /* Save any pending frames on both sides. Start by counting
2686 * how many we're going to need... */
2695 /* If we had any, prepend them to the ones already in the queue, and
2696 * load up the alertpipe */
2698 prev->next = original->readq;
2699 original->readq = clone->readq;
2700 clone->readq = NULL;
2701 if (original->alertpipe[1] > -1) {
2702 for (i = 0; i < x; i++)
2703 write(original->alertpipe[1], &x, sizeof(x));
2706 clone->_softhangup = AST_SOFTHANGUP_DEV;
2709 /* And of course, so does our current state. Note we need not
2710 call ast_setstate since the event manager doesn't really consider
2711 these separate. We do this early so that the clone has the proper
2712 state of the original channel. */
2713 origstate = original->_state;
2714 original->_state = clone->_state;
2715 clone->_state = origstate;
2717 if (clone->tech->fixup){
2718 res = clone->tech->fixup(original, clone);
2720 ast_log(LOG_WARNING, "Fixup failed on channel %s, strange things may happen.\n", clone->name);
2723 /* Start by disconnecting the original's physical side */
2724 if (clone->tech->hangup)
2725 res = clone->tech->hangup(clone);
2727 ast_log(LOG_WARNING, "Hangup failed! Strange things may happen!\n");
2728 ast_mutex_unlock(&clone->lock);
2732 snprintf(zombn, sizeof(zombn), "%s<ZOMBIE>", orig);
2733 /* Mangle the name of the clone channel */
2734 ast_copy_string(clone->name, zombn, sizeof(clone->name));
2735 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", masqn, zombn, clone->uniqueid);
2737 /* Update the type. */
2738 original->type = clone->type;
2739 t_pvt = original->monitor;
2740 original->monitor = clone->monitor;
2741 clone->monitor = t_pvt;
2743 /* Keep the same language. */
2744 ast_copy_string(original->language, clone->language, sizeof(original->language));
2746 for (x = 0; x < AST_MAX_FDS; x++) {
2747 original->fds[x] = clone->fds[x];
2749 clone_variables(original, clone);
2750 clone->varshead.first = NULL;
2751 /* Presense of ADSI capable CPE follows clone */
2752 original->adsicpe = clone->adsicpe;
2753 /* Bridge remains the same */
2754 /* CDR fields remain the same */
2755 /* XXX What about blocking, softhangup, blocker, and lock and blockproc? XXX */
2756 /* Application and data remain the same */
2757 /* Clone exception becomes real one, as with fdno */
2758 ast_copy_flags(original, clone, AST_FLAG_EXCEPTION);
2759 original->fdno = clone->fdno;
2760 /* Schedule context remains the same */
2761 /* Stream stuff stays the same */
2762 /* Keep the original state. The fixup code will need to work with it most likely */
2764 /* Just swap the whole structures, nevermind the allocations, they'll work themselves
2766 tmpcid = original->cid;
2767 original->cid = clone->cid;
2768 clone->cid = tmpcid;
2770 /* Restore original timing file descriptor */
2771 original->fds[AST_MAX_FDS - 2] = original->timingfd;
2773 /* Our native formats are different now */
2774 original->nativeformats = clone->nativeformats;
2776 /* Context, extension, priority, app data, jump table, remain the same */
2777 /* pvt switches. pbx stays the same, as does next */
2779 /* Set the write format */
2780 ast_set_write_format(original, wformat);
2782 /* Set the read format */
2783 ast_set_read_format(original, rformat);
2785 /* Copy the music class */
2786 ast_copy_string(original->musicclass, clone->musicclass, sizeof(original->musicclass));
2788 ast_log(LOG_DEBUG, "Putting channel %s in %d/%d formats\n", original->name, wformat, rformat);
2790 /* Okay. Last thing is to let the channel driver know about all this mess, so he
2791 can fix up everything as best as possible */
2792 if (original->tech->fixup) {
2793 res = original->tech->fixup(clone, original);
2795 ast_log(LOG_WARNING, "Channel for type '%s' could not fixup channel %s\n",
2796 original->type, original->name);
2797 ast_mutex_unlock(&clone->lock);
2801 ast_log(LOG_WARNING, "Channel type '%s' does not have a fixup routine (for %s)! Bad things may happen.\n",
2802 original->type, original->name);
2804 /* Now, at this point, the "clone" channel is totally F'd up. We mark it as
2805 a zombie so nothing tries to touch it. If it's already been marked as a
2806 zombie, then free it now (since it already is considered invalid). */
2807 if (ast_test_flag(clone, AST_FLAG_ZOMBIE)) {
2808 ast_log(LOG_DEBUG, "Destroying channel clone '%s'\n", clone->name);
2809 ast_mutex_unlock(&clone->lock);
2810 ast_channel_free(clone);
2811 manager_event(EVENT_FLAG_CALL, "Hangup",
2815 "Cause-txt: %s\r\n",
2819 ast_cause2str(clone->hangupcause)
2822 struct ast_frame null_frame = { AST_FRAME_NULL, };
2823 ast_log(LOG_DEBUG, "Released clone lock on '%s'\n", clone->name);
2824 ast_set_flag(clone, AST_FLAG_ZOMBIE);
2825 ast_queue_frame(clone, &null_frame);
2826 ast_mutex_unlock(&clone->lock);
2829 /* Signal any blocker */
2830 if (ast_test_flag(original, AST_FLAG_BLOCKING))
2831 pthread_kill(original->blocker, SIGURG);
2832 ast_log(LOG_DEBUG, "Done Masquerading %s (%d)\n", original->name, original->_state);
2836 void ast_set_callerid(struct ast_channel *chan, const char *callerid, const char *calleridname, const char *ani)
2839 if (chan->cid.cid_num)
2840 free(chan->cid.cid_num);
2841 if (ast_strlen_zero(callerid))
2842 chan->cid.cid_num = NULL;
2844 chan->cid.cid_num = strdup(callerid);
2847 if (chan->cid.cid_name)
2848 free(chan->cid.cid_name);
2849 if (ast_strlen_zero(calleridname))
2850 chan->cid.cid_name = NULL;
2852 chan->cid.cid_name = strdup(calleridname);
2855 if (chan->cid.cid_ani)
2856 free(chan->cid.cid_ani);
2857 if (ast_strlen_zero(ani))
2858 chan->cid.cid_ani = NULL;
2860 chan->cid.cid_ani = strdup(ani);
2863 ast_cdr_setcid(chan->cdr, chan);
2864 manager_event(EVENT_FLAG_CALL, "Newcallerid",
2867 "CallerIDName: %s\r\n"
2869 "CID-CallingPres: %d (%s)\r\n",
2870 chan->name, chan->cid.cid_num ?
2871 chan->cid.cid_num : "<Unknown>",
2872 chan->cid.cid_name ?
2873 chan->cid.cid_name : "<Unknown>",
2876 ast_describe_caller_presentation(chan->cid.cid_pres)
2880 int ast_setstate(struct ast_channel *chan, int state)
2882 int oldstate = chan->_state;
2884 if (oldstate == state)
2887 chan->_state = state;
2888 ast_device_state_changed(chan->name);
2889 manager_event(EVENT_FLAG_CALL,
2890 (oldstate == AST_STATE_DOWN) ? "Newchannel" : "Newstate",
2894 "CallerIDName: %s\r\n"
2896 chan->name, ast_state2str(chan->_state),
2897 chan->cid.cid_num ? chan->cid.cid_num : "<unknown>",
2898 chan->cid.cid_name ? chan->cid.cid_name : "<unknown>",
2904 /*--- Find bridged channel */
2905 struct ast_channel *ast_bridged_channel(struct ast_channel *chan)
2907 struct ast_channel *bridged;
2908 bridged = chan->_bridge;
2909 if (bridged && bridged->tech->bridged_channel)
2910 bridged = bridged->tech->bridged_channel(chan, bridged);
2914 static void bridge_playfile(struct ast_channel *chan, struct ast_channel *peer, char *sound, int remain)
2916 int res=0, min=0, sec=0,check=0;
2918 check = ast_autoservice_start(peer);
2923 if (remain / 60 > 1) {
2931 if (!strcmp(sound,"timeleft")) { /* Queue support */
2932 res = ast_streamfile(chan, "vm-youhave", chan->language);
2933 res = ast_waitstream(chan, "");
2935 res = ast_say_number(chan, min, AST_DIGIT_ANY, chan->language, (char *) NULL);
2936 res = ast_streamfile(chan, "queue-minutes", chan->language);
2937 res = ast_waitstream(chan, "");
2940 res = ast_say_number(chan, sec, AST_DIGIT_ANY, chan->language, (char *) NULL);
2941 res = ast_streamfile(chan, "queue-seconds", chan->language);
2942 res = ast_waitstream(chan, "");
2945 res = ast_streamfile(chan, sound, chan->language);
2946 res = ast_waitstream(chan, "");
2949 check = ast_autoservice_stop(peer);
2952 static enum ast_bridge_result ast_generic_bridge(struct ast_channel *c0, struct ast_channel *c1,
2953 struct ast_bridge_config *config, struct ast_frame **fo, struct ast_channel **rc, int toms)
2955 /* Copy voice back and forth between the two channels. */
2956 struct ast_channel *cs[3];
2957 struct ast_frame *f;
2958 struct ast_channel *who = NULL;
2959 enum ast_bridge_result res = AST_BRIDGE_COMPLETE;
2960 int o0nativeformats;
2961 int o1nativeformats;
2968 pvt0 = c0->tech_pvt;
2969 pvt1 = c1->tech_pvt;
2970 o0nativeformats = c0->nativeformats;
2971 o1nativeformats = c1->nativeformats;
2972 watch_c0_dtmf = config->flags & AST_BRIDGE_DTMF_CHANNEL_0;
2973 watch_c1_dtmf = config->flags & AST_BRIDGE_DTMF_CHANNEL_1;
2976 if ((c0->tech_pvt != pvt0) || (c1->tech_pvt != pvt1) ||
2977 (o0nativeformats != c0->nativeformats) ||
2978 (o1nativeformats != c1->nativeformats)) {
2979 /* Check for Masquerade, codec changes, etc */
2980 res = AST_BRIDGE_RETRY;
2983 who = ast_waitfor_n(cs, 2, &toms);
2985 ast_log(LOG_DEBUG, "Nobody there, continuing...\n");
2986 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE || c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE) {
2987 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
2988 c0->_softhangup = 0;
2989 if (c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
2990 c1->_softhangup = 0;
3000 res = AST_BRIDGE_COMPLETE;
3001 ast_log(LOG_DEBUG, "Didn't get a frame from channel: %s\n",who->name);
3005 if ((f->frametype == AST_FRAME_CONTROL) && !(config->flags & AST_BRIDGE_IGNORE_SIGS)) {
3006 if ((f->subclass == AST_CONTROL_HOLD) || (f->subclass == AST_CONTROL_UNHOLD) ||
3007 (f->subclass == AST_CONTROL_VIDUPDATE)) {
3008 ast_indicate(who == c0 ? c1 : c0, f->subclass);
3012 res = AST_BRIDGE_COMPLETE;
3013 ast_log(LOG_DEBUG, "Got a FRAME_CONTROL (%d) frame on channel %s\n", f->subclass, who->name);
3017 if ((f->frametype == AST_FRAME_VOICE) ||
3018 (f->frametype == AST_FRAME_DTMF) ||
3019 (f->frametype == AST_FRAME_VIDEO) ||
3020 (f->frametype == AST_FRAME_IMAGE) ||
3021 (f->frametype == AST_FRAME_HTML) ||
3022 (f->frametype == AST_FRAME_TEXT)) {
3023 if (f->frametype == AST_FRAME_DTMF) {
3024 if (((who == c0) && watch_c0_dtmf) ||
3025 ((who == c1) && watch_c1_dtmf)) {
3028 res = AST_BRIDGE_COMPLETE;
3029 ast_log(LOG_DEBUG, "Got DTMF on channel (%s)\n", who->name);
3036 ast_log(LOG_DEBUG, "Read from %s\n", who->name);
3038 ast_log(LOG_DEBUG, "Servicing channel %s twice in a row?\n", last->name);
3042 ast_write((who == c0) ? c1 : c0, f);
3047 /* Swap who gets priority */
3055 /*--- ast_channel_bridge: Bridge two channels together */
3056 enum ast_bridge_result ast_channel_bridge(struct ast_channel *c0, struct ast_channel *c1,
3057 struct ast_bridge_config *config, struct ast_frame **fo, struct ast_channel **rc)
3059 struct ast_channel *who = NULL;
3060 enum ast_bridge_result res = AST_BRIDGE_COMPLETE;
3063 int o0nativeformats;
3064 int o1nativeformats;
3065 long time_left_ms=0;
3066 struct timeval nexteventts = { 0, };
3067 char caller_warning = 0;
3068 char callee_warning = 0;
3072 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n",
3073 c0->name, c0->_bridge->name);
3077 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n",
3078 c1->name, c1->_bridge->name);
3082 /* Stop if we're a zombie or need a soft hangup */
3083 if (ast_test_flag(c0, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c0) ||
3084 ast_test_flag(c1, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c1))
3088 firstpass = config->firstpass;
3089 config->firstpass = 0;
3091 if (ast_tvzero(config->start_time))
3092 config->start_time = ast_tvnow();
3093 time_left_ms = config->timelimit;
3095 caller_warning = ast_test_flag(&config->features_caller, AST_FEATURE_PLAY_WARNING);
3096 callee_warning = ast_test_flag(&config->features_callee, AST_FEATURE_PLAY_WARNING);
3098 if (config->start_sound && firstpass) {
3100 bridge_playfile(c0, c1, config->start_sound, time_left_ms / 1000);
3102 bridge_playfile(c1, c0, config->start_sound, time_left_ms / 1000);
3105 /* Keep track of bridge */
3109 manager_event(EVENT_FLAG_CALL, "Link",
3115 "CallerID2: %s\r\n",
3116 c0->name, c1->name, c0->uniqueid, c1->uniqueid, c0->cid.cid_num, c1->cid.cid_num);
3118 o0nativeformats = c0->nativeformats;
3119 o1nativeformats = c1->nativeformats;
3121 if (config->timelimit) {
3122 nexteventts = ast_tvadd(config->start_time, ast_samp2tv(config->timelimit, 1000));
3123 if (caller_warning || callee_warning)
3124 nexteventts = ast_tvsub(nexteventts, ast_samp2tv(config->play_warning, 1000));
3127 for (/* ever */;;) {
3129 if (config->timelimit) {
3132 to = ast_tvdiff_ms(nexteventts, now);
3135 time_left_ms = config->timelimit - ast_tvdiff_ms(now, config->start_time);
3136 if (time_left_ms < to)
3139 if (time_left_ms <= 0) {
3140 if (caller_warning && config->end_sound)
3141 bridge_playfile(c0, c1, config->end_sound, 0);
3142 if (callee_warning && config->end_sound)
3143 bridge_playfile(c1, c0, config->end_sound, 0);