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)
270 chan->whentohangup = myt + offset;
272 chan->whentohangup = 0;
276 /*--- ast_channel_cmpwhentohangup: Compare a offset with when to hangup channel */
277 int ast_channel_cmpwhentohangup(struct ast_channel *chan, time_t offset)
281 if (chan->whentohangup == 0) {
290 whentohangup = offset + time (NULL);
291 if (chan->whentohangup < whentohangup)
293 else if (chan->whentohangup == whentohangup)
301 /*--- ast_channel_register: Register a new telephony channel in Asterisk */
302 int ast_channel_register(const struct ast_channel_tech *tech)
304 struct chanlist *chan;
306 ast_mutex_lock(&chlock);
310 if (!strcasecmp(tech->type, chan->tech->type)) {
311 ast_log(LOG_WARNING, "Already have a handler for type '%s'\n", tech->type);
312 ast_mutex_unlock(&chlock);
318 chan = malloc(sizeof(*chan));
320 ast_log(LOG_WARNING, "Out of memory\n");
321 ast_mutex_unlock(&chlock);
325 chan->next = backends;
329 ast_log(LOG_DEBUG, "Registered handler for '%s' (%s)\n", chan->tech->type, chan->tech->description);
331 if (option_verbose > 1)
332 ast_verbose(VERBOSE_PREFIX_2 "Registered channel type '%s' (%s)\n", chan->tech->type,
333 chan->tech->description);
335 ast_mutex_unlock(&chlock);
339 void ast_channel_unregister(const struct ast_channel_tech *tech)
341 struct chanlist *chan, *last=NULL;
344 ast_log(LOG_DEBUG, "Unregistering channel type '%s'\n", tech->type);
346 ast_mutex_lock(&chlock);
350 if (chan->tech == tech) {
352 last->next = chan->next;
354 backends = backends->next;
356 ast_mutex_unlock(&chlock);
358 if (option_verbose > 1)
359 ast_verbose( VERBOSE_PREFIX_2 "Unregistered channel type '%s'\n", tech->type);
367 ast_mutex_unlock(&chlock);
370 const struct ast_channel_tech *ast_get_channel_tech(const char *name)
372 struct chanlist *chanls;
374 if (ast_mutex_lock(&chlock)) {
375 ast_log(LOG_WARNING, "Unable to lock channel tech list\n");
379 for (chanls = backends; chanls; chanls = chanls->next) {
380 if (strcasecmp(name, chanls->tech->type))
383 ast_mutex_unlock(&chlock);
387 ast_mutex_unlock(&chlock);
391 /*--- ast_cause2str: Gives the string form of a given hangup cause */
392 const char *ast_cause2str(int cause)
396 for (x=0; x < sizeof(causes) / sizeof(causes[0]); x++)
397 if (causes[x].cause == cause)
398 return causes[x].desc;
403 /*--- ast_state2str: Gives the string form of a given channel state */
404 char *ast_state2str(int state)
406 /* XXX Not reentrant XXX */
407 static char localtmp[256];
411 case AST_STATE_RESERVED:
413 case AST_STATE_OFFHOOK:
415 case AST_STATE_DIALING:
419 case AST_STATE_RINGING:
426 snprintf(localtmp, sizeof(localtmp), "Unknown (%d)\n", state);
431 /*--- ast_transfercapability2str: Gives the string form of a given transfer capability */
432 char *ast_transfercapability2str(int transfercapability)
434 switch(transfercapability) {
435 case AST_TRANS_CAP_SPEECH:
437 case AST_TRANS_CAP_DIGITAL:
439 case AST_TRANS_CAP_RESTRICTED_DIGITAL:
440 return "RESTRICTED_DIGITAL";
441 case AST_TRANS_CAP_3_1K_AUDIO:
443 case AST_TRANS_CAP_DIGITAL_W_TONES:
444 return "DIGITAL_W_TONES";
445 case AST_TRANS_CAP_VIDEO:
452 /*--- ast_best_codec: Pick the best codec */
453 int ast_best_codec(int fmts)
455 /* This just our opinion, expressed in code. We are asked to choose
456 the best codec to use, given no information */
460 /* Okay, ulaw is used by all telephony equipment, so start with it */
462 /* Unless of course, you're a silly European, so then prefer ALAW */
464 /* Okay, well, signed linear is easy to translate into other stuff */
466 /* G.726 is standard ADPCM */
468 /* ADPCM has great sound quality and is still pretty easy to translate */
470 /* Okay, we're down to vocoders now, so pick GSM because it's small and easier to
471 translate and sounds pretty good */
473 /* iLBC is not too bad */
475 /* Speex is free, but computationally more expensive than GSM */
477 /* Ick, LPC10 sounds terrible, but at least we have code for it, if you're tacky enough
480 /* G.729a is faster than 723 and slightly less expensive */
482 /* Down to G.723.1 which is proprietary but at least designed for voice */
487 /* Find the first prefered codec in the format given */
488 for (x=0; x < (sizeof(prefs) / sizeof(prefs[0]) ); x++)
491 ast_log(LOG_WARNING, "Don't know any of 0x%x formats\n", fmts);
495 static const struct ast_channel_tech null_tech = {
497 .description = "Null channel (should not see this)",
500 /*--- ast_channel_alloc: Create a new channel structure */
501 struct ast_channel *ast_channel_alloc(int needqueue)
503 struct ast_channel *tmp;
506 struct varshead *headp;
509 /* If shutting down, don't allocate any new channels */
511 ast_log(LOG_WARNING, "Channel allocation failed: Refusing due to active shutdown\n");
515 tmp = malloc(sizeof(struct ast_channel));
517 ast_log(LOG_WARNING, "Channel allocation failed: Out of memory\n");
521 memset(tmp, 0, sizeof(struct ast_channel));
522 tmp->sched = sched_context_create();
524 ast_log(LOG_WARNING, "Channel allocation failed: Unable to create schedule context\n");
529 for (x=0; x<AST_MAX_FDS - 1; x++)
532 #ifdef ZAPTEL_OPTIMIZATIONS
533 tmp->timingfd = open("/dev/zap/timer", O_RDWR);
534 if (tmp->timingfd > -1) {
535 /* Check if timing interface supports new
538 if (!ioctl(tmp->timingfd, ZT_TIMERPONG, &flags))
546 if (pipe(tmp->alertpipe)) {
547 ast_log(LOG_WARNING, "Channel allocation failed: Can't create alert pipe!\n");
551 flags = fcntl(tmp->alertpipe[0], F_GETFL);
552 fcntl(tmp->alertpipe[0], F_SETFL, flags | O_NONBLOCK);
553 flags = fcntl(tmp->alertpipe[1], F_GETFL);
554 fcntl(tmp->alertpipe[1], F_SETFL, flags | O_NONBLOCK);
557 /* Make sure we've got it done right if they don't */
558 tmp->alertpipe[0] = tmp->alertpipe[1] = -1;
560 /* Always watch the alertpipe */
561 tmp->fds[AST_MAX_FDS-1] = tmp->alertpipe[0];
562 /* And timing pipe */
563 tmp->fds[AST_MAX_FDS-2] = tmp->timingfd;
564 strcpy(tmp->name, "**Unkown**");
566 tmp->_state = AST_STATE_DOWN;
570 tmp->fin = global_fin;
571 tmp->fout = global_fout;
572 snprintf(tmp->uniqueid, sizeof(tmp->uniqueid), "%li.%d", (long) time(NULL), uniqueint++);
573 headp = &tmp->varshead;
574 ast_mutex_init(&tmp->lock);
575 AST_LIST_HEAD_INIT(headp);
576 strcpy(tmp->context, "default");
577 ast_copy_string(tmp->language, defaultlanguage, sizeof(tmp->language));
578 strcpy(tmp->exten, "s");
580 tmp->amaflags = ast_default_amaflags;
581 ast_copy_string(tmp->accountcode, ast_default_accountcode, sizeof(tmp->accountcode));
583 tmp->tech = &null_tech;
585 ast_mutex_lock(&chlock);
586 tmp->next = channels;
589 ast_mutex_unlock(&chlock);
593 /*--- ast_queue_frame: Queue an outgoing media frame */
594 int ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin)
597 struct ast_frame *prev, *cur;
601 /* Build us a copy and free the original one */
604 ast_log(LOG_WARNING, "Unable to duplicate frame\n");
607 ast_mutex_lock(&chan->lock);
611 if ((cur->frametype == AST_FRAME_CONTROL) && (cur->subclass == AST_CONTROL_HANGUP)) {
612 /* Don't bother actually queueing anything after a hangup */
614 ast_mutex_unlock(&chan->lock);
621 /* Allow up to 96 voice frames outstanding, and up to 128 total frames */
622 if (((fin->frametype == AST_FRAME_VOICE) && (qlen > 96)) || (qlen > 128)) {
623 if (fin->frametype != AST_FRAME_VOICE) {
624 ast_log(LOG_WARNING, "Exceptionally long queue length queuing to %s\n", chan->name);
627 ast_log(LOG_DEBUG, "Dropping voice to exceptionally long queue on %s\n", chan->name);
629 ast_mutex_unlock(&chan->lock);
637 if (chan->alertpipe[1] > -1) {
638 if (write(chan->alertpipe[1], &blah, sizeof(blah)) != sizeof(blah))
639 ast_log(LOG_WARNING, "Unable to write to alert pipe on %s, frametype/subclass %d/%d (qlen = %d): %s!\n",
640 chan->name, f->frametype, f->subclass, qlen, strerror(errno));
641 #ifdef ZAPTEL_OPTIMIZATIONS
642 } else if (chan->timingfd > -1) {
643 ioctl(chan->timingfd, ZT_TIMERPING, &blah);
645 } else if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
646 pthread_kill(chan->blocker, SIGURG);
648 ast_mutex_unlock(&chan->lock);
652 /*--- ast_queue_hangup: Queue a hangup frame for channel */
653 int ast_queue_hangup(struct ast_channel *chan)
655 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_HANGUP };
656 chan->_softhangup |= AST_SOFTHANGUP_DEV;
657 return ast_queue_frame(chan, &f);
660 /*--- ast_queue_control: Queue a control frame */
661 int ast_queue_control(struct ast_channel *chan, int control)
663 struct ast_frame f = { AST_FRAME_CONTROL, };
664 f.subclass = control;
665 return ast_queue_frame(chan, &f);
668 /*--- ast_channel_defer_dtmf: Set defer DTMF flag on channel */
669 int ast_channel_defer_dtmf(struct ast_channel *chan)
674 pre = ast_test_flag(chan, AST_FLAG_DEFER_DTMF);
675 ast_set_flag(chan, AST_FLAG_DEFER_DTMF);
680 /*--- ast_channel_undefer_dtmf: Unset defer DTMF flag on channel */
681 void ast_channel_undefer_dtmf(struct ast_channel *chan)
684 ast_clear_flag(chan, AST_FLAG_DEFER_DTMF);
688 * Helper function to find channels. It supports these modes:
690 * prev != NULL : get channel next in list after prev
691 * name != NULL : get channel with matching name
692 * name != NULL && namelen != 0 : get channel whose name starts with prefix
693 * exten != NULL : get channel whose exten or macroexten matches
694 * context != NULL && exten != NULL : get channel whose context or macrocontext
696 * It returns with the channel's lock held. If getting the individual lock fails,
697 * unlock and retry quickly up to 10 times, then give up.
699 * XXX Note that this code has cost O(N) because of the need to verify
700 * that the object is still on the global list.
702 * XXX also note that accessing fields (e.g. c->name in ast_log())
703 * can only be done with the lock held or someone could delete the
704 * object while we work on it. This causes some ugliness in the code.
705 * Note that removing the first ast_log() may be harmful, as it would
706 * shorten the retry period and possibly cause failures.
707 * We should definitely go for a better scheme that is deadlock-free.
709 static struct ast_channel *channel_find_locked(const struct ast_channel *prev,
710 const char *name, const int namelen,
711 const char *context, const char *exten)
713 const char *msg = prev ? "deadlock" : "initial deadlock";
715 struct ast_channel *c;
717 for (retries = 0; retries < 10; retries++) {
718 ast_mutex_lock(&chlock);
719 for (c = channels; c; c = c->next) {
721 /* want head of list */
725 /* want match by full name */
727 if (!strcasecmp(c->name, name))
732 /* want match by name prefix */
733 if (!strncasecmp(c->name, name, namelen))
736 /* want match by context and exten */
737 if (context && (strcasecmp(c->context, context) &&
738 strcasecmp(c->macrocontext, context)))
741 if (strcasecmp(c->exten, exten) &&
742 strcasecmp(c->macroexten, exten))
747 } else if (c == prev) { /* found, return c->next */
752 /* exit if chan not found or mutex acquired successfully */
753 done = (c == NULL) || (ast_mutex_trylock(&c->lock) == 0);
754 /* this is slightly unsafe, as we _should_ hold the lock to access c->name */
756 ast_log(LOG_DEBUG, "Avoiding %s for '%s'\n", msg, c->name);
757 ast_mutex_unlock(&chlock);
763 * c is surely not null, but we don't have the lock so cannot
766 ast_log(LOG_WARNING, "Avoided %s for '%p', %d retries!\n",
772 /*--- ast_channel_walk_locked: Browse channels in use */
773 struct ast_channel *ast_channel_walk_locked(const struct ast_channel *prev)
775 return channel_find_locked(prev, NULL, 0, NULL, NULL);
778 /*--- ast_get_channel_by_name_locked: Get channel by name and lock it */
779 struct ast_channel *ast_get_channel_by_name_locked(const char *name)
781 return channel_find_locked(NULL, name, 0, NULL, NULL);
784 /*--- ast_get_channel_by_name_prefix_locked: Get channel by name prefix and lock it */
785 struct ast_channel *ast_get_channel_by_name_prefix_locked(const char *name, const int namelen)
787 return channel_find_locked(NULL, name, namelen, NULL, NULL);
790 /*--- ast_get_channel_by_exten_locked: Get channel by exten (and optionally context) and lock it */
791 struct ast_channel *ast_get_channel_by_exten_locked(const char *exten, const char *context)
793 return channel_find_locked(NULL, NULL, 0, context, exten);
796 /*--- ast_safe_sleep_conditional: Wait, look for hangups and condition arg */
797 int ast_safe_sleep_conditional( struct ast_channel *chan, int ms,
798 int (*cond)(void*), void *data )
803 if( cond && ((*cond)(data) == 0 ) )
805 ms = ast_waitfor(chan, ms);
818 /*--- ast_safe_sleep: Wait, look for hangups */
819 int ast_safe_sleep(struct ast_channel *chan, int ms)
823 ms = ast_waitfor(chan, ms);
836 static void free_cid(struct ast_callerid *cid)
847 free(cid->cid_rdnis);
850 /*--- ast_channel_free: Free a channel structure */
851 void ast_channel_free(struct ast_channel *chan)
853 struct ast_channel *last=NULL, *cur;
855 struct ast_var_t *vardata;
856 struct ast_frame *f, *fp;
857 struct varshead *headp;
858 char name[AST_CHANNEL_NAME];
860 headp=&chan->varshead;
862 ast_mutex_lock(&chlock);
867 last->next = cur->next;
869 channels = cur->next;
876 ast_log(LOG_WARNING, "Unable to find channel in list\n");
878 /* Lock and unlock the channel just to be sure nobody
879 has it locked still */
880 ast_mutex_lock(&cur->lock);
881 ast_mutex_unlock(&cur->lock);
883 if (chan->tech_pvt) {
884 ast_log(LOG_WARNING, "Channel '%s' may not have been hung up properly\n", chan->name);
885 free(chan->tech_pvt);
888 ast_copy_string(name, chan->name, sizeof(name));
890 /* Stop monitoring */
892 chan->monitor->stop( chan, 0 );
895 /* If there is native format music-on-hold state, free it */
896 if(chan->music_state)
897 ast_moh_cleanup(chan);
899 /* Free translatosr */
901 ast_translator_free_path(chan->readtrans);
902 if (chan->writetrans)
903 ast_translator_free_path(chan->writetrans);
905 ast_log(LOG_WARNING, "PBX may not have been terminated properly on '%s'\n", chan->name);
906 free_cid(&chan->cid);
907 ast_mutex_destroy(&chan->lock);
908 /* Close pipes if appropriate */
909 if ((fd = chan->alertpipe[0]) > -1)
911 if ((fd = chan->alertpipe[1]) > -1)
913 if ((fd = chan->timingfd) > -1)
923 /* loop over the variables list, freeing all data and deleting list items */
924 /* no need to lock the list, as the channel is already locked */
926 while (!AST_LIST_EMPTY(headp)) { /* List Deletion. */
927 vardata = AST_LIST_REMOVE_HEAD(headp, entries);
928 ast_var_delete(vardata);
932 ast_mutex_unlock(&chlock);
934 ast_device_state_changed(name);
937 static void ast_spy_detach(struct ast_channel *chan)
939 struct ast_channel_spy *chanspy;
943 for (chanspy = chan->spiers; chanspy; chanspy = chanspy->next) {
944 if (chanspy->status == CHANSPY_RUNNING) {
945 chanspy->status = CHANSPY_DONE;
949 /* signal all the spys to get lost and allow them time to unhook themselves
950 god help us if they don't......
952 while (chan->spiers && to >= 0) {
953 ast_safe_sleep(chan, sleepms);
960 /*--- ast_softhangup_nolock: Softly hangup a channel, don't lock */
961 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
964 struct ast_frame f = { AST_FRAME_NULL };
966 ast_log(LOG_DEBUG, "Soft-Hanging up channel '%s'\n", chan->name);
967 /* Inform channel driver that we need to be hung up, if it cares */
968 chan->_softhangup |= cause;
969 ast_queue_frame(chan, &f);
970 /* Interrupt any poll call or such */
971 if (ast_test_flag(chan, AST_FLAG_BLOCKING))
972 pthread_kill(chan->blocker, SIGURG);
976 /*--- ast_softhangup_nolock: Softly hangup a channel, lock */
977 int ast_softhangup(struct ast_channel *chan, int cause)
980 ast_mutex_lock(&chan->lock);
981 res = ast_softhangup_nolock(chan, cause);
982 ast_mutex_unlock(&chan->lock);
986 static void ast_queue_spy_frame(struct ast_channel_spy *spy, struct ast_frame *f, int pos)
988 struct ast_frame *tmpf = NULL;
991 ast_mutex_lock(&spy->lock);
992 for (tmpf=spy->queue[pos]; tmpf && tmpf->next; tmpf=tmpf->next) {
996 struct ast_frame *freef, *headf;
998 ast_log(LOG_ERROR, "Too many frames queued at once, flushing cache.\n");
999 headf = spy->queue[pos];
1000 /* deref the queue right away so it looks empty */
1001 spy->queue[pos] = NULL;
1003 /* free the wasted frames */
1009 ast_mutex_unlock(&spy->lock);
1014 tmpf->next = ast_frdup(f);
1016 spy->queue[pos] = ast_frdup(f);
1019 ast_mutex_unlock(&spy->lock);
1022 static void free_translation(struct ast_channel *clone)
1024 if (clone->writetrans)
1025 ast_translator_free_path(clone->writetrans);
1026 if (clone->readtrans)
1027 ast_translator_free_path(clone->readtrans);
1028 clone->writetrans = NULL;
1029 clone->readtrans = NULL;
1030 clone->rawwriteformat = clone->nativeformats;
1031 clone->rawreadformat = clone->nativeformats;
1034 /*--- ast_hangup: Hangup a channel */
1035 int ast_hangup(struct ast_channel *chan)
1039 /* Don't actually hang up a channel that will masquerade as someone else, or
1040 if someone is going to masquerade as us */
1041 ast_mutex_lock(&chan->lock);
1043 ast_spy_detach(chan); /* get rid of spies */
1046 if (ast_do_masquerade(chan))
1047 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1051 ast_log(LOG_WARNING, "%s getting hung up, but someone is trying to masq into us?!?\n", chan->name);
1052 ast_mutex_unlock(&chan->lock);
1055 /* If this channel is one which will be masqueraded into something,
1056 mark it as a zombie already, so we know to free it later */
1058 ast_set_flag(chan, AST_FLAG_ZOMBIE);
1059 ast_mutex_unlock(&chan->lock);
1062 free_translation(chan);
1063 if (chan->stream) /* Close audio stream */
1064 ast_closestream(chan->stream);
1065 if (chan->vstream) /* Close video stream */
1066 ast_closestream(chan->vstream);
1068 sched_context_destroy(chan->sched);
1070 if (chan->generatordata) /* Clear any tone stuff remaining */
1071 chan->generator->release(chan, chan->generatordata);
1072 chan->generatordata = NULL;
1073 chan->generator = NULL;
1074 if (chan->cdr) { /* End the CDR if it hasn't already */
1075 ast_cdr_end(chan->cdr);
1076 ast_cdr_detach(chan->cdr); /* Post and Free the CDR */
1079 if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
1080 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
1081 "is blocked by thread %ld in procedure %s! Expect a failure\n",
1082 (long)pthread_self(), chan->name, (long)chan->blocker, chan->blockproc);
1085 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE)) {
1087 ast_log(LOG_DEBUG, "Hanging up channel '%s'\n", chan->name);
1088 if (chan->tech->hangup)
1089 res = chan->tech->hangup(chan);
1092 ast_log(LOG_DEBUG, "Hanging up zombie '%s'\n", chan->name);
1095 ast_mutex_unlock(&chan->lock);
1096 manager_event(EVENT_FLAG_CALL, "Hangup",
1100 "Cause-txt: %s\r\n",
1104 ast_cause2str(chan->hangupcause)
1106 ast_channel_free(chan);
1110 int ast_answer(struct ast_channel *chan)
1113 ast_mutex_lock(&chan->lock);
1114 /* Stop if we're a zombie or need a soft hangup */
1115 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
1116 ast_mutex_unlock(&chan->lock);
1119 switch(chan->_state) {
1120 case AST_STATE_RINGING:
1121 case AST_STATE_RING:
1122 if (chan->tech->answer)
1123 res = chan->tech->answer(chan);
1124 ast_setstate(chan, AST_STATE_UP);
1126 ast_cdr_answer(chan->cdr);
1127 ast_mutex_unlock(&chan->lock);
1132 ast_cdr_answer(chan->cdr);
1135 ast_mutex_unlock(&chan->lock);
1141 void ast_deactivate_generator(struct ast_channel *chan)
1143 ast_mutex_lock(&chan->lock);
1144 if (chan->generatordata) {
1145 if (chan->generator && chan->generator->release)
1146 chan->generator->release(chan, chan->generatordata);
1147 chan->generatordata = NULL;
1148 chan->generator = NULL;
1149 ast_clear_flag(chan, AST_FLAG_WRITE_INT);
1150 ast_settimeout(chan, 0, NULL, NULL);
1152 ast_mutex_unlock(&chan->lock);
1155 static int generator_force(void *data)
1157 /* Called if generator doesn't have data */
1160 int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples);
1161 struct ast_channel *chan = data;
1162 tmp = chan->generatordata;
1163 chan->generatordata = NULL;
1164 generate = chan->generator->generate;
1165 res = generate(chan, tmp, 0, 160);
1166 chan->generatordata = tmp;
1168 ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
1169 ast_deactivate_generator(chan);
1174 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
1177 ast_mutex_lock(&chan->lock);
1178 if (chan->generatordata) {
1179 if (chan->generator && chan->generator->release)
1180 chan->generator->release(chan, chan->generatordata);
1181 chan->generatordata = NULL;
1184 if ((chan->generatordata = gen->alloc(chan, params))) {
1185 ast_settimeout(chan, 160, generator_force, chan);
1186 chan->generator = gen;
1190 ast_mutex_unlock(&chan->lock);
1194 /*--- ast_waitfor_n_fd: Wait for x amount of time on a file descriptor to have input. */
1195 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
1197 struct timeval start = { 0 , 0 };
1202 struct pollfd *pfds;
1204 pfds = alloca(sizeof(struct pollfd) * n);
1206 ast_log(LOG_ERROR, "Out of memory\n");
1210 start = ast_tvnow();
1212 for (x=0; x < n; x++) {
1214 pfds[y].fd = fds[x];
1215 pfds[y].events = POLLIN | POLLPRI;
1219 res = poll(pfds, y, *ms);
1221 /* Simulate a timeout if we were interrupted */
1229 for (x=0; x < n; x++) {
1231 if ((res = ast_fdisset(pfds, fds[x], y, &spoint))) {
1243 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
1250 /*--- ast_waitfor_nanfds: Wait for x amount of time on a file descriptor to have input. */
1251 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
1252 int *exception, int *outfd, int *ms)
1254 struct timeval start = { 0 , 0 };
1255 struct pollfd *pfds;
1261 long whentohangup = 0, havewhen = 0, diff;
1262 struct ast_channel *winner = NULL;
1264 pfds = alloca(sizeof(struct pollfd) * (n * AST_MAX_FDS + nfds));
1266 ast_log(LOG_ERROR, "Out of memory\n");
1276 /* Perform any pending masquerades */
1277 for (x=0; x < n; x++) {
1278 ast_mutex_lock(&c[x]->lock);
1279 if (c[x]->whentohangup) {
1282 diff = c[x]->whentohangup - now;
1283 if (!havewhen || (diff < whentohangup)) {
1285 whentohangup = diff;
1289 if (ast_do_masquerade(c[x])) {
1290 ast_log(LOG_WARNING, "Masquerade failed\n");
1292 ast_mutex_unlock(&c[x]->lock);
1296 ast_mutex_unlock(&c[x]->lock);
1302 if ((*ms < 0) || (whentohangup * 1000 < *ms)) {
1303 rms = whentohangup * 1000;
1307 for (x=0; x < n; x++) {
1308 for (y=0; y< AST_MAX_FDS; y++) {
1309 if (c[x]->fds[y] > -1) {
1310 pfds[max].fd = c[x]->fds[y];
1311 pfds[max].events = POLLIN | POLLPRI;
1312 pfds[max].revents = 0;
1316 CHECK_BLOCKING(c[x]);
1318 for (x=0; x < nfds; x++) {
1320 pfds[max].fd = fds[x];
1321 pfds[max].events = POLLIN | POLLPRI;
1322 pfds[max].revents = 0;
1327 start = ast_tvnow();
1328 res = poll(pfds, max, rms);
1330 for (x=0; x < n; x++)
1331 ast_clear_flag(c[x], AST_FLAG_BLOCKING);
1332 /* Simulate a timeout if we were interrupted */
1336 /* Just an interrupt */
1343 /* If no fds signalled, then timeout. So set ms = 0
1344 since we may not have an exact timeout.
1353 for (x=0; x < n; x++) {
1354 ast_clear_flag(c[x], AST_FLAG_BLOCKING);
1355 if (havewhen && c[x]->whentohangup && (now > c[x]->whentohangup)) {
1356 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1360 for (y=0; y < AST_MAX_FDS; y++) {
1361 if (c[x]->fds[y] > -1) {
1362 if ((res = ast_fdisset(pfds, c[x]->fds[y], max, &spoint))) {
1364 ast_set_flag(c[x], AST_FLAG_EXCEPTION);
1366 ast_clear_flag(c[x], AST_FLAG_EXCEPTION);
1373 for (x=0; x < nfds; x++) {
1375 if ((res = ast_fdisset(pfds, fds[x], max, &spoint))) {
1389 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
1396 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
1398 return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
1401 int ast_waitfor(struct ast_channel *c, int ms)
1403 struct ast_channel *chan;
1406 chan = ast_waitfor_n(&c, 1, &ms);
1416 int ast_waitfordigit(struct ast_channel *c, int ms)
1418 /* XXX Should I be merged with waitfordigit_full XXX */
1419 struct ast_frame *f;
1422 /* Stop if we're a zombie or need a soft hangup */
1423 if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
1426 /* Wait for a digit, no more than ms milliseconds total. */
1427 while(ms && !result) {
1428 ms = ast_waitfor(c, ms);
1429 if (ms < 0) /* Error */
1432 /* Read something */
1435 if (f->frametype == AST_FRAME_DTMF)
1436 result = f->subclass;
1445 int ast_settimeout(struct ast_channel *c, int samples, int (*func)(void *data), void *data)
1448 #ifdef ZAPTEL_OPTIMIZATIONS
1449 if (c->timingfd > -1) {
1454 ast_log(LOG_DEBUG, "Scheduling timer at %d sample intervals\n", samples);
1455 res = ioctl(c->timingfd, ZT_TIMERCONFIG, &samples);
1456 c->timingfunc = func;
1457 c->timingdata = data;
1463 int ast_waitfordigit_full(struct ast_channel *c, int ms, int audiofd, int cmdfd)
1465 struct ast_frame *f;
1466 struct ast_channel *rchan;
1470 /* Stop if we're a zombie or need a soft hangup */
1471 if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
1473 /* Wait for a digit, no more than ms milliseconds total. */
1476 rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
1477 if ((!rchan) && (outfd < 0) && (ms)) {
1478 if (errno == 0 || errno == EINTR)
1480 ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
1482 } else if (outfd > -1) {
1483 /* The FD we were watching has something waiting */
1491 switch(f->frametype) {
1492 case AST_FRAME_DTMF:
1496 case AST_FRAME_CONTROL:
1497 switch(f->subclass) {
1498 case AST_CONTROL_HANGUP:
1501 case AST_CONTROL_RINGING:
1502 case AST_CONTROL_ANSWER:
1506 ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", f->subclass);
1508 case AST_FRAME_VOICE:
1509 /* Write audio if appropriate */
1511 write(audiofd, f->data, f->datalen);
1517 return 0; /* Time is up */
1520 struct ast_frame *ast_read(struct ast_channel *chan)
1522 struct ast_frame *f = NULL;
1525 #ifdef ZAPTEL_OPTIMIZATIONS
1526 int (*func)(void *);
1530 static struct ast_frame null_frame = {
1534 ast_mutex_lock(&chan->lock);
1536 if (ast_do_masquerade(chan)) {
1537 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1541 ast_mutex_unlock(&chan->lock);
1545 /* Stop if we're a zombie or need a soft hangup */
1546 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
1547 if (chan->generator)
1548 ast_deactivate_generator(chan);
1549 ast_mutex_unlock(&chan->lock);
1552 prestate = chan->_state;
1554 if (!ast_test_flag(chan, AST_FLAG_DEFER_DTMF) && !ast_strlen_zero(chan->dtmfq)) {
1555 /* We have DTMF that has been deferred. Return it now */
1556 chan->dtmff.frametype = AST_FRAME_DTMF;
1557 chan->dtmff.subclass = chan->dtmfq[0];
1558 /* Drop first digit */
1559 memmove(chan->dtmfq, chan->dtmfq + 1, sizeof(chan->dtmfq) - 1);
1560 ast_mutex_unlock(&chan->lock);
1561 return &chan->dtmff;
1564 /* Read and ignore anything on the alertpipe, but read only
1565 one sizeof(blah) per frame that we send from it */
1566 if (chan->alertpipe[0] > -1) {
1567 read(chan->alertpipe[0], &blah, sizeof(blah));
1569 #ifdef ZAPTEL_OPTIMIZATIONS
1570 if ((chan->timingfd > -1) && (chan->fdno == AST_MAX_FDS - 2) && ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
1571 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
1573 /* IF we can't get event, assume it's an expired as-per the old interface */
1574 res = ioctl(chan->timingfd, ZT_GETEVENT, &blah);
1576 blah = ZT_EVENT_TIMER_EXPIRED;
1578 if (blah == ZT_EVENT_TIMER_PING) {
1580 ast_log(LOG_NOTICE, "Oooh, there's a PING!\n");
1582 if (!chan->readq || !chan->readq->next) {
1583 /* Acknowledge PONG unless we need it again */
1585 ast_log(LOG_NOTICE, "Sending a PONG!\n");
1587 if (ioctl(chan->timingfd, ZT_TIMERPONG, &blah)) {
1588 ast_log(LOG_WARNING, "Failed to pong timer on '%s': %s\n", chan->name, strerror(errno));
1591 } else if (blah == ZT_EVENT_TIMER_EXPIRED) {
1592 ioctl(chan->timingfd, ZT_TIMERACK, &blah);
1593 func = chan->timingfunc;
1594 data = chan->timingdata;
1595 ast_mutex_unlock(&chan->lock);
1598 ast_log(LOG_DEBUG, "Calling private function\n");
1603 ast_mutex_lock(&chan->lock);
1604 ioctl(chan->timingfd, ZT_TIMERCONFIG, &blah);
1605 chan->timingdata = NULL;
1606 ast_mutex_unlock(&chan->lock);
1611 ast_log(LOG_NOTICE, "No/unknown event '%d' on timer for '%s'?\n", blah, chan->name);
1614 /* Check for pending read queue */
1617 chan->readq = f->next;
1618 /* Interpret hangup and return NULL */
1619 if ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_HANGUP)) {
1624 chan->blocker = pthread_self();
1625 if (ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
1626 if (chan->tech->exception)
1627 f = chan->tech->exception(chan);
1629 ast_log(LOG_WARNING, "Exception flag set on '%s', but no exception handler\n", chan->name);
1632 /* Clear the exception flag */
1633 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
1635 if (chan->tech->read)
1636 f = chan->tech->read(chan);
1638 ast_log(LOG_WARNING, "No read routine on channel %s\n", chan->name);
1643 if (f && (f->frametype == AST_FRAME_VOICE)) {
1644 if (!(f->subclass & chan->nativeformats)) {
1645 /* This frame can't be from the current native formats -- drop it on the
1647 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));
1652 struct ast_channel_spy *spying;
1653 for (spying = chan->spiers; spying; spying=spying->next) {
1654 ast_queue_spy_frame(spying, f, 0);
1657 if (chan->monitor && chan->monitor->read_stream ) {
1658 #ifndef MONITOR_CONSTANT_DELAY
1659 int jump = chan->outsmpl - chan->insmpl - 2 * f->samples;
1661 if (ast_seekstream(chan->monitor->read_stream, jump + f->samples, SEEK_FORCECUR) == -1)
1662 ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
1663 chan->insmpl += jump + 2 * f->samples;
1665 chan->insmpl+= f->samples;
1667 int jump = chan->outsmpl - chan->insmpl;
1668 if (jump - MONITOR_DELAY >= 0) {
1669 if (ast_seekstream(chan->monitor->read_stream, jump - f->samples, SEEK_FORCECUR) == -1)
1670 ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
1671 chan->insmpl += jump;
1673 chan->insmpl += f->samples;
1675 if (ast_writestream(chan->monitor->read_stream, f) < 0)
1676 ast_log(LOG_WARNING, "Failed to write data to channel monitor read stream\n");
1678 if (chan->readtrans) {
1679 f = ast_translate(chan->readtrans, f, 1);
1686 /* Make sure we always return NULL in the future */
1688 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1689 if (chan->generator)
1690 ast_deactivate_generator(chan);
1691 /* End the CDR if appropriate */
1693 ast_cdr_end(chan->cdr);
1694 } else if (ast_test_flag(chan, AST_FLAG_DEFER_DTMF) && f->frametype == AST_FRAME_DTMF) {
1695 if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2)
1696 chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
1698 ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
1700 } else if ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_ANSWER)) {
1701 if (prestate == AST_STATE_UP) {
1702 ast_log(LOG_DEBUG, "Dropping duplicate answer!\n");
1705 /* Answer the CDR */
1706 ast_setstate(chan, AST_STATE_UP);
1707 ast_cdr_answer(chan->cdr);
1710 /* Run any generator sitting on the line */
1711 if (f && (f->frametype == AST_FRAME_VOICE) && chan->generatordata) {
1712 /* Mask generator data temporarily and apply. If there is a timing function, it
1713 will be calling the generator instead */
1716 int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples);
1718 if (chan->timingfunc) {
1719 ast_log(LOG_DEBUG, "Generator got voice, switching to phase locked mode\n");
1720 ast_settimeout(chan, 0, NULL, NULL);
1722 tmp = chan->generatordata;
1723 chan->generatordata = NULL;
1724 generate = chan->generator->generate;
1725 res = generate(chan, tmp, f->datalen, f->samples);
1726 chan->generatordata = tmp;
1728 ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
1729 ast_deactivate_generator(chan);
1731 } else if (f && (f->frametype == AST_FRAME_CNG)) {
1732 if (chan->generator && !chan->timingfunc && (chan->timingfd > -1)) {
1733 ast_log(LOG_DEBUG, "Generator got CNG, switching to zap timed mode\n");
1734 ast_settimeout(chan, 160, generator_force, chan);
1737 /* High bit prints debugging */
1738 if (chan->fin & 0x80000000)
1739 ast_frame_dump(chan->name, f, "<<");
1740 if ((chan->fin & 0x7fffffff) == 0x7fffffff)
1741 chan->fin &= 0x80000000;
1744 ast_mutex_unlock(&chan->lock);
1748 int ast_indicate(struct ast_channel *chan, int condition)
1752 /* Stop if we're a zombie or need a soft hangup */
1753 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
1755 ast_mutex_lock(&chan->lock);
1756 if (chan->tech->indicate)
1757 res = chan->tech->indicate(chan, condition);
1758 ast_mutex_unlock(&chan->lock);
1759 if (!chan->tech->indicate || res) {
1761 * Device does not support (that) indication, lets fake
1762 * it by doing our own tone generation. (PM2002)
1764 if (condition >= 0) {
1765 const struct tone_zone_sound *ts = NULL;
1766 switch (condition) {
1767 case AST_CONTROL_RINGING:
1768 ts = ast_get_indication_tone(chan->zone, "ring");
1770 case AST_CONTROL_BUSY:
1771 ts = ast_get_indication_tone(chan->zone, "busy");
1773 case AST_CONTROL_CONGESTION:
1774 ts = ast_get_indication_tone(chan->zone, "congestion");
1777 if (ts && ts->data[0]) {
1778 ast_log(LOG_DEBUG, "Driver for channel '%s' does not support indication %d, emulating it\n", chan->name, condition);
1779 ast_playtones_start(chan,0,ts->data, 1);
1781 } else if (condition == AST_CONTROL_PROGRESS) {
1782 /* ast_playtones_stop(chan); */
1783 } else if (condition == AST_CONTROL_PROCEEDING) {
1784 /* Do nothing, really */
1785 } else if (condition == AST_CONTROL_HOLD) {
1786 /* Do nothing.... */
1787 } else if (condition == AST_CONTROL_UNHOLD) {
1788 /* Do nothing.... */
1789 } else if (condition == AST_CONTROL_VIDUPDATE) {
1790 /* Do nothing.... */
1793 ast_log(LOG_WARNING, "Unable to handle indication %d for '%s'\n", condition, chan->name);
1797 else ast_playtones_stop(chan);
1802 int ast_recvchar(struct ast_channel *chan, int timeout)
1805 char *buf = ast_recvtext(chan, timeout);
1807 return -1; /* error or timeout */
1808 c = *(unsigned char *)buf;
1813 char *ast_recvtext(struct ast_channel *chan, int timeout)
1819 struct ast_frame *f;
1820 if (ast_check_hangup(chan))
1822 res = ast_waitfor(chan, timeout);
1823 if (res <= 0) /* timeout or error */
1825 timeout = res; /* update timeout */
1828 break; /* no frame */
1829 if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP)
1830 done = 1; /* force a break */
1831 else if (f->frametype == AST_FRAME_TEXT) { /* what we want */
1832 buf = strndup((char *) f->data, f->datalen); /* dup and break */
1840 int ast_sendtext(struct ast_channel *chan, char *text)
1843 /* Stop if we're a zombie or need a soft hangup */
1844 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
1846 CHECK_BLOCKING(chan);
1847 if (chan->tech->send_text)
1848 res = chan->tech->send_text(chan, text);
1849 ast_clear_flag(chan, AST_FLAG_BLOCKING);
1853 static int do_senddigit(struct ast_channel *chan, char digit)
1857 if (chan->tech->send_digit)
1858 res = chan->tech->send_digit(chan, digit);
1859 if (!chan->tech->send_digit || res) {
1861 * Device does not support DTMF tones, lets fake
1862 * it by doing our own generation. (PM2002)
1864 static const char* dtmf_tones[] = {
1865 "!941+1336/100,!0/100", /* 0 */
1866 "!697+1209/100,!0/100", /* 1 */
1867 "!697+1336/100,!0/100", /* 2 */
1868 "!697+1477/100,!0/100", /* 3 */
1869 "!770+1209/100,!0/100", /* 4 */
1870 "!770+1336/100,!0/100", /* 5 */
1871 "!770+1477/100,!0/100", /* 6 */
1872 "!852+1209/100,!0/100", /* 7 */
1873 "!852+1336/100,!0/100", /* 8 */
1874 "!852+1477/100,!0/100", /* 9 */
1875 "!697+1633/100,!0/100", /* A */
1876 "!770+1633/100,!0/100", /* B */
1877 "!852+1633/100,!0/100", /* C */
1878 "!941+1633/100,!0/100", /* D */
1879 "!941+1209/100,!0/100", /* * */
1880 "!941+1477/100,!0/100" }; /* # */
1881 if (digit >= '0' && digit <='9')
1882 ast_playtones_start(chan, 0, dtmf_tones[digit-'0'], 0);
1883 else if (digit >= 'A' && digit <= 'D')
1884 ast_playtones_start(chan, 0, dtmf_tones[digit-'A'+10], 0);
1885 else if (digit == '*')
1886 ast_playtones_start(chan, 0, dtmf_tones[14], 0);
1887 else if (digit == '#')
1888 ast_playtones_start(chan, 0, dtmf_tones[15], 0);
1891 ast_log(LOG_DEBUG, "Unable to generate DTMF tone '%c' for '%s'\n", digit, chan->name);
1897 int ast_senddigit(struct ast_channel *chan, char digit)
1899 return do_senddigit(chan, digit);
1902 int ast_prod(struct ast_channel *chan)
1904 struct ast_frame a = { AST_FRAME_VOICE };
1907 /* Send an empty audio frame to get things moving */
1908 if (chan->_state != AST_STATE_UP) {
1909 ast_log(LOG_DEBUG, "Prodding channel '%s'\n", chan->name);
1910 a.subclass = chan->rawwriteformat;
1911 a.data = nothing + AST_FRIENDLY_OFFSET;
1913 if (ast_write(chan, &a))
1914 ast_log(LOG_WARNING, "Prodding channel '%s' failed\n", chan->name);
1919 int ast_write_video(struct ast_channel *chan, struct ast_frame *fr)
1922 if (!chan->tech->write_video)
1924 res = ast_write(chan, fr);
1930 int ast_write(struct ast_channel *chan, struct ast_frame *fr)
1933 struct ast_frame *f = NULL;
1934 /* Stop if we're a zombie or need a soft hangup */
1935 ast_mutex_lock(&chan->lock);
1936 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
1937 ast_mutex_unlock(&chan->lock);
1940 /* Handle any pending masquerades */
1942 if (ast_do_masquerade(chan)) {
1943 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1944 ast_mutex_unlock(&chan->lock);
1949 ast_mutex_unlock(&chan->lock);
1952 if (chan->generatordata) {
1953 if (ast_test_flag(chan, AST_FLAG_WRITE_INT))
1954 ast_deactivate_generator(chan);
1956 ast_mutex_unlock(&chan->lock);
1960 /* High bit prints debugging */
1961 if (chan->fout & 0x80000000)
1962 ast_frame_dump(chan->name, fr, ">>");
1963 CHECK_BLOCKING(chan);
1964 switch(fr->frametype) {
1965 case AST_FRAME_CONTROL:
1966 /* XXX Interpret control frames XXX */
1967 ast_log(LOG_WARNING, "Don't know how to handle control frames yet\n");
1969 case AST_FRAME_DTMF:
1970 ast_clear_flag(chan, AST_FLAG_BLOCKING);
1971 ast_mutex_unlock(&chan->lock);
1972 res = do_senddigit(chan,fr->subclass);
1973 ast_mutex_lock(&chan->lock);
1974 CHECK_BLOCKING(chan);
1976 case AST_FRAME_TEXT:
1977 if (chan->tech->send_text)
1978 res = chan->tech->send_text(chan, (char *) fr->data);
1982 case AST_FRAME_HTML:
1983 if (chan->tech->send_html)
1984 res = chan->tech->send_html(chan, fr->subclass, (char *) fr->data, fr->datalen);
1988 case AST_FRAME_VIDEO:
1989 /* XXX Handle translation of video codecs one day XXX */
1990 if (chan->tech->write_video)
1991 res = chan->tech->write_video(chan, fr);
1996 if (chan->tech->write) {
1997 if (chan->writetrans)
1998 f = ast_translate(chan->writetrans, fr, 0);
2002 if (f->frametype == AST_FRAME_VOICE && chan->spiers) {
2003 struct ast_channel_spy *spying;
2004 for (spying = chan->spiers; spying; spying=spying->next) {
2005 ast_queue_spy_frame(spying, f, 1);
2009 if( chan->monitor && chan->monitor->write_stream &&
2010 f && ( f->frametype == AST_FRAME_VOICE ) ) {
2011 #ifndef MONITOR_CONSTANT_DELAY
2012 int jump = chan->insmpl - chan->outsmpl - 2 * f->samples;
2014 if (ast_seekstream(chan->monitor->write_stream, jump + f->samples, SEEK_FORCECUR) == -1)
2015 ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
2016 chan->outsmpl += jump + 2 * f->samples;
2018 chan->outsmpl += f->samples;
2020 int jump = chan->insmpl - chan->outsmpl;
2021 if (jump - MONITOR_DELAY >= 0) {
2022 if (ast_seekstream(chan->monitor->write_stream, jump - f->samples, SEEK_FORCECUR) == -1)
2023 ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
2024 chan->outsmpl += jump;
2026 chan->outsmpl += f->samples;
2028 if (ast_writestream(chan->monitor->write_stream, f) < 0)
2029 ast_log(LOG_WARNING, "Failed to write data to channel monitor write stream\n");
2032 res = chan->tech->write(chan, f);
2038 /* It's possible this is a translated frame */
2039 if (f && f->frametype == AST_FRAME_DTMF) {
2040 ast_log(LOG_DTMF, "%s : %c\n", chan->name, f->subclass);
2041 } else if (fr->frametype == AST_FRAME_DTMF) {
2042 ast_log(LOG_DTMF, "%s : %c\n", chan->name, fr->subclass);
2047 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2048 /* Consider a write failure to force a soft hangup */
2050 chan->_softhangup |= AST_SOFTHANGUP_DEV;
2052 if ((chan->fout & 0x7fffffff) == 0x7fffffff)
2053 chan->fout &= 0x80000000;
2057 ast_mutex_unlock(&chan->lock);
2061 static int set_format(struct ast_channel *chan, int fmt, int *rawformat, int *format,
2062 struct ast_trans_pvt **trans, const int direction)
2067 native = chan->nativeformats;
2068 /* Find a translation path from the native format to one of the desired formats */
2071 res = ast_translator_best_choice(&fmt, &native);
2074 res = ast_translator_best_choice(&native, &fmt);
2077 ast_log(LOG_WARNING, "Unable to find a codec translation path from %s to %s\n",
2078 ast_getformatname(native), ast_getformatname(fmt));
2082 /* Now we have a good choice for both. */
2083 ast_mutex_lock(&chan->lock);
2084 *rawformat = native;
2085 /* User perspective is fmt */
2087 /* Free any read translation we have right now */
2089 ast_translator_free_path(*trans);
2090 /* Build a translation path from the raw format to the desired format */
2093 *trans = ast_translator_build_path(*format, *rawformat);
2096 *trans = ast_translator_build_path(*rawformat, *format);
2097 ast_mutex_unlock(&chan->lock);
2099 ast_log(LOG_DEBUG, "Set channel %s to %s format %s\n", chan->name,
2100 direction ? "write" : "read", ast_getformatname(fmt));
2104 int ast_set_read_format(struct ast_channel *chan, int fmt)
2106 return set_format(chan, fmt, &chan->rawreadformat, &chan->readformat,
2107 &chan->readtrans, 0);
2110 int ast_set_write_format(struct ast_channel *chan, int fmt)
2112 return set_format(chan, fmt, &chan->rawwriteformat, &chan->writeformat,
2113 &chan->writetrans, 1);
2116 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)
2120 struct ast_channel *chan;
2121 struct ast_frame *f;
2124 chan = ast_request(type, format, data, &cause);
2127 ast_set_variables(chan, oh->vars);
2128 ast_set_callerid(chan, oh->cid_num, oh->cid_name, oh->cid_num);
2130 ast_set_callerid(chan, cid_num, cid_name, cid_num);
2132 if (!ast_call(chan, data, 0)) {
2133 while(timeout && (chan->_state != AST_STATE_UP)) {
2134 res = ast_waitfor(chan, timeout);
2136 /* Something not cool, or timed out */
2139 /* If done, break out */
2146 state = AST_CONTROL_HANGUP;
2150 if (f->frametype == AST_FRAME_CONTROL) {
2151 if (f->subclass == AST_CONTROL_RINGING)
2152 state = AST_CONTROL_RINGING;
2153 else if ((f->subclass == AST_CONTROL_BUSY) || (f->subclass == AST_CONTROL_CONGESTION)) {
2154 state = f->subclass;
2157 } else if (f->subclass == AST_CONTROL_ANSWER) {
2158 state = f->subclass;
2161 } else if (f->subclass == AST_CONTROL_PROGRESS) {
2163 } else if (f->subclass == -1) {
2164 /* Ignore -- just stopping indications */
2166 ast_log(LOG_NOTICE, "Don't know what to do with control frame %d\n", f->subclass);
2172 ast_log(LOG_NOTICE, "Unable to call channel %s/%s\n", type, (char *)data);
2174 ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
2176 case AST_CAUSE_BUSY:
2177 state = AST_CONTROL_BUSY;
2179 case AST_CAUSE_CONGESTION:
2180 state = AST_CONTROL_CONGESTION;
2187 if (oh->context && *oh->context)
2188 ast_copy_string(chan->context, oh->context, sizeof(chan->context));
2189 if (oh->exten && *oh->exten)
2190 ast_copy_string(chan->exten, oh->exten, sizeof(chan->exten));
2192 chan->priority = oh->priority;
2194 if (chan->_state == AST_STATE_UP)
2195 state = AST_CONTROL_ANSWER;
2199 if (chan && res <= 0) {
2201 chan->cdr = ast_cdr_alloc();
2203 ast_cdr_init(chan->cdr, chan);
2207 snprintf(tmp, 256, "%s/%s", type, (char *)data);
2208 ast_cdr_setapp(chan->cdr,"Dial",tmp);
2209 ast_cdr_update(chan);
2210 ast_cdr_start(chan->cdr);
2211 ast_cdr_end(chan->cdr);
2212 /* If the cause wasn't handled properly */
2213 if (ast_cdr_disposition(chan->cdr,chan->hangupcause))
2214 ast_cdr_failed(chan->cdr);
2216 ast_log(LOG_WARNING, "Unable to create Call Detail Record\n");
2223 struct ast_channel *ast_request_and_dial(const char *type, int format, void *data, int timeout, int *outstate, const char *cidnum, const char *cidname)
2225 return __ast_request_and_dial(type, format, data, timeout, outstate, cidnum, cidname, NULL);
2228 struct ast_channel *ast_request(const char *type, int format, void *data, int *cause)
2230 struct chanlist *chan;
2231 struct ast_channel *c;
2239 *cause = AST_CAUSE_NOTDEFINED;
2241 if (ast_mutex_lock(&chlock)) {
2242 ast_log(LOG_WARNING, "Unable to lock channel list\n");
2246 for (chan = backends; chan; chan = chan->next) {
2247 if (strcasecmp(type, chan->tech->type))
2250 capabilities = chan->tech->capabilities;
2252 res = ast_translator_best_choice(&fmt, &capabilities);
2254 ast_log(LOG_WARNING, "No translator path exists for channel type %s (native %d) to %d\n", type, chan->tech->capabilities, format);
2255 ast_mutex_unlock(&chlock);
2258 ast_mutex_unlock(&chlock);
2259 if (!chan->tech->requester)
2262 if (!(c = chan->tech->requester(type, capabilities, data, cause)))
2265 if (c->_state == AST_STATE_DOWN) {
2266 manager_event(EVENT_FLAG_CALL, "Newchannel",
2270 "CallerIDName: %s\r\n"
2272 c->name, ast_state2str(c->_state),
2273 c->cid.cid_num ? c->cid.cid_num : "<unknown>",
2274 c->cid.cid_name ? c->cid.cid_name : "<unknown>",
2280 ast_log(LOG_WARNING, "No channel type registered for '%s'\n", type);
2281 *cause = AST_CAUSE_NOSUCHDRIVER;
2282 ast_mutex_unlock(&chlock);
2287 int ast_call(struct ast_channel *chan, char *addr, int timeout)
2289 /* Place an outgoing call, but don't wait any longer than timeout ms before returning.
2290 If the remote end does not answer within the timeout, then do NOT hang up, but
2293 /* Stop if we're a zombie or need a soft hangup */
2294 ast_mutex_lock(&chan->lock);
2295 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan))
2296 if (chan->tech->call)
2297 res = chan->tech->call(chan, addr, timeout);
2298 ast_mutex_unlock(&chan->lock);
2302 /*--- ast_transfer: Transfer a call to dest, if the channel supports transfer */
2303 /* called by app_transfer or the manager interface */
2304 int ast_transfer(struct ast_channel *chan, char *dest)
2308 /* Stop if we're a zombie or need a soft hangup */
2309 ast_mutex_lock(&chan->lock);
2310 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
2311 if (chan->tech->transfer) {
2312 res = chan->tech->transfer(chan, dest);
2318 ast_mutex_unlock(&chan->lock);
2322 int ast_readstring(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders)
2328 /* XXX Merge with full version? XXX */
2329 /* Stop if we're a zombie or need a soft hangup */
2330 if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
2336 d = ast_waitstream(c, AST_DIGIT_ANY);
2340 d = ast_waitfordigit(c, to);
2342 d = ast_waitfordigit(c, to);
2350 if (!strchr(enders, d))
2352 if (strchr(enders, d) || (pos >= len)) {
2362 int ast_readstring_full(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders, int audiofd, int ctrlfd)
2368 /* Stop if we're a zombie or need a soft hangup */
2369 if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
2375 d = ast_waitstream_full(c, AST_DIGIT_ANY, audiofd, ctrlfd);
2379 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
2381 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
2393 if (!strchr(enders, d))
2395 if (strchr(enders, d) || (pos >= len)) {
2405 int ast_channel_supports_html(struct ast_channel *chan)
2407 if (chan->tech->send_html)
2412 int ast_channel_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
2414 if (chan->tech->send_html)
2415 return chan->tech->send_html(chan, subclass, data, datalen);
2419 int ast_channel_sendurl(struct ast_channel *chan, const char *url)
2421 if (chan->tech->send_html)
2422 return chan->tech->send_html(chan, AST_HTML_URL, url, strlen(url) + 1);
2426 int ast_channel_make_compatible(struct ast_channel *chan, struct ast_channel *peer)
2431 /* Set up translation from the chan to the peer */
2432 src = chan->nativeformats;
2433 dst = peer->nativeformats;
2434 if (ast_translator_best_choice(&dst, &src) < 0) {
2435 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", chan->name, src, peer->name, dst);
2439 /* if the best path is not 'pass through', then
2440 transcoding is needed; if desired, force transcode path
2441 to use SLINEAR between channels */
2442 if ((src != dst) && option_transcode_slin)
2443 dst = AST_FORMAT_SLINEAR;
2444 if (ast_set_read_format(chan, dst) < 0) {
2445 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", chan->name, dst);
2448 if (ast_set_write_format(peer, dst) < 0) {
2449 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", peer->name, dst);
2453 /* Set up translation from the peer to the chan */
2454 src = peer->nativeformats;
2455 dst = chan->nativeformats;
2456 if (ast_translator_best_choice(&dst, &src) < 0) {
2457 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", peer->name, src, chan->name, dst);
2460 /* if the best path is not 'pass through', then
2461 transcoding is needed; if desired, force transcode path
2462 to use SLINEAR between channels */
2463 if ((src != dst) && option_transcode_slin)
2464 dst = AST_FORMAT_SLINEAR;
2465 if (ast_set_read_format(peer, dst) < 0) {
2466 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", peer->name, dst);
2469 if (ast_set_write_format(chan, dst) < 0) {
2470 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", chan->name, dst);
2476 int ast_channel_masquerade(struct ast_channel *original, struct ast_channel *clone)
2478 struct ast_frame null = { AST_FRAME_NULL, };
2481 if (original == clone) {
2482 ast_log(LOG_WARNING, "Can't masquerade channel '%s' into itself!\n", original->name);
2485 ast_mutex_lock(&original->lock);
2486 while(ast_mutex_trylock(&clone->lock)) {
2487 ast_mutex_unlock(&original->lock);
2489 ast_mutex_lock(&original->lock);
2491 ast_log(LOG_DEBUG, "Planning to masquerade channel %s into the structure of %s\n",
2492 clone->name, original->name);
2493 if (original->masq) {
2494 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n",
2495 original->masq->name, original->name);
2496 } else if (clone->masqr) {
2497 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n",
2498 clone->name, clone->masqr->name);
2500 original->masq = clone;
2501 clone->masqr = original;
2502 ast_queue_frame(original, &null);
2503 ast_queue_frame(clone, &null);
2504 ast_log(LOG_DEBUG, "Done planning to masquerade channel %s into the structure of %s\n", clone->name, original->name);
2507 ast_mutex_unlock(&clone->lock);
2508 ast_mutex_unlock(&original->lock);
2512 void ast_change_name(struct ast_channel *chan, char *newname)
2515 ast_copy_string(tmp, chan->name, sizeof(tmp));
2516 ast_copy_string(chan->name, newname, sizeof(chan->name));
2517 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", tmp, chan->name, chan->uniqueid);
2520 void ast_channel_inherit_variables(const struct ast_channel *parent, struct ast_channel *child)
2522 struct ast_var_t *current, *newvar;
2525 AST_LIST_TRAVERSE(&parent->varshead, current, entries) {
2528 varname = ast_var_full_name(current);
2532 if (varname[0] == '_') {
2534 if (varname[1] == '_')
2540 newvar = ast_var_assign(&varname[1], ast_var_value(current));
2542 AST_LIST_INSERT_TAIL(&child->varshead, newvar, entries);
2544 ast_log(LOG_DEBUG, "Copying soft-transferable variable %s.\n", ast_var_name(newvar));
2548 newvar = ast_var_assign(ast_var_full_name(current), ast_var_value(current));
2550 AST_LIST_INSERT_TAIL(&child->varshead, newvar, entries);
2552 ast_log(LOG_DEBUG, "Copying hard-transferable variable %s.\n", ast_var_name(newvar));
2557 ast_log(LOG_DEBUG, "Not copying variable %s.\n", ast_var_name(current));
2563 /* Clone channel variables from 'clone' channel into 'original' channel
2564 All variables except those related to app_groupcount are cloned
2565 Variables are actually _removed_ from 'clone' channel, presumably
2566 because it will subsequently be destroyed.
2567 Assumes locks will be in place on both channels when called.
2570 static void clone_variables(struct ast_channel *original, struct ast_channel *clone)
2572 struct ast_var_t *varptr;
2574 /* we need to remove all app_groupcount related variables from the original
2575 channel before merging in the clone's variables; any groups assigned to the
2576 original channel should be released, only those assigned to the clone
2580 AST_LIST_TRAVERSE_SAFE_BEGIN(&original->varshead, varptr, entries) {
2581 if (!strncmp(ast_var_name(varptr), GROUP_CATEGORY_PREFIX, strlen(GROUP_CATEGORY_PREFIX))) {
2582 AST_LIST_REMOVE(&original->varshead, varptr, entries);
2583 ast_var_delete(varptr);
2586 AST_LIST_TRAVERSE_SAFE_END;
2588 /* Append variables from clone channel into original channel */
2589 /* XXX Is this always correct? We have to in order to keep MACROS working XXX */
2590 if (AST_LIST_FIRST(&clone->varshead))
2591 AST_LIST_INSERT_TAIL(&original->varshead, AST_LIST_FIRST(&clone->varshead), entries);
2594 /*--- ast_do_masquerade: Masquerade a channel */
2595 /* Assumes channel will be locked when called */
2596 int ast_do_masquerade(struct ast_channel *original)
2601 struct ast_frame *cur, *prev;
2602 const struct ast_channel_tech *t;
2604 struct ast_callerid tmpcid;
2605 struct ast_channel *clone = original->masq;
2606 int rformat = original->readformat;
2607 int wformat = original->writeformat;
2613 if (option_debug > 3)
2614 ast_log(LOG_DEBUG, "Actually Masquerading %s(%d) into the structure of %s(%d)\n",
2615 clone->name, clone->_state, original->name, original->_state);
2617 /* XXX This is a seriously wacked out operation. We're essentially putting the guts of
2618 the clone channel into the original channel. Start by killing off the original
2619 channel's backend. I'm not sure we're going to keep this function, because
2620 while the features are nice, the cost is very high in terms of pure nastiness. XXX */
2622 /* We need the clone's lock, too */
2623 ast_mutex_lock(&clone->lock);
2625 ast_log(LOG_DEBUG, "Got clone lock for masquerade on '%s' at %p\n", clone->name, &clone->lock);
2627 /* Having remembered the original read/write formats, we turn off any translation on either
2629 free_translation(clone);
2630 free_translation(original);
2633 /* Unlink the masquerade */
2634 original->masq = NULL;
2635 clone->masqr = NULL;
2637 /* Save the original name */
2638 ast_copy_string(orig, original->name, sizeof(orig));
2639 /* Save the new name */
2640 ast_copy_string(newn, clone->name, sizeof(newn));
2641 /* Create the masq name */
2642 snprintf(masqn, sizeof(masqn), "%s<MASQ>", newn);
2644 /* Copy the name from the clone channel */
2645 ast_copy_string(original->name, newn, sizeof(original->name));
2647 /* Mangle the name of the clone channel */
2648 ast_copy_string(clone->name, masqn, sizeof(clone->name));
2650 /* Notify any managers of the change, first the masq then the other */
2651 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", newn, masqn, clone->uniqueid);
2652 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", orig, newn, original->uniqueid);
2654 /* Swap the technlogies */
2656 original->tech = clone->tech;
2659 t_pvt = original->tech_pvt;
2660 original->tech_pvt = clone->tech_pvt;
2661 clone->tech_pvt = t_pvt;
2663 /* Swap the readq's */
2664 cur = original->readq;
2665 original->readq = clone->readq;
2668 /* Swap the alertpipes */
2669 for (i = 0; i < 2; i++) {
2670 x = original->alertpipe[i];
2671 original->alertpipe[i] = clone->alertpipe[i];
2672 clone->alertpipe[i] = x;
2675 /* Swap the raw formats */
2676 x = original->rawreadformat;
2677 original->rawreadformat = clone->rawreadformat;
2678 clone->rawreadformat = x;
2679 x = original->rawwriteformat;
2680 original->rawwriteformat = clone->rawwriteformat;
2681 clone->rawwriteformat = x;
2683 /* Save any pending frames on both sides. Start by counting
2684 * how many we're going to need... */
2693 /* If we had any, prepend them to the ones already in the queue, and
2694 * load up the alertpipe */
2696 prev->next = original->readq;
2697 original->readq = clone->readq;
2698 clone->readq = NULL;
2699 if (original->alertpipe[1] > -1) {
2700 for (i = 0; i < x; i++)
2701 write(original->alertpipe[1], &x, sizeof(x));
2704 clone->_softhangup = AST_SOFTHANGUP_DEV;
2707 /* And of course, so does our current state. Note we need not
2708 call ast_setstate since the event manager doesn't really consider
2709 these separate. We do this early so that the clone has the proper
2710 state of the original channel. */
2711 origstate = original->_state;
2712 original->_state = clone->_state;
2713 clone->_state = origstate;
2715 if (clone->tech->fixup){
2716 res = clone->tech->fixup(original, clone);
2718 ast_log(LOG_WARNING, "Fixup failed on channel %s, strange things may happen.\n", clone->name);
2721 /* Start by disconnecting the original's physical side */
2722 if (clone->tech->hangup)
2723 res = clone->tech->hangup(clone);
2725 ast_log(LOG_WARNING, "Hangup failed! Strange things may happen!\n");
2726 ast_mutex_unlock(&clone->lock);
2730 snprintf(zombn, sizeof(zombn), "%s<ZOMBIE>", orig);
2731 /* Mangle the name of the clone channel */
2732 ast_copy_string(clone->name, zombn, sizeof(clone->name));
2733 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", masqn, zombn, clone->uniqueid);
2735 /* Update the type. */
2736 original->type = clone->type;
2737 t_pvt = original->monitor;
2738 original->monitor = clone->monitor;
2739 clone->monitor = t_pvt;
2741 /* Keep the same language. */
2742 ast_copy_string(original->language, clone->language, sizeof(original->language));
2744 for (x = 0; x < AST_MAX_FDS; x++) {
2745 original->fds[x] = clone->fds[x];
2747 clone_variables(original, clone);
2748 clone->varshead.first = NULL;
2749 /* Presense of ADSI capable CPE follows clone */
2750 original->adsicpe = clone->adsicpe;
2751 /* Bridge remains the same */
2752 /* CDR fields remain the same */
2753 /* XXX What about blocking, softhangup, blocker, and lock and blockproc? XXX */
2754 /* Application and data remain the same */
2755 /* Clone exception becomes real one, as with fdno */
2756 ast_copy_flags(original, clone, AST_FLAG_EXCEPTION);
2757 original->fdno = clone->fdno;
2758 /* Schedule context remains the same */
2759 /* Stream stuff stays the same */
2760 /* Keep the original state. The fixup code will need to work with it most likely */
2762 /* Just swap the whole structures, nevermind the allocations, they'll work themselves
2764 tmpcid = original->cid;
2765 original->cid = clone->cid;
2766 clone->cid = tmpcid;
2768 /* Restore original timing file descriptor */
2769 original->fds[AST_MAX_FDS - 2] = original->timingfd;
2771 /* Our native formats are different now */
2772 original->nativeformats = clone->nativeformats;
2774 /* Context, extension, priority, app data, jump table, remain the same */
2775 /* pvt switches. pbx stays the same, as does next */
2777 /* Set the write format */
2778 ast_set_write_format(original, wformat);
2780 /* Set the read format */
2781 ast_set_read_format(original, rformat);
2783 /* Copy the music class */
2784 ast_copy_string(original->musicclass, clone->musicclass, sizeof(original->musicclass));
2786 ast_log(LOG_DEBUG, "Putting channel %s in %d/%d formats\n", original->name, wformat, rformat);
2788 /* Okay. Last thing is to let the channel driver know about all this mess, so he
2789 can fix up everything as best as possible */
2790 if (original->tech->fixup) {
2791 res = original->tech->fixup(clone, original);
2793 ast_log(LOG_WARNING, "Channel for type '%s' could not fixup channel %s\n",
2794 original->type, original->name);
2795 ast_mutex_unlock(&clone->lock);
2799 ast_log(LOG_WARNING, "Channel type '%s' does not have a fixup routine (for %s)! Bad things may happen.\n",
2800 original->type, original->name);
2802 /* Now, at this point, the "clone" channel is totally F'd up. We mark it as
2803 a zombie so nothing tries to touch it. If it's already been marked as a
2804 zombie, then free it now (since it already is considered invalid). */
2805 if (ast_test_flag(clone, AST_FLAG_ZOMBIE)) {
2806 ast_log(LOG_DEBUG, "Destroying channel clone '%s'\n", clone->name);
2807 ast_mutex_unlock(&clone->lock);
2808 ast_channel_free(clone);
2809 manager_event(EVENT_FLAG_CALL, "Hangup",
2813 "Cause-txt: %s\r\n",
2817 ast_cause2str(clone->hangupcause)
2820 struct ast_frame null_frame = { AST_FRAME_NULL, };
2821 ast_log(LOG_DEBUG, "Released clone lock on '%s'\n", clone->name);
2822 ast_set_flag(clone, AST_FLAG_ZOMBIE);
2823 ast_queue_frame(clone, &null_frame);
2824 ast_mutex_unlock(&clone->lock);
2827 /* Signal any blocker */
2828 if (ast_test_flag(original, AST_FLAG_BLOCKING))
2829 pthread_kill(original->blocker, SIGURG);
2830 ast_log(LOG_DEBUG, "Done Masquerading %s (%d)\n", original->name, original->_state);
2834 void ast_set_callerid(struct ast_channel *chan, const char *callerid, const char *calleridname, const char *ani)
2837 if (chan->cid.cid_num)
2838 free(chan->cid.cid_num);
2839 if (ast_strlen_zero(callerid))
2840 chan->cid.cid_num = NULL;
2842 chan->cid.cid_num = strdup(callerid);
2845 if (chan->cid.cid_name)
2846 free(chan->cid.cid_name);
2847 if (ast_strlen_zero(calleridname))
2848 chan->cid.cid_name = NULL;
2850 chan->cid.cid_name = strdup(calleridname);
2853 if (chan->cid.cid_ani)
2854 free(chan->cid.cid_ani);
2855 if (ast_strlen_zero(ani))
2856 chan->cid.cid_ani = NULL;
2858 chan->cid.cid_ani = strdup(ani);
2861 ast_cdr_setcid(chan->cdr, chan);
2862 manager_event(EVENT_FLAG_CALL, "Newcallerid",
2865 "CallerIDName: %s\r\n"
2867 "CID-CallingPres: %d (%s)\r\n",
2868 chan->name, chan->cid.cid_num ?
2869 chan->cid.cid_num : "<Unknown>",
2870 chan->cid.cid_name ?
2871 chan->cid.cid_name : "<Unknown>",
2874 ast_describe_caller_presentation(chan->cid.cid_pres)
2878 int ast_setstate(struct ast_channel *chan, int state)
2880 int oldstate = chan->_state;
2882 if (oldstate == state)
2885 chan->_state = state;
2886 ast_device_state_changed(chan->name);
2887 manager_event(EVENT_FLAG_CALL,
2888 (oldstate == AST_STATE_DOWN) ? "Newchannel" : "Newstate",
2892 "CallerIDName: %s\r\n"
2894 chan->name, ast_state2str(chan->_state),
2895 chan->cid.cid_num ? chan->cid.cid_num : "<unknown>",
2896 chan->cid.cid_name ? chan->cid.cid_name : "<unknown>",
2902 /*--- Find bridged channel */
2903 struct ast_channel *ast_bridged_channel(struct ast_channel *chan)
2905 struct ast_channel *bridged;
2906 bridged = chan->_bridge;
2907 if (bridged && bridged->tech->bridged_channel)
2908 bridged = bridged->tech->bridged_channel(chan, bridged);
2912 static void bridge_playfile(struct ast_channel *chan, struct ast_channel *peer, char *sound, int remain)
2914 int res=0, min=0, sec=0,check=0;
2916 check = ast_autoservice_start(peer);
2921 if (remain / 60 > 1) {
2929 if (!strcmp(sound,"timeleft")) { /* Queue support */
2930 res = ast_streamfile(chan, "vm-youhave", chan->language);
2931 res = ast_waitstream(chan, "");
2933 res = ast_say_number(chan, min, AST_DIGIT_ANY, chan->language, (char *) NULL);
2934 res = ast_streamfile(chan, "queue-minutes", chan->language);
2935 res = ast_waitstream(chan, "");
2938 res = ast_say_number(chan, sec, AST_DIGIT_ANY, chan->language, (char *) NULL);
2939 res = ast_streamfile(chan, "queue-seconds", chan->language);
2940 res = ast_waitstream(chan, "");
2943 res = ast_streamfile(chan, sound, chan->language);
2944 res = ast_waitstream(chan, "");
2947 check = ast_autoservice_stop(peer);
2950 static enum ast_bridge_result ast_generic_bridge(int *playitagain, int *playit, struct ast_channel *c0, struct ast_channel *c1,
2951 struct ast_bridge_config *config, struct ast_frame **fo, struct ast_channel **rc)
2953 /* Copy voice back and forth between the two channels. */
2954 struct ast_channel *cs[3];
2956 struct ast_frame *f;
2957 struct ast_channel *who = NULL;
2958 enum ast_bridge_result res = AST_BRIDGE_COMPLETE;
2959 int o0nativeformats;
2960 int o1nativeformats;
2961 long elapsed_ms=0, time_left_ms=0;
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;
2984 if (config->timelimit) {
2985 /* If there is a time limit, return now */
2986 elapsed_ms = ast_tvdiff_ms(ast_tvnow(), config->start_time);
2987 time_left_ms = config->timelimit - elapsed_ms;
2990 ((ast_test_flag(&(config->features_caller), AST_FEATURE_PLAY_WARNING)) ||
2991 (ast_test_flag(&(config->features_callee), AST_FEATURE_PLAY_WARNING))) &&
2992 (config->play_warning && time_left_ms <= config->play_warning)) {
2993 if (config->warning_freq == 0 || time_left_ms == config->play_warning || (time_left_ms % config->warning_freq) <= 50) {
2994 res = AST_BRIDGE_RETRY;
2998 if (time_left_ms <= 0) {
2999 res = AST_BRIDGE_RETRY;
3002 if (time_left_ms >= 5000 && *playit) {
3003 res = AST_BRIDGE_RETRY;
3010 who = ast_waitfor_n(cs, 2, &to);
3012 ast_log(LOG_DEBUG, "Nobody there, continuing...\n");
3013 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE || c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE) {
3014 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
3015 c0->_softhangup = 0;
3016 if (c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
3017 c1->_softhangup = 0;
3027 res = AST_BRIDGE_COMPLETE;
3028 ast_log(LOG_DEBUG, "Didn't get a frame from channel: %s\n",who->name);
3032 if ((f->frametype == AST_FRAME_CONTROL) && !(config->flags & AST_BRIDGE_IGNORE_SIGS)) {
3033 if ((f->subclass == AST_CONTROL_HOLD) || (f->subclass == AST_CONTROL_UNHOLD) ||
3034 (f->subclass == AST_CONTROL_VIDUPDATE)) {
3035 ast_indicate(who == c0 ? c1 : c0, f->subclass);
3039 res = AST_BRIDGE_COMPLETE;
3040 ast_log(LOG_DEBUG, "Got a FRAME_CONTROL (%d) frame on channel %s\n", f->subclass, who->name);
3044 if ((f->frametype == AST_FRAME_VOICE) ||
3045 (f->frametype == AST_FRAME_DTMF) ||
3046 (f->frametype == AST_FRAME_VIDEO) ||
3047 (f->frametype == AST_FRAME_IMAGE) ||
3048 (f->frametype == AST_FRAME_HTML) ||
3049 (f->frametype == AST_FRAME_TEXT)) {
3050 if (f->frametype == AST_FRAME_DTMF) {
3051 if (((who == c0) && watch_c0_dtmf) ||
3052 ((who == c1) && watch_c1_dtmf)) {
3055 res = AST_BRIDGE_COMPLETE;
3056 ast_log(LOG_DEBUG, "Got DTMF on channel (%s)\n", who->name);
3063 ast_log(LOG_DEBUG, "Read from %s\n", who->name);
3065 ast_log(LOG_DEBUG, "Servicing channel %s twice in a row?\n", last->name);
3069 ast_write((who == c0) ? c1 : c0, f);
3074 /* Swap who gets priority */
3082 /*--- ast_channel_bridge: Bridge two channels together */
3083 enum ast_bridge_result ast_channel_bridge(struct ast_channel *c0, struct ast_channel *c1,
3084 struct ast_bridge_config *config, struct ast_frame **fo, struct ast_channel **rc)
3086 struct ast_channel *who = NULL;
3087 enum ast_bridge_result res = AST_BRIDGE_COMPLETE;
3090 int o0nativeformats;
3091 int o1nativeformats;
3092 long elapsed_ms=0, time_left_ms=0;
3093 int playit=0, playitagain=1, first_time=1;
3094 char caller_warning = 0;
3095 char callee_warning = 0;
3098 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n",
3099 c0->name, c0->_bridge->name);
3103 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n",
3104 c1->name, c1->_bridge->name);
3108 /* Stop if we're a zombie or need a soft hangup */
3109 if (ast_test_flag(c0, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c0) ||
3110 ast_test_flag(c1, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c1))
3114 firstpass = config->firstpass;
3115 config->firstpass = 0;
3117 if (ast_tvzero(config->start_time))
3118 config->start_time = ast_tvnow();
3119 time_left_ms = config->timelimit;
3121 caller_warning = ast_test_flag(&config->features_caller, AST_FEATURE_PLAY_WARNING);
3122 callee_warning = ast_test_flag(&config->features_callee, AST_FEATURE_PLAY_WARNING);
3124 if (config->start_sound && firstpass) {
3126 bridge_playfile(c0, c1, config->start_sound, time_left_ms / 1000);
3128 bridge_playfile(c1, c0, config->start_sound, time_left_ms / 1000);
3131 /* Keep track of bridge */
3135 manager_event(EVENT_FLAG_CALL, "Link",
3141 "CallerID2: %s\r\n",
3142 c0->name, c1->name, c0->uniqueid, c1->uniqueid, c0->cid.cid_num, c1->cid.cid_num);
3144 o0nativeformats = c0->nativeformats;
3145 o1nativeformats = c1->nativeformats;
3147 for (/* ever */;;) {
3148 if (config->timelimit) {