2 * Asterisk -- A telephony toolkit for Linux.
6 * Copyright (C) 1999 - 2005, Digium, Inc.
8 * Mark Spencer <markster@digium.com>
10 * This program is free software, distributed under the terms of
11 * the GNU General Public License
21 #include <math.h> /* For PI */
23 #ifdef ZAPTEL_OPTIMIZATIONS
24 #include <sys/ioctl.h>
26 #include <linux/zaptel.h>
29 #endif /* __linux__ */
31 #error "You need newer zaptel! Please cvs update zaptel"
37 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
39 #include "asterisk/pbx.h"
40 #include "asterisk/frame.h"
41 #include "asterisk/sched.h"
42 #include "asterisk/options.h"
43 #include "asterisk/channel.h"
44 #include "asterisk/musiconhold.h"
45 #include "asterisk/logger.h"
46 #include "asterisk/say.h"
47 #include "asterisk/file.h"
48 #include "asterisk/cli.h"
49 #include "asterisk/translate.h"
50 #include "asterisk/manager.h"
51 #include "asterisk/chanvars.h"
52 #include "asterisk/linkedlists.h"
53 #include "asterisk/indications.h"
54 #include "asterisk/monitor.h"
55 #include "asterisk/causes.h"
56 #include "asterisk/utils.h"
57 #include "asterisk/lock.h"
58 #include "asterisk/app.h"
59 #include "asterisk/transcap.h"
60 #include "asterisk/devicestate.h"
62 /* uncomment if you have problems with 'monitoring' synchronized files */
64 #define MONITOR_CONSTANT_DELAY
65 #define MONITOR_DELAY 150 * 8 /* 150 ms of MONITORING DELAY */
69 * Prevent new channel allocation if shutting down.
71 static int shutting_down = 0;
73 static int uniqueint = 0;
75 unsigned long global_fin = 0, global_fout = 0;
77 /* XXX Lock appropriately in more functions XXX */
80 const struct ast_channel_tech *tech;
81 struct chanlist *next;
84 static struct chanlist *backends = NULL;
87 * the list of channels we have
89 static struct ast_channel *channels = NULL;
91 /* Protect the channel list, both backends and channels.
93 AST_MUTEX_DEFINE_STATIC(chlock);
95 const struct ast_cause {
99 { AST_CAUSE_UNALLOCATED, "Unallocated (unassigned) number" },
100 { AST_CAUSE_NO_ROUTE_TRANSIT_NET, "No route to specified transmit network" },
101 { AST_CAUSE_NO_ROUTE_DESTINATION, "No route to destination" },
102 { AST_CAUSE_CHANNEL_UNACCEPTABLE, "Channel unacceptable" },
103 { AST_CAUSE_CALL_AWARDED_DELIVERED, "Call awarded and being delivered in an established channel" },
104 { AST_CAUSE_NORMAL_CLEARING, "Normal Clearing" },
105 { AST_CAUSE_USER_BUSY, "User busy" },
106 { AST_CAUSE_NO_USER_RESPONSE, "No user responding" },
107 { AST_CAUSE_NO_ANSWER, "User alerting, no answer" },
108 { AST_CAUSE_CALL_REJECTED, "Call Rejected" },
109 { AST_CAUSE_NUMBER_CHANGED, "Number changed" },
110 { AST_CAUSE_DESTINATION_OUT_OF_ORDER, "Destination out of order" },
111 { AST_CAUSE_INVALID_NUMBER_FORMAT, "Invalid number format" },
112 { AST_CAUSE_FACILITY_REJECTED, "Facility rejected" },
113 { AST_CAUSE_RESPONSE_TO_STATUS_ENQUIRY, "Response to STATus ENQuiry" },
114 { AST_CAUSE_NORMAL_UNSPECIFIED, "Normal, unspecified" },
115 { AST_CAUSE_NORMAL_CIRCUIT_CONGESTION, "Circuit/channel congestion" },
116 { AST_CAUSE_NETWORK_OUT_OF_ORDER, "Network out of order" },
117 { AST_CAUSE_NORMAL_TEMPORARY_FAILURE, "Temporary failure" },
118 { AST_CAUSE_SWITCH_CONGESTION, "Switching equipment congestion" },
119 { AST_CAUSE_ACCESS_INFO_DISCARDED, "Access information discarded" },
120 { AST_CAUSE_REQUESTED_CHAN_UNAVAIL, "Requested channel not available" },
121 { AST_CAUSE_PRE_EMPTED, "Pre-empted" },
122 { AST_CAUSE_FACILITY_NOT_SUBSCRIBED, "Facility not subscribed" },
123 { AST_CAUSE_OUTGOING_CALL_BARRED, "Outgoing call barred" },
124 { AST_CAUSE_INCOMING_CALL_BARRED, "Incoming call barred" },
125 { AST_CAUSE_BEARERCAPABILITY_NOTAUTH, "Bearer capability not authorized" },
126 { AST_CAUSE_BEARERCAPABILITY_NOTAVAIL, "Bearer capability not available" },
127 { AST_CAUSE_BEARERCAPABILITY_NOTIMPL, "Bearer capability not implemented" },
128 { AST_CAUSE_CHAN_NOT_IMPLEMENTED, "Channel not implemented" },
129 { AST_CAUSE_FACILITY_NOT_IMPLEMENTED, "Facility not implemented" },
130 { AST_CAUSE_INVALID_CALL_REFERENCE, "Invalid call reference value" },
131 { AST_CAUSE_INCOMPATIBLE_DESTINATION, "Incompatible destination" },
132 { AST_CAUSE_INVALID_MSG_UNSPECIFIED, "Invalid message unspecified" },
133 { AST_CAUSE_MANDATORY_IE_MISSING, "Mandatory information element is missing" },
134 { AST_CAUSE_MESSAGE_TYPE_NONEXIST, "Message type nonexist." },
135 { AST_CAUSE_WRONG_MESSAGE, "Wrong message" },
136 { AST_CAUSE_IE_NONEXIST, "Info. element nonexist or not implemented" },
137 { AST_CAUSE_INVALID_IE_CONTENTS, "Invalid information element contents" },
138 { AST_CAUSE_WRONG_CALL_STATE, "Message not compatible with call state" },
139 { AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE, "Recover on timer expiry" },
140 { AST_CAUSE_MANDATORY_IE_LENGTH_ERROR, "Mandatory IE length error" },
141 { AST_CAUSE_PROTOCOL_ERROR, "Protocol error, unspecified" },
142 { AST_CAUSE_INTERWORKING, "Interworking, unspecified" },
146 static int show_channeltypes(int fd, int argc, char *argv[])
148 #define FORMAT "%-10.10s %-50.50s %-12.12s\n"
149 struct chanlist *cl = backends;
150 ast_cli(fd, FORMAT, "Type", "Description", "Devicestate");
151 ast_cli(fd, FORMAT, "----------", "-----------", "-----------");
152 if (ast_mutex_lock(&chlock)) {
153 ast_log(LOG_WARNING, "Unable to lock channel list\n");
157 ast_cli(fd, FORMAT, cl->tech->type, cl->tech->description, (cl->tech->devicestate)?"yes":"no");
160 ast_mutex_unlock(&chlock);
161 return RESULT_SUCCESS;
167 static char show_channeltypes_usage[] =
168 "Usage: show channeltypes\n"
169 " Shows available channel types registered in your Asterisk server.\n";
171 static struct ast_cli_entry cli_show_channeltypes =
172 { { "show", "channeltypes", NULL }, show_channeltypes, "Show available channel types", show_channeltypes_usage };
174 /*--- ast_check_hangup: Checks to see if a channel is needing hang up */
175 int ast_check_hangup(struct ast_channel *chan)
179 /* if soft hangup flag, return true */
180 if (chan->_softhangup)
182 /* if no technology private data, return true */
185 /* if no hangup scheduled, just return here */
186 if (!chan->whentohangup)
188 time(&myt); /* get current time */
189 /* return, if not yet */
190 if (chan->whentohangup > myt)
192 chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
196 static int ast_check_hangup_locked(struct ast_channel *chan)
199 ast_mutex_lock(&chan->lock);
200 res = ast_check_hangup(chan);
201 ast_mutex_unlock(&chan->lock);
205 /*--- ast_begin_shutdown: Initiate system shutdown */
206 void ast_begin_shutdown(int hangup)
208 struct ast_channel *c;
211 ast_mutex_lock(&chlock);
214 ast_softhangup(c, AST_SOFTHANGUP_SHUTDOWN);
217 ast_mutex_unlock(&chlock);
221 /*--- ast_active_channels: returns number of active/allocated channels */
222 int ast_active_channels(void)
224 struct ast_channel *c;
226 ast_mutex_lock(&chlock);
232 ast_mutex_unlock(&chlock);
236 /*--- ast_cancel_shutdown: Cancel a shutdown in progress */
237 void ast_cancel_shutdown(void)
242 /*--- ast_shutting_down: Returns non-zero if Asterisk is being shut down */
243 int ast_shutting_down(void)
245 return shutting_down;
248 /*--- ast_channel_setwhentohangup: Set when to hangup channel */
249 void ast_channel_setwhentohangup(struct ast_channel *chan, time_t offset)
255 chan->whentohangup = myt + offset;
257 chan->whentohangup = 0;
261 /*--- ast_channel_register: Register a new telephony channel in Asterisk */
262 int ast_channel_register(const struct ast_channel_tech *tech)
264 struct chanlist *chan;
266 ast_mutex_lock(&chlock);
270 if (!strcasecmp(tech->type, chan->tech->type)) {
271 ast_log(LOG_WARNING, "Already have a handler for type '%s'\n", tech->type);
272 ast_mutex_unlock(&chlock);
278 chan = malloc(sizeof(*chan));
280 ast_log(LOG_WARNING, "Out of memory\n");
281 ast_mutex_unlock(&chlock);
285 chan->next = backends;
289 ast_log(LOG_DEBUG, "Registered handler for '%s' (%s)\n", chan->tech->type, chan->tech->description);
291 if (option_verbose > 1)
292 ast_verbose(VERBOSE_PREFIX_2 "Registered channel type '%s' (%s)\n", chan->tech->type,
293 chan->tech->description);
295 ast_mutex_unlock(&chlock);
299 void ast_channel_unregister(const struct ast_channel_tech *tech)
301 struct chanlist *chan, *last=NULL;
304 ast_log(LOG_DEBUG, "Unregistering channel type '%s'\n", tech->type);
306 ast_mutex_lock(&chlock);
310 if (chan->tech == tech) {
312 last->next = chan->next;
314 backends = backends->next;
316 ast_mutex_unlock(&chlock);
318 if (option_verbose > 1)
319 ast_verbose( VERBOSE_PREFIX_2 "Unregistered channel type '%s'\n", tech->type);
327 ast_mutex_unlock(&chlock);
330 const struct ast_channel_tech *ast_get_channel_tech(const char *name)
332 struct chanlist *chanls;
334 if (ast_mutex_lock(&chlock)) {
335 ast_log(LOG_WARNING, "Unable to lock channel tech list\n");
339 for (chanls = backends; chanls; chanls = chanls->next) {
340 if (strcasecmp(name, chanls->tech->type))
343 ast_mutex_unlock(&chlock);
347 ast_mutex_unlock(&chlock);
351 /*--- ast_cause2str: Gives the string form of a given hangup cause */
352 const char *ast_cause2str(int cause)
356 for (x=0; x < sizeof(causes) / sizeof(causes[0]); x++)
357 if (causes[x].cause == cause)
358 return causes[x].desc;
363 /*--- ast_state2str: Gives the string form of a given channel state */
364 char *ast_state2str(int state)
366 /* XXX Not reentrant XXX */
367 static char localtmp[256];
371 case AST_STATE_RESERVED:
373 case AST_STATE_OFFHOOK:
375 case AST_STATE_DIALING:
379 case AST_STATE_RINGING:
386 snprintf(localtmp, sizeof(localtmp), "Unknown (%d)\n", state);
391 /*--- ast_transfercapability2str: Gives the string form of a given transfer capability */
392 char *ast_transfercapability2str(int transfercapability)
394 switch(transfercapability) {
395 case AST_TRANS_CAP_SPEECH:
397 case AST_TRANS_CAP_DIGITAL:
399 case AST_TRANS_CAP_RESTRICTED_DIGITAL:
400 return "RESTRICTED_DIGITAL";
401 case AST_TRANS_CAP_3_1K_AUDIO:
403 case AST_TRANS_CAP_DIGITAL_W_TONES:
404 return "DIGITAL_W_TONES";
405 case AST_TRANS_CAP_VIDEO:
412 /*--- ast_best_codec: Pick the best codec */
413 int ast_best_codec(int fmts)
415 /* This just our opinion, expressed in code. We are asked to choose
416 the best codec to use, given no information */
420 /* Okay, ulaw is used by all telephony equipment, so start with it */
422 /* Unless of course, you're a silly European, so then prefer ALAW */
424 /* Okay, well, signed linear is easy to translate into other stuff */
426 /* G.726 is standard ADPCM */
428 /* ADPCM has great sound quality and is still pretty easy to translate */
430 /* Okay, we're down to vocoders now, so pick GSM because it's small and easier to
431 translate and sounds pretty good */
433 /* iLBC is not too bad */
435 /* Speex is free, but computationally more expensive than GSM */
437 /* Ick, LPC10 sounds terrible, but at least we have code for it, if you're tacky enough
440 /* G.729a is faster than 723 and slightly less expensive */
442 /* Down to G.723.1 which is proprietary but at least designed for voice */
447 /* Find the first prefered codec in the format given */
448 for (x=0; x < (sizeof(prefs) / sizeof(prefs[0]) ); x++)
451 ast_log(LOG_WARNING, "Don't know any of 0x%x formats\n", fmts);
455 static const struct ast_channel_tech null_tech = {
457 .description = "Null channel (should not see this)",
460 /*--- ast_channel_alloc: Create a new channel structure */
461 struct ast_channel *ast_channel_alloc(int needqueue)
463 struct ast_channel *tmp;
466 struct varshead *headp;
469 /* If shutting down, don't allocate any new channels */
471 ast_log(LOG_WARNING, "Channel allocation failed: Refusing due to active shutdown\n");
475 tmp = malloc(sizeof(struct ast_channel));
477 ast_log(LOG_WARNING, "Channel allocation failed: Out of memory\n");
481 memset(tmp, 0, sizeof(struct ast_channel));
482 tmp->sched = sched_context_create();
484 ast_log(LOG_WARNING, "Channel allocation failed: Unable to create schedule context\n");
489 for (x=0; x<AST_MAX_FDS - 1; x++)
492 #ifdef ZAPTEL_OPTIMIZATIONS
493 tmp->timingfd = open("/dev/zap/timer", O_RDWR);
494 if (tmp->timingfd > -1) {
495 /* Check if timing interface supports new
498 if (!ioctl(tmp->timingfd, ZT_TIMERPONG, &flags))
506 if (pipe(tmp->alertpipe)) {
507 ast_log(LOG_WARNING, "Channel allocation failed: Can't create alert pipe!\n");
511 flags = fcntl(tmp->alertpipe[0], F_GETFL);
512 fcntl(tmp->alertpipe[0], F_SETFL, flags | O_NONBLOCK);
513 flags = fcntl(tmp->alertpipe[1], F_GETFL);
514 fcntl(tmp->alertpipe[1], F_SETFL, flags | O_NONBLOCK);
517 /* Make sure we've got it done right if they don't */
518 tmp->alertpipe[0] = tmp->alertpipe[1] = -1;
520 /* Always watch the alertpipe */
521 tmp->fds[AST_MAX_FDS-1] = tmp->alertpipe[0];
522 /* And timing pipe */
523 tmp->fds[AST_MAX_FDS-2] = tmp->timingfd;
524 strcpy(tmp->name, "**Unkown**");
526 tmp->_state = AST_STATE_DOWN;
530 tmp->fin = global_fin;
531 tmp->fout = global_fout;
532 snprintf(tmp->uniqueid, sizeof(tmp->uniqueid), "%li.%d", (long)time(NULL), uniqueint++);
533 headp = &tmp->varshead;
534 ast_mutex_init(&tmp->lock);
535 AST_LIST_HEAD_INIT(headp);
536 strcpy(tmp->context, "default");
537 ast_copy_string(tmp->language, defaultlanguage, sizeof(tmp->language));
538 strcpy(tmp->exten, "s");
540 tmp->amaflags = ast_default_amaflags;
541 ast_copy_string(tmp->accountcode, ast_default_accountcode, sizeof(tmp->accountcode));
543 tmp->tech = &null_tech;
545 ast_mutex_lock(&chlock);
546 tmp->next = channels;
549 ast_mutex_unlock(&chlock);
553 /*--- ast_queue_frame: Queue an outgoing media frame */
554 int ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin)
557 struct ast_frame *prev, *cur;
560 /* Build us a copy and free the original one */
563 ast_log(LOG_WARNING, "Unable to duplicate frame\n");
566 ast_mutex_lock(&chan->lock);
570 if ((cur->frametype == AST_FRAME_CONTROL) && (cur->subclass == AST_CONTROL_HANGUP)) {
571 /* Don't bother actually queueing anything after a hangup */
573 ast_mutex_unlock(&chan->lock);
580 /* Allow up to 96 voice frames outstanding, and up to 128 total frames */
581 if (((fin->frametype == AST_FRAME_VOICE) && (qlen > 96)) || (qlen > 128)) {
582 if (fin->frametype != AST_FRAME_VOICE) {
583 ast_log(LOG_WARNING, "Exceptionally long queue length queuing to %s\n", chan->name);
586 ast_log(LOG_DEBUG, "Dropping voice to exceptionally long queue on %s\n", chan->name);
588 ast_mutex_unlock(&chan->lock);
596 if (chan->alertpipe[1] > -1) {
597 if (write(chan->alertpipe[1], &blah, sizeof(blah)) != sizeof(blah))
598 ast_log(LOG_WARNING, "Unable to write to alert pipe on %s, frametype/subclass %d/%d (qlen = %d): %s!\n",
599 chan->name, f->frametype, f->subclass, qlen, strerror(errno));
600 #ifdef ZAPTEL_OPTIMIZATIONS
601 } else if (chan->timingfd > -1) {
602 ioctl(chan->timingfd, ZT_TIMERPING, &blah);
604 } else if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
605 pthread_kill(chan->blocker, SIGURG);
607 ast_mutex_unlock(&chan->lock);
611 /*--- ast_queue_hangup: Queue a hangup frame for channel */
612 int ast_queue_hangup(struct ast_channel *chan)
614 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_HANGUP };
615 chan->_softhangup |= AST_SOFTHANGUP_DEV;
616 return ast_queue_frame(chan, &f);
619 /*--- ast_queue_control: Queue a control frame */
620 int ast_queue_control(struct ast_channel *chan, int control)
622 struct ast_frame f = { AST_FRAME_CONTROL, };
623 f.subclass = control;
624 return ast_queue_frame(chan, &f);
627 /*--- ast_channel_defer_dtmf: Set defer DTMF flag on channel */
628 int ast_channel_defer_dtmf(struct ast_channel *chan)
632 pre = ast_test_flag(chan, AST_FLAG_DEFER_DTMF);
633 ast_set_flag(chan, AST_FLAG_DEFER_DTMF);
638 /*--- ast_channel_undefer_dtmf: Unset defer DTMF flag on channel */
639 void ast_channel_undefer_dtmf(struct ast_channel *chan)
642 ast_clear_flag(chan, AST_FLAG_DEFER_DTMF);
646 * Helper function to return the channel after prev, or the one matching name,
647 * with the channel's lock held. If getting the individual lock fails,
648 * unlock and retry quickly up to 10 times, then give up.
650 * XXX Note that this code has cost O(N) because of the need to verify
651 * that the object is still on the global list.
653 * XXX also note that accessing fields (e.g. c->name in ast_log())
654 * can only be done with the lock held or someone could delete the
655 * object while we work on it. This causes some ugliness in the code.
656 * Note that removing the first ast_log() may be harmful, as it would
657 * shorten the retry period and possibly cause failures.
658 * We should definitely go for a better scheme that is deadlock-free.
660 static struct ast_channel *channel_find_locked(const struct ast_channel *prev,
661 const char *name, const int namelen)
663 const char *msg = prev ? "deadlock" : "initial deadlock";
665 struct ast_channel *c;
667 for (retries = 0; retries < 10; retries++) {
668 ast_mutex_lock(&chlock);
669 for (c = channels; c; c = c->next) {
671 /* want head of list */
674 /* want match by full name */
676 if (!strcasecmp(c->name, name))
681 /* want match by name prefix */
682 if (!strncasecmp(c->name, name, namelen))
684 } else if (c == prev) { /* found, return c->next */
689 /* exit if chan not found or mutex acquired successfully */
690 done = (c == NULL) || (ast_mutex_trylock(&c->lock) == 0);
691 /* this is slightly unsafe, as we _should_ hold the lock to access c->name */
693 ast_log(LOG_DEBUG, "Avoiding %s for '%s'\n", msg, c->name);
694 ast_mutex_unlock(&chlock);
700 * c is surely not null, but we don't have the lock so cannot
703 ast_log(LOG_WARNING, "Avoided %s for '%p', %d retries!\n",
709 /*--- ast_channel_walk_locked: Browse channels in use */
710 struct ast_channel *ast_channel_walk_locked(const struct ast_channel *prev)
712 return channel_find_locked(prev, NULL, 0);
715 /*--- ast_get_channel_by_name_locked: Get channel by name and lock it */
716 struct ast_channel *ast_get_channel_by_name_locked(const char *name)
718 return channel_find_locked(NULL, name, 0);
721 /*--- ast_get_channel_by_name_prefix_locked: Get channel by name prefix and lock it */
722 struct ast_channel *ast_get_channel_by_name_prefix_locked(const char *name, const int namelen)
724 return channel_find_locked(NULL, name, namelen);
727 /*--- ast_safe_sleep_conditional: Wait, look for hangups and condition arg */
728 int ast_safe_sleep_conditional( struct ast_channel *chan, int ms,
729 int (*cond)(void*), void *data )
734 if( cond && ((*cond)(data) == 0 ) )
736 ms = ast_waitfor(chan, ms);
749 /*--- ast_safe_sleep: Wait, look for hangups */
750 int ast_safe_sleep(struct ast_channel *chan, int ms)
754 ms = ast_waitfor(chan, ms);
767 static void free_cid(struct ast_callerid *cid)
778 free(cid->cid_rdnis);
781 /*--- ast_channel_free: Free a channel structure */
782 void ast_channel_free(struct ast_channel *chan)
784 struct ast_channel *last=NULL, *cur;
786 struct ast_var_t *vardata;
787 struct ast_frame *f, *fp;
788 struct varshead *headp;
789 char name[AST_CHANNEL_NAME];
791 headp=&chan->varshead;
793 ast_mutex_lock(&chlock);
798 last->next = cur->next;
800 channels = cur->next;
807 ast_log(LOG_WARNING, "Unable to find channel in list\n");
809 /* Lock and unlock the channel just to be sure nobody
810 has it locked still */
811 ast_mutex_lock(&cur->lock);
812 ast_mutex_unlock(&cur->lock);
814 if (chan->tech_pvt) {
815 ast_log(LOG_WARNING, "Channel '%s' may not have been hung up properly\n", chan->name);
816 free(chan->tech_pvt);
819 ast_copy_string(name, chan->name, sizeof(name));
821 /* Stop monitoring */
823 chan->monitor->stop( chan, 0 );
826 /* If there is native format music-on-hold state, free it */
827 if(chan->music_state)
828 ast_moh_cleanup(chan);
830 /* Free translatosr */
832 ast_translator_free_path(chan->readtrans);
833 if (chan->writetrans)
834 ast_translator_free_path(chan->writetrans);
836 ast_log(LOG_WARNING, "PBX may not have been terminated properly on '%s'\n", chan->name);
837 free_cid(&chan->cid);
838 ast_mutex_destroy(&chan->lock);
839 /* Close pipes if appropriate */
840 if ((fd = chan->alertpipe[0]) > -1)
842 if ((fd = chan->alertpipe[1]) > -1)
844 if ((fd = chan->timingfd) > -1)
854 /* loop over the variables list, freeing all data and deleting list items */
855 /* no need to lock the list, as the channel is already locked */
857 while (!AST_LIST_EMPTY(headp)) { /* List Deletion. */
858 vardata = AST_LIST_REMOVE_HEAD(headp, entries);
859 ast_var_delete(vardata);
863 ast_mutex_unlock(&chlock);
865 ast_device_state_changed(name);
868 static void ast_spy_detach(struct ast_channel *chan)
870 struct ast_channel_spy *chanspy;
874 for (chanspy = chan->spiers; chanspy; chanspy = chanspy->next) {
875 if (chanspy->status == CHANSPY_RUNNING) {
876 chanspy->status = CHANSPY_DONE;
880 /* signal all the spys to get lost and allow them time to unhook themselves
881 god help us if they don't......
883 while (chan->spiers && to >= 0) {
884 ast_safe_sleep(chan, sleepms);
891 /*--- ast_softhangup_nolock: Softly hangup a channel, don't lock */
892 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
895 struct ast_frame f = { AST_FRAME_NULL };
897 ast_log(LOG_DEBUG, "Soft-Hanging up channel '%s'\n", chan->name);
898 /* Inform channel driver that we need to be hung up, if it cares */
899 chan->_softhangup |= cause;
900 ast_queue_frame(chan, &f);
901 /* Interrupt any poll call or such */
902 if (ast_test_flag(chan, AST_FLAG_BLOCKING))
903 pthread_kill(chan->blocker, SIGURG);
907 /*--- ast_softhangup_nolock: Softly hangup a channel, lock */
908 int ast_softhangup(struct ast_channel *chan, int cause)
911 ast_mutex_lock(&chan->lock);
912 res = ast_softhangup_nolock(chan, cause);
913 ast_mutex_unlock(&chan->lock);
917 static void ast_queue_spy_frame(struct ast_channel_spy *spy, struct ast_frame *f, int pos)
919 struct ast_frame *tmpf = NULL;
922 ast_mutex_lock(&spy->lock);
923 for (tmpf=spy->queue[pos]; tmpf && tmpf->next; tmpf=tmpf->next) {
927 struct ast_frame *freef, *headf;
929 ast_log(LOG_ERROR, "Too Many frames queued at once, flushing cache.\n");
930 headf = spy->queue[pos];
931 /* deref the queue right away so it looks empty */
932 spy->queue[pos] = NULL;
934 /* free the wasted frames */
940 ast_mutex_unlock(&spy->lock);
945 tmpf->next = ast_frdup(f);
947 spy->queue[pos] = ast_frdup(f);
950 ast_mutex_unlock(&spy->lock);
953 static void free_translation(struct ast_channel *clone)
955 if (clone->writetrans)
956 ast_translator_free_path(clone->writetrans);
957 if (clone->readtrans)
958 ast_translator_free_path(clone->readtrans);
959 clone->writetrans = NULL;
960 clone->readtrans = NULL;
961 clone->rawwriteformat = clone->nativeformats;
962 clone->rawreadformat = clone->nativeformats;
965 /*--- ast_hangup: Hangup a channel */
966 int ast_hangup(struct ast_channel *chan)
969 /* Don't actually hang up a channel that will masquerade as someone else, or
970 if someone is going to masquerade as us */
971 ast_mutex_lock(&chan->lock);
974 ast_spy_detach(chan); /* get rid of spies */
977 if (ast_do_masquerade(chan))
978 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
982 ast_log(LOG_WARNING, "%s getting hung up, but someone is trying to masq into us?!?\n", chan->name);
983 ast_mutex_unlock(&chan->lock);
986 /* If this channel is one which will be masqueraded into something,
987 mark it as a zombie already, so we know to free it later */
989 ast_set_flag(chan, AST_FLAG_ZOMBIE);
990 ast_mutex_unlock(&chan->lock);
993 free_translation(chan);
994 if (chan->stream) /* Close audio stream */
995 ast_closestream(chan->stream);
996 if (chan->vstream) /* Close video stream */
997 ast_closestream(chan->vstream);
999 sched_context_destroy(chan->sched);
1001 if (chan->generatordata) /* Clear any tone stuff remaining */
1002 chan->generator->release(chan, chan->generatordata);
1003 chan->generatordata = NULL;
1004 chan->generator = NULL;
1005 if (chan->cdr) { /* End the CDR if it hasn't already */
1006 ast_cdr_end(chan->cdr);
1007 ast_cdr_detach(chan->cdr); /* Post and Free the CDR */
1009 if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
1010 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
1011 "is blocked by thread %ld in procedure %s! Expect a failure\n",
1012 (long)pthread_self(), chan->name, (long)chan->blocker, chan->blockproc);
1015 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE)) {
1017 ast_log(LOG_DEBUG, "Hanging up channel '%s'\n", chan->name);
1018 if (chan->tech->hangup)
1019 res = chan->tech->hangup(chan);
1022 ast_log(LOG_DEBUG, "Hanging up zombie '%s'\n", chan->name);
1024 ast_mutex_unlock(&chan->lock);
1025 manager_event(EVENT_FLAG_CALL, "Hangup",
1032 ast_channel_free(chan);
1036 int ast_answer(struct ast_channel *chan)
1039 ast_mutex_lock(&chan->lock);
1040 /* Stop if we're a zombie or need a soft hangup */
1041 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
1042 ast_mutex_unlock(&chan->lock);
1045 switch(chan->_state) {
1046 case AST_STATE_RINGING:
1047 case AST_STATE_RING:
1048 if (chan->tech->answer)
1049 res = chan->tech->answer(chan);
1050 ast_setstate(chan, AST_STATE_UP);
1052 ast_cdr_answer(chan->cdr);
1053 ast_mutex_unlock(&chan->lock);
1058 ast_cdr_answer(chan->cdr);
1061 ast_mutex_unlock(&chan->lock);
1067 void ast_deactivate_generator(struct ast_channel *chan)
1069 ast_mutex_lock(&chan->lock);
1070 if (chan->generatordata) {
1071 if (chan->generator && chan->generator->release)
1072 chan->generator->release(chan, chan->generatordata);
1073 chan->generatordata = NULL;
1074 chan->generator = NULL;
1075 ast_clear_flag(chan, AST_FLAG_WRITE_INT);
1076 ast_settimeout(chan, 0, NULL, NULL);
1078 ast_mutex_unlock(&chan->lock);
1081 static int generator_force(void *data)
1083 /* Called if generator doesn't have data */
1086 int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples);
1087 struct ast_channel *chan = data;
1088 tmp = chan->generatordata;
1089 chan->generatordata = NULL;
1090 generate = chan->generator->generate;
1091 res = generate(chan, tmp, 0, 160);
1092 chan->generatordata = tmp;
1094 ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
1095 ast_deactivate_generator(chan);
1100 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
1103 ast_mutex_lock(&chan->lock);
1104 if (chan->generatordata) {
1105 if (chan->generator && chan->generator->release)
1106 chan->generator->release(chan, chan->generatordata);
1107 chan->generatordata = NULL;
1110 if ((chan->generatordata = gen->alloc(chan, params))) {
1111 ast_settimeout(chan, 160, generator_force, chan);
1112 chan->generator = gen;
1116 ast_mutex_unlock(&chan->lock);
1120 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
1122 /* Wait for x amount of time on a file descriptor to have input. */
1123 struct timeval start = { 0 , 0 };
1128 struct pollfd *pfds;
1130 pfds = alloca(sizeof(struct pollfd) * n);
1132 ast_log(LOG_ERROR, "Out of memory\n");
1136 start = ast_tvnow();
1140 pfds[y].fd = fds[x];
1141 pfds[y].events = POLLIN | POLLPRI;
1145 res = poll(pfds, y, *ms);
1147 /* Simulate a timeout if we were interrupted */
1157 if ((res = ast_fdisset(pfds, fds[x], y, &spoint))) {
1169 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
1176 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
1177 int *exception, int *outfd, int *ms)
1179 /* Wait for x amount of time on a file descriptor to have input. */
1180 struct timeval start;
1181 struct pollfd *pfds;
1187 long whentohangup = 0, havewhen = 0, diff;
1188 struct ast_channel *winner = NULL;
1190 pfds = alloca(sizeof(struct pollfd) * (n * AST_MAX_FDS + nfds));
1192 ast_log(LOG_ERROR, "Out of memory\n");
1202 /* Perform any pending masquerades */
1204 ast_mutex_lock(&c[x]->lock);
1205 if (c[x]->whentohangup) {
1208 diff = c[x]->whentohangup - now;
1209 if (!havewhen || (diff < whentohangup)) {
1211 whentohangup = diff;
1215 if (ast_do_masquerade(c[x])) {
1216 ast_log(LOG_WARNING, "Masquerade failed\n");
1218 ast_mutex_unlock(&c[x]->lock);
1222 ast_mutex_unlock(&c[x]->lock);
1228 if ((*ms < 0) || (whentohangup * 1000 < *ms)) {
1229 rms = whentohangup * 1000;
1234 for (y=0;y<AST_MAX_FDS;y++) {
1235 if (c[x]->fds[y] > -1) {
1236 pfds[max].fd = c[x]->fds[y];
1237 pfds[max].events = POLLIN | POLLPRI;
1241 CHECK_BLOCKING(c[x]);
1243 for (x=0;x<nfds; x++) {
1245 pfds[max].fd = fds[x];
1246 pfds[max].events = POLLIN | POLLPRI;
1251 start = ast_tvnow();
1252 res = poll(pfds, max, rms);
1255 ast_clear_flag(c[x], AST_FLAG_BLOCKING);
1256 /* Simulate a timeout if we were interrupted */
1260 /* Just an interrupt */
1267 /* If no fds signalled, then timeout. So set ms = 0
1268 since we may not have an exact timeout.
1278 ast_clear_flag(c[x], AST_FLAG_BLOCKING);
1279 if (havewhen && c[x]->whentohangup && (now > c[x]->whentohangup)) {
1280 c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1284 for (y=0;y<AST_MAX_FDS;y++) {
1285 if (c[x]->fds[y] > -1) {
1286 if ((res = ast_fdisset(pfds, c[x]->fds[y], max, &spoint))) {
1288 ast_set_flag(c[x], AST_FLAG_EXCEPTION);
1290 ast_clear_flag(c[x], AST_FLAG_EXCEPTION);
1297 for (x=0;x<nfds;x++) {
1299 if ((res = ast_fdisset(pfds, fds[x], max, &spoint))) {
1313 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
1320 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
1322 return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
1325 int ast_waitfor(struct ast_channel *c, int ms)
1327 struct ast_channel *chan;
1329 chan = ast_waitfor_n(&c, 1, &ms);
1339 int ast_waitfordigit(struct ast_channel *c, int ms)
1341 /* XXX Should I be merged with waitfordigit_full XXX */
1342 struct ast_frame *f;
1344 /* Stop if we're a zombie or need a soft hangup */
1345 if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
1347 /* Wait for a digit, no more than ms milliseconds total. */
1348 while(ms && !result) {
1349 ms = ast_waitfor(c, ms);
1350 if (ms < 0) /* Error */
1353 /* Read something */
1356 if (f->frametype == AST_FRAME_DTMF)
1357 result = f->subclass;
1366 int ast_settimeout(struct ast_channel *c, int samples, int (*func)(void *data), void *data)
1369 #ifdef ZAPTEL_OPTIMIZATIONS
1370 if (c->timingfd > -1) {
1375 ast_log(LOG_DEBUG, "Scheduling timer at %d sample intervals\n", samples);
1376 res = ioctl(c->timingfd, ZT_TIMERCONFIG, &samples);
1377 c->timingfunc = func;
1378 c->timingdata = data;
1383 int ast_waitfordigit_full(struct ast_channel *c, int ms, int audiofd, int cmdfd)
1385 struct ast_frame *f;
1386 struct ast_channel *rchan;
1389 /* Stop if we're a zombie or need a soft hangup */
1390 if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
1392 /* Wait for a digit, no more than ms milliseconds total. */
1395 rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
1396 if ((!rchan) && (outfd < 0) && (ms)) {
1397 if (errno == 0 || errno == EINTR)
1399 ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
1401 } else if (outfd > -1) {
1402 /* The FD we were watching has something waiting */
1410 switch(f->frametype) {
1411 case AST_FRAME_DTMF:
1415 case AST_FRAME_CONTROL:
1416 switch(f->subclass) {
1417 case AST_CONTROL_HANGUP:
1420 case AST_CONTROL_RINGING:
1421 case AST_CONTROL_ANSWER:
1425 ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", f->subclass);
1427 case AST_FRAME_VOICE:
1428 /* Write audio if appropriate */
1430 write(audiofd, f->data, f->datalen);
1436 return 0; /* Time is up */
1439 struct ast_frame *ast_read(struct ast_channel *chan)
1441 struct ast_frame *f = NULL;
1444 #ifdef ZAPTEL_OPTIMIZATIONS
1445 int (*func)(void *);
1449 static struct ast_frame null_frame =
1454 ast_mutex_lock(&chan->lock);
1456 if (ast_do_masquerade(chan)) {
1457 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1461 ast_mutex_unlock(&chan->lock);
1465 /* Stop if we're a zombie or need a soft hangup */
1466 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
1467 if (chan->generator)
1468 ast_deactivate_generator(chan);
1469 ast_mutex_unlock(&chan->lock);
1472 prestate = chan->_state;
1474 if (!ast_test_flag(chan, AST_FLAG_DEFER_DTMF) && !ast_strlen_zero(chan->dtmfq)) {
1475 /* We have DTMF that has been deferred. Return it now */
1476 chan->dtmff.frametype = AST_FRAME_DTMF;
1477 chan->dtmff.subclass = chan->dtmfq[0];
1478 /* Drop first digit */
1479 memmove(chan->dtmfq, chan->dtmfq + 1, sizeof(chan->dtmfq) - 1);
1480 ast_mutex_unlock(&chan->lock);
1481 return &chan->dtmff;
1484 /* Read and ignore anything on the alertpipe, but read only
1485 one sizeof(blah) per frame that we send from it */
1486 if (chan->alertpipe[0] > -1) {
1487 read(chan->alertpipe[0], &blah, sizeof(blah));
1489 #ifdef ZAPTEL_OPTIMIZATIONS
1490 if ((chan->timingfd > -1) && (chan->fdno == AST_MAX_FDS - 2) && ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
1491 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
1493 /* IF we can't get event, assume it's an expired as-per the old interface */
1494 res = ioctl(chan->timingfd, ZT_GETEVENT, &blah);
1496 blah = ZT_EVENT_TIMER_EXPIRED;
1498 if (blah == ZT_EVENT_TIMER_PING) {
1500 ast_log(LOG_NOTICE, "Oooh, there's a PING!\n");
1502 if (!chan->readq || !chan->readq->next) {
1503 /* Acknowledge PONG unless we need it again */
1505 ast_log(LOG_NOTICE, "Sending a PONG!\n");
1507 if (ioctl(chan->timingfd, ZT_TIMERPONG, &blah)) {
1508 ast_log(LOG_WARNING, "Failed to pong timer on '%s': %s\n", chan->name, strerror(errno));
1511 } else if (blah == ZT_EVENT_TIMER_EXPIRED) {
1512 ioctl(chan->timingfd, ZT_TIMERACK, &blah);
1513 func = chan->timingfunc;
1514 data = chan->timingdata;
1515 ast_mutex_unlock(&chan->lock);
1518 ast_log(LOG_DEBUG, "Calling private function\n");
1523 ast_mutex_lock(&chan->lock);
1524 ioctl(chan->timingfd, ZT_TIMERCONFIG, &blah);
1525 chan->timingdata = NULL;
1526 ast_mutex_unlock(&chan->lock);
1531 ast_log(LOG_NOTICE, "No/unknown event '%d' on timer for '%s'?\n", blah, chan->name);
1534 /* Check for pending read queue */
1537 chan->readq = f->next;
1538 /* Interpret hangup and return NULL */
1539 if ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_HANGUP)) {
1544 chan->blocker = pthread_self();
1545 if (ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
1546 if (chan->tech->exception)
1547 f = chan->tech->exception(chan);
1549 ast_log(LOG_WARNING, "Exception flag set on '%s', but no exception handler\n", chan->name);
1552 /* Clear the exception flag */
1553 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
1555 if (chan->tech->read)
1556 f = chan->tech->read(chan);
1558 ast_log(LOG_WARNING, "No read routine on channel %s\n", chan->name);
1562 if (f && (f->frametype == AST_FRAME_VOICE)) {
1563 if (!(f->subclass & chan->nativeformats)) {
1564 /* This frame can't be from the current native formats -- drop it on the
1566 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));
1571 struct ast_channel_spy *spying;
1572 for (spying = chan->spiers; spying; spying=spying->next) {
1573 ast_queue_spy_frame(spying, f, 0);
1576 if (chan->monitor && chan->monitor->read_stream ) {
1577 #ifndef MONITOR_CONSTANT_DELAY
1578 int jump = chan->outsmpl - chan->insmpl - 2 * f->samples;
1580 if (ast_seekstream(chan->monitor->read_stream, jump + f->samples, SEEK_FORCECUR) == -1)
1581 ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
1582 chan->insmpl += jump + 2 * f->samples;
1584 chan->insmpl+= f->samples;
1586 int jump = chan->outsmpl - chan->insmpl;
1587 if (jump - MONITOR_DELAY >= 0) {
1588 if (ast_seekstream(chan->monitor->read_stream, jump - f->samples, SEEK_FORCECUR) == -1)
1589 ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
1590 chan->insmpl += jump;
1592 chan->insmpl += f->samples;
1594 if (ast_writestream(chan->monitor->read_stream, f) < 0)
1595 ast_log(LOG_WARNING, "Failed to write data to channel monitor read stream\n");
1597 if (chan->readtrans) {
1598 f = ast_translate(chan->readtrans, f, 1);
1605 /* Make sure we always return NULL in the future */
1607 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1608 if (chan->generator)
1609 ast_deactivate_generator(chan);
1610 /* End the CDR if appropriate */
1612 ast_cdr_end(chan->cdr);
1613 } else if (ast_test_flag(chan, AST_FLAG_DEFER_DTMF) && f->frametype == AST_FRAME_DTMF) {
1614 if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2)
1615 chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
1617 ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
1619 } else if ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_ANSWER)) {
1620 if (prestate == AST_STATE_UP) {
1621 ast_log(LOG_DEBUG, "Dropping duplicate answer!\n");
1624 /* Answer the CDR */
1625 ast_setstate(chan, AST_STATE_UP);
1626 ast_cdr_answer(chan->cdr);
1629 /* Run any generator sitting on the line */
1630 if (f && (f->frametype == AST_FRAME_VOICE) && chan->generatordata) {
1631 /* Mask generator data temporarily and apply. If there is a timing function, it
1632 will be calling the generator instead */
1635 int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples);
1636 if (chan->timingfunc) {
1637 ast_log(LOG_DEBUG, "Generator got voice, switching to phase locked mode\n");
1638 ast_settimeout(chan, 0, NULL, NULL);
1640 tmp = chan->generatordata;
1641 chan->generatordata = NULL;
1642 generate = chan->generator->generate;
1643 res = generate(chan, tmp, f->datalen, f->samples);
1644 chan->generatordata = tmp;
1646 ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
1647 ast_deactivate_generator(chan);
1649 } else if (f && (f->frametype == AST_FRAME_CNG)) {
1650 if (chan->generator && !chan->timingfunc && (chan->timingfd > -1)) {
1651 ast_log(LOG_DEBUG, "Generator got CNG, switching to zap timed mode\n");
1652 ast_settimeout(chan, 160, generator_force, chan);
1655 /* High bit prints debugging */
1656 if (chan->fin & 0x80000000)
1657 ast_frame_dump(chan->name, f, "<<");
1658 if ((chan->fin & 0x7fffffff) == 0x7fffffff)
1659 chan->fin &= 0x80000000;
1662 ast_mutex_unlock(&chan->lock);
1666 int ast_indicate(struct ast_channel *chan, int condition)
1669 /* Stop if we're a zombie or need a soft hangup */
1670 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
1672 ast_mutex_lock(&chan->lock);
1673 if (chan->tech->indicate)
1674 res = chan->tech->indicate(chan, condition);
1675 ast_mutex_unlock(&chan->lock);
1676 if (!chan->tech->indicate || res) {
1678 * Device does not support (that) indication, lets fake
1679 * it by doing our own tone generation. (PM2002)
1681 if (condition >= 0) {
1682 const struct tone_zone_sound *ts = NULL;
1683 switch (condition) {
1684 case AST_CONTROL_RINGING:
1685 ts = ast_get_indication_tone(chan->zone, "ring");
1687 case AST_CONTROL_BUSY:
1688 ts = ast_get_indication_tone(chan->zone, "busy");
1690 case AST_CONTROL_CONGESTION:
1691 ts = ast_get_indication_tone(chan->zone, "congestion");
1694 if (ts && ts->data[0]) {
1695 ast_log(LOG_DEBUG, "Driver for channel '%s' does not support indication %d, emulating it\n", chan->name, condition);
1696 ast_playtones_start(chan,0,ts->data, 1);
1698 } else if (condition == AST_CONTROL_PROGRESS) {
1699 /* ast_playtones_stop(chan); */
1700 } else if (condition == AST_CONTROL_PROCEEDING) {
1701 /* Do nothing, really */
1702 } else if (condition == AST_CONTROL_HOLD) {
1703 /* Do nothing.... */
1704 } else if (condition == AST_CONTROL_UNHOLD) {
1705 /* Do nothing.... */
1708 ast_log(LOG_WARNING, "Unable to handle indication %d for '%s'\n", condition, chan->name);
1712 else ast_playtones_stop(chan);
1717 int ast_recvchar(struct ast_channel *chan, int timeout)
1720 char *buf = ast_recvtext(chan, timeout);
1722 return -1; /* error or timeout */
1723 c = *(unsigned char *)buf;
1728 char *ast_recvtext(struct ast_channel *chan, int timeout)
1734 struct ast_frame *f;
1735 if (ast_check_hangup(chan))
1737 res = ast_waitfor(chan, timeout);
1738 if (res <= 0) /* timeout or error */
1740 timeout = res; /* update timeout */
1743 break; /* no frame */
1744 if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP)
1745 done = 1; /* force a break */
1746 else if (f->frametype == AST_FRAME_TEXT) { /* what we want */
1747 buf = strndup((char *) f->data, f->datalen); /* dup and break */
1755 int ast_sendtext(struct ast_channel *chan, char *text)
1758 /* Stop if we're a zombie or need a soft hangup */
1759 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
1761 CHECK_BLOCKING(chan);
1762 if (chan->tech->send_text)
1763 res = chan->tech->send_text(chan, text);
1764 ast_clear_flag(chan, AST_FLAG_BLOCKING);
1768 static int do_senddigit(struct ast_channel *chan, char digit)
1772 if (chan->tech->send_digit)
1773 res = chan->tech->send_digit(chan, digit);
1774 if (!chan->tech->send_digit || res) {
1776 * Device does not support DTMF tones, lets fake
1777 * it by doing our own generation. (PM2002)
1779 static const char* dtmf_tones[] = {
1780 "!941+1336/100,!0/100", /* 0 */
1781 "!697+1209/100,!0/100", /* 1 */
1782 "!697+1336/100,!0/100", /* 2 */
1783 "!697+1477/100,!0/100", /* 3 */
1784 "!770+1209/100,!0/100", /* 4 */
1785 "!770+1336/100,!0/100", /* 5 */
1786 "!770+1477/100,!0/100", /* 6 */
1787 "!852+1209/100,!0/100", /* 7 */
1788 "!852+1336/100,!0/100", /* 8 */
1789 "!852+1477/100,!0/100", /* 9 */
1790 "!697+1633/100,!0/100", /* A */
1791 "!770+1633/100,!0/100", /* B */
1792 "!852+1633/100,!0/100", /* C */
1793 "!941+1633/100,!0/100", /* D */
1794 "!941+1209/100,!0/100", /* * */
1795 "!941+1477/100,!0/100" }; /* # */
1796 if (digit >= '0' && digit <='9')
1797 ast_playtones_start(chan,0,dtmf_tones[digit-'0'], 0);
1798 else if (digit >= 'A' && digit <= 'D')
1799 ast_playtones_start(chan,0,dtmf_tones[digit-'A'+10], 0);
1800 else if (digit == '*')
1801 ast_playtones_start(chan,0,dtmf_tones[14], 0);
1802 else if (digit == '#')
1803 ast_playtones_start(chan,0,dtmf_tones[15], 0);
1806 ast_log(LOG_DEBUG, "Unable to handle DTMF tone '%c' for '%s'\n", digit, chan->name);
1812 int ast_senddigit(struct ast_channel *chan, char digit)
1814 return do_senddigit(chan, digit);
1817 int ast_prod(struct ast_channel *chan)
1819 struct ast_frame a = { AST_FRAME_VOICE };
1821 /* Send an empty audio frame to get things moving */
1822 if (chan->_state != AST_STATE_UP) {
1823 ast_log(LOG_DEBUG, "Prodding channel '%s'\n", chan->name);
1824 a.subclass = chan->rawwriteformat;
1825 a.data = nothing + AST_FRIENDLY_OFFSET;
1827 if (ast_write(chan, &a))
1828 ast_log(LOG_WARNING, "Prodding channel '%s' failed\n", chan->name);
1833 int ast_write_video(struct ast_channel *chan, struct ast_frame *fr)
1836 if (!chan->tech->write_video)
1838 res = ast_write(chan, fr);
1844 int ast_write(struct ast_channel *chan, struct ast_frame *fr)
1847 struct ast_frame *f = NULL;
1848 /* Stop if we're a zombie or need a soft hangup */
1849 ast_mutex_lock(&chan->lock);
1850 if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
1851 ast_mutex_unlock(&chan->lock);
1854 /* Handle any pending masquerades */
1856 if (ast_do_masquerade(chan)) {
1857 ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1858 ast_mutex_unlock(&chan->lock);
1863 ast_mutex_unlock(&chan->lock);
1866 if (chan->generatordata) {
1867 if (ast_test_flag(chan, AST_FLAG_WRITE_INT))
1868 ast_deactivate_generator(chan);
1870 ast_mutex_unlock(&chan->lock);
1874 /* High bit prints debugging */
1875 if (chan->fout & 0x80000000)
1876 ast_frame_dump(chan->name, fr, ">>");
1877 CHECK_BLOCKING(chan);
1878 switch(fr->frametype) {
1879 case AST_FRAME_CONTROL:
1880 /* XXX Interpret control frames XXX */
1881 ast_log(LOG_WARNING, "Don't know how to handle control frames yet\n");
1883 case AST_FRAME_DTMF:
1884 ast_clear_flag(chan, AST_FLAG_BLOCKING);
1885 ast_mutex_unlock(&chan->lock);
1886 res = do_senddigit(chan,fr->subclass);
1887 ast_mutex_lock(&chan->lock);
1888 CHECK_BLOCKING(chan);
1890 case AST_FRAME_TEXT:
1891 if (chan->tech->send_text)
1892 res = chan->tech->send_text(chan, (char *) fr->data);
1896 case AST_FRAME_HTML:
1897 if (chan->tech->send_html)
1898 res = chan->tech->send_html(chan, fr->subclass, (char *) fr->data, fr->datalen);
1902 case AST_FRAME_VIDEO:
1903 /* XXX Handle translation of video codecs one day XXX */
1904 if (chan->tech->write_video)
1905 res = chan->tech->write_video(chan, fr);
1910 if (chan->tech->write) {
1911 if (chan->writetrans) {
1912 f = ast_translate(chan->writetrans, fr, 0);
1916 if (f->frametype == AST_FRAME_VOICE && chan->spiers) {
1917 struct ast_channel_spy *spying;
1918 for (spying = chan->spiers; spying; spying=spying->next) {
1919 ast_queue_spy_frame(spying, f, 1);
1923 if( chan->monitor &&
1924 chan->monitor->write_stream &&
1925 f && ( f->frametype == AST_FRAME_VOICE ) ) {
1926 #ifndef MONITOR_CONSTANT_DELAY
1927 int jump = chan->insmpl - chan->outsmpl - 2 * f->samples;
1929 if (ast_seekstream(chan->monitor->write_stream, jump + f->samples, SEEK_FORCECUR) == -1)
1930 ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
1931 chan->outsmpl += jump + 2 * f->samples;
1933 chan->outsmpl += f->samples;
1935 int jump = chan->insmpl - chan->outsmpl;
1936 if (jump - MONITOR_DELAY >= 0) {
1937 if (ast_seekstream(chan->monitor->write_stream, jump - f->samples, SEEK_FORCECUR) == -1)
1938 ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
1939 chan->outsmpl += jump;
1941 chan->outsmpl += f->samples;
1943 if (ast_writestream(chan->monitor->write_stream, f) < 0)
1944 ast_log(LOG_WARNING, "Failed to write data to channel monitor write stream\n");
1947 res = chan->tech->write(chan, f);
1954 ast_clear_flag(chan, AST_FLAG_BLOCKING);
1955 /* Consider a write failure to force a soft hangup */
1957 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1959 if ((chan->fout & 0x7fffffff) == 0x7fffffff)
1960 chan->fout &= 0x80000000;
1964 ast_mutex_unlock(&chan->lock);
1968 static int set_format(struct ast_channel *chan, int fmt, int *rawformat, int *format,
1969 struct ast_trans_pvt **trans, const int direction)
1974 native = chan->nativeformats;
1975 /* Find a translation path from the native format to one of the desired formats */
1978 res = ast_translator_best_choice(&fmt, &native);
1981 res = ast_translator_best_choice(&native, &fmt);
1984 ast_log(LOG_NOTICE, "Unable to find a path from %s to %s\n",
1985 ast_getformatname(native), ast_getformatname(fmt));
1989 /* Now we have a good choice for both. */
1990 ast_mutex_lock(&chan->lock);
1991 *rawformat = native;
1992 /* User perspective is fmt */
1994 /* Free any read translation we have right now */
1996 ast_translator_free_path(*trans);
1997 /* Build a translation path from the raw format to the desired format */
2000 *trans = ast_translator_build_path(*format, *rawformat);
2003 *trans = ast_translator_build_path(*rawformat, *format);
2004 ast_mutex_unlock(&chan->lock);
2006 ast_log(LOG_DEBUG, "Set channel %s to %s format %s\n", chan->name,
2007 direction ? "write" : "read", ast_getformatname(fmt));
2011 int ast_set_read_format(struct ast_channel *chan, int fmt)
2013 return set_format(chan, fmt, &chan->rawreadformat, &chan->readformat,
2014 &chan->readtrans, 0);
2017 int ast_set_write_format(struct ast_channel *chan, int fmt)
2019 return set_format(chan, fmt, &chan->rawwriteformat, &chan->writeformat,
2020 &chan->writetrans, 1);
2023 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)
2027 struct ast_channel *chan;
2028 struct ast_frame *f;
2031 chan = ast_request(type, format, data, &cause);
2034 ast_set_variables(chan, oh->vars);
2035 ast_set_callerid(chan, oh->cid_num, oh->cid_name, oh->cid_num);
2037 ast_set_callerid(chan, cid_num, cid_name, cid_num);
2039 if (!ast_call(chan, data, 0)) {
2040 while(timeout && (chan->_state != AST_STATE_UP)) {
2041 res = ast_waitfor(chan, timeout);
2043 /* Something not cool, or timed out */
2046 /* If done, break out */
2053 state = AST_CONTROL_HANGUP;
2057 if (f->frametype == AST_FRAME_CONTROL) {
2058 if (f->subclass == AST_CONTROL_RINGING)
2059 state = AST_CONTROL_RINGING;
2060 else if ((f->subclass == AST_CONTROL_BUSY) || (f->subclass == AST_CONTROL_CONGESTION)) {
2061 state = f->subclass;
2064 } else if (f->subclass == AST_CONTROL_ANSWER) {
2065 state = f->subclass;
2068 } else if (f->subclass == AST_CONTROL_PROGRESS) {
2070 } else if (f->subclass == -1) {
2071 /* Ignore -- just stopping indications */
2073 ast_log(LOG_NOTICE, "Don't know what to do with control frame %d\n", f->subclass);
2079 ast_log(LOG_NOTICE, "Unable to call channel %s/%s\n", type, (char *)data);
2081 ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
2083 case AST_CAUSE_BUSY:
2084 state = AST_CONTROL_BUSY;
2086 case AST_CAUSE_CONGESTION:
2087 state = AST_CONTROL_CONGESTION;
2094 if (oh->context && *oh->context)
2095 ast_copy_string(chan->context, oh->context, sizeof(chan->context));
2096 if (oh->exten && *oh->exten)
2097 ast_copy_string(chan->exten, oh->exten, sizeof(chan->exten));
2099 chan->priority = oh->priority;
2101 if (chan->_state == AST_STATE_UP)
2102 state = AST_CONTROL_ANSWER;
2106 if (chan && res <= 0) {
2108 chan->cdr = ast_cdr_alloc();
2110 ast_cdr_init(chan->cdr, chan);
2114 snprintf(tmp, 256, "%s/%s", type, (char *)data);
2115 ast_cdr_setapp(chan->cdr,"Dial",tmp);
2116 ast_cdr_update(chan);
2117 ast_cdr_start(chan->cdr);
2118 ast_cdr_end(chan->cdr);
2119 /* If the cause wasn't handled properly */
2120 if (ast_cdr_disposition(chan->cdr,chan->hangupcause))
2121 ast_cdr_failed(chan->cdr);
2123 ast_log(LOG_WARNING, "Unable to create Call Detail Record\n");
2130 struct ast_channel *ast_request_and_dial(const char *type, int format, void *data, int timeout, int *outstate, const char *cidnum, const char *cidname)
2132 return __ast_request_and_dial(type, format, data, timeout, outstate, cidnum, cidname, NULL);
2135 struct ast_channel *ast_request(const char *type, int format, void *data, int *cause)
2137 struct chanlist *chan;
2138 struct ast_channel *c = NULL;
2145 *cause = AST_CAUSE_NOTDEFINED;
2146 if (ast_mutex_lock(&chlock)) {
2147 ast_log(LOG_WARNING, "Unable to lock channel list\n");
2152 if (!strcasecmp(type, chan->tech->type)) {
2153 capabilities = chan->tech->capabilities;
2155 res = ast_translator_best_choice(&fmt, &capabilities);
2157 ast_log(LOG_WARNING, "No translator path exists for channel type %s (native %d) to %d\n", type, chan->tech->capabilities, format);
2158 ast_mutex_unlock(&chlock);
2161 ast_mutex_unlock(&chlock);
2162 if (chan->tech->requester)
2163 c = chan->tech->requester(type, capabilities, data, cause);
2165 if (c->_state == AST_STATE_DOWN) {
2166 manager_event(EVENT_FLAG_CALL, "Newchannel",
2170 "CallerIDName: %s\r\n"
2172 c->name, ast_state2str(c->_state), c->cid.cid_num ? c->cid.cid_num : "<unknown>", c->cid.cid_name ? c->cid.cid_name : "<unknown>",c->uniqueid);
2180 ast_log(LOG_WARNING, "No channel type registered for '%s'\n", type);
2181 *cause = AST_CAUSE_NOSUCHDRIVER;
2183 ast_mutex_unlock(&chlock);
2187 int ast_call(struct ast_channel *chan, char *addr, int timeout)
2189 /* Place an outgoing call, but don't wait any longer than timeout ms before returning.
2190 If the remote end does not answer within the timeout, then do NOT hang up, but
2193 /* Stop if we're a zombie or need a soft hangup */
2194 ast_mutex_lock(&chan->lock);
2195 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan))
2196 if (chan->tech->call)
2197 res = chan->tech->call(chan, addr, timeout);
2198 ast_mutex_unlock(&chan->lock);
2202 int ast_transfer(struct ast_channel *chan, char *dest)
2204 /* Place an outgoing call, but don't wait any longer than timeout ms before returning.
2205 If the remote end does not answer within the timeout, then do NOT hang up, but
2208 /* Stop if we're a zombie or need a soft hangup */
2209 ast_mutex_lock(&chan->lock);
2210 if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
2211 if (chan->tech->transfer) {
2212 res = chan->tech->transfer(chan, dest);
2218 ast_mutex_unlock(&chan->lock);
2222 int ast_readstring(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders)
2227 /* XXX Merge with full version? XXX */
2228 /* Stop if we're a zombie or need a soft hangup */
2229 if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
2235 d = ast_waitstream(c, AST_DIGIT_ANY);
2239 d = ast_waitfordigit(c, to);
2241 d = ast_waitfordigit(c, to);
2249 if (!strchr(enders, d))
2251 if (strchr(enders, d) || (pos >= len)) {
2261 int ast_readstring_full(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders, int audiofd, int ctrlfd)
2266 /* Stop if we're a zombie or need a soft hangup */
2267 if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
2273 d = ast_waitstream_full(c, AST_DIGIT_ANY, audiofd, ctrlfd);
2277 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
2279 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
2291 if (!strchr(enders, d))
2293 if (strchr(enders, d) || (pos >= len)) {
2303 int ast_channel_supports_html(struct ast_channel *chan)
2305 if (chan->tech->send_html)
2310 int ast_channel_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
2312 if (chan->tech->send_html)
2313 return chan->tech->send_html(chan, subclass, data, datalen);
2317 int ast_channel_sendurl(struct ast_channel *chan, const char *url)
2319 if (chan->tech->send_html)
2320 return chan->tech->send_html(chan, AST_HTML_URL, url, strlen(url) + 1);
2324 int ast_channel_make_compatible(struct ast_channel *chan, struct ast_channel *peer)
2329 /* Set up translation from the chan to the peer */
2330 src = chan->nativeformats;
2331 dst = peer->nativeformats;
2332 if (ast_translator_best_choice(&dst, &src) < 0) {
2333 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", chan->name, src, peer->name, dst);
2336 /* if the best path is not 'pass through', then
2337 transcoding is needed; if desired, force transcode path
2338 to use SLINEAR between channels */
2339 if ((src != dst) && option_transcode_slin)
2340 dst = AST_FORMAT_SLINEAR;
2341 if (ast_set_read_format(chan, dst) < 0) {
2342 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", chan->name, dst);
2345 if (ast_set_write_format(peer, dst) < 0) {
2346 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", peer->name, dst);
2350 /* Set up translation from the peer to the chan */
2351 src = peer->nativeformats;
2352 dst = chan->nativeformats;
2353 if (ast_translator_best_choice(&dst, &src) < 0) {
2354 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", peer->name, src, chan->name, dst);
2357 /* if the best path is not 'pass through', then
2358 transcoding is needed; if desired, force transcode path
2359 to use SLINEAR between channels */
2360 if ((src != dst) && option_transcode_slin)
2361 dst = AST_FORMAT_SLINEAR;
2362 if (ast_set_read_format(peer, dst) < 0) {
2363 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", peer->name, dst);
2366 if (ast_set_write_format(chan, dst) < 0) {
2367 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", chan->name, dst);
2373 int ast_channel_masquerade(struct ast_channel *original, struct ast_channel *clone)
2375 struct ast_frame null = { AST_FRAME_NULL, };
2377 if (original == clone) {
2378 ast_log(LOG_WARNING, "Can't masquerade channel '%s' into itself!\n", original->name);
2381 ast_mutex_lock(&original->lock);
2382 while(ast_mutex_trylock(&clone->lock)) {
2383 ast_mutex_unlock(&original->lock);
2385 ast_mutex_lock(&original->lock);
2387 ast_log(LOG_DEBUG, "Planning to masquerade %s into the structure of %s\n",
2388 clone->name, original->name);
2389 if (original->masq) {
2390 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n",
2391 original->masq->name, original->name);
2392 } else if (clone->masqr) {
2393 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n",
2394 clone->name, clone->masqr->name);
2396 original->masq = clone;
2397 clone->masqr = original;
2398 ast_queue_frame(original, &null);
2399 ast_queue_frame(clone, &null);
2400 ast_log(LOG_DEBUG, "Done planning to masquerade %s into the structure of %s\n", original->name, clone->name);
2403 ast_mutex_unlock(&clone->lock);
2404 ast_mutex_unlock(&original->lock);
2408 void ast_change_name(struct ast_channel *chan, char *newname)
2411 ast_copy_string(tmp, chan->name, sizeof(tmp));
2412 ast_copy_string(chan->name, newname, sizeof(chan->name));
2413 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", tmp, chan->name, chan->uniqueid);
2416 void ast_channel_inherit_variables(const struct ast_channel *parent, struct ast_channel *child)
2418 struct ast_var_t *current, *newvar;
2421 AST_LIST_TRAVERSE(&parent->varshead, current, entries) {
2424 varname = ast_var_full_name(current);
2428 if (varname[0] == '_') {
2430 if (varname[1] == '_')
2436 newvar = ast_var_assign(&varname[1], ast_var_value(current));
2438 AST_LIST_INSERT_HEAD(&child->varshead, newvar, entries);
2440 ast_log(LOG_DEBUG, "Copying soft-transferable variable %s.\n", ast_var_name(newvar));
2444 newvar = ast_var_assign(ast_var_full_name(current), ast_var_value(current));
2446 AST_LIST_INSERT_HEAD(&child->varshead, newvar, entries);
2448 ast_log(LOG_DEBUG, "Copying hard-transferable variable %s.\n", ast_var_name(newvar));
2453 ast_log(LOG_DEBUG, "Not copying variable %s.\n", ast_var_name(current));
2459 /* Clone channel variables from 'clone' channel into 'original' channel
2460 All variables except those related to app_groupcount are cloned
2461 Variables are actually _removed_ from 'clone' channel, presumably
2462 because it will subsequently be destroyed.
2463 Assumes locks will be in place on both channels when called.
2466 static void clone_variables(struct ast_channel *original, struct ast_channel *clone)
2468 struct ast_var_t *varptr;
2470 /* we need to remove all app_groupcount related variables from the original
2471 channel before merging in the clone's variables; any groups assigned to the
2472 original channel should be released, only those assigned to the clone
2476 AST_LIST_TRAVERSE_SAFE_BEGIN(&original->varshead, varptr, entries) {
2477 if (!strncmp(ast_var_name(varptr), GROUP_CATEGORY_PREFIX, strlen(GROUP_CATEGORY_PREFIX))) {
2478 AST_LIST_REMOVE(&original->varshead, varptr, entries);
2479 ast_var_delete(varptr);
2482 AST_LIST_TRAVERSE_SAFE_END;
2484 /* Append variables from clone channel into original channel */
2485 /* XXX Is this always correct? We have to in order to keep MACROS working XXX */
2486 if (AST_LIST_FIRST(&clone->varshead))
2487 AST_LIST_INSERT_TAIL(&original->varshead, AST_LIST_FIRST(&clone->varshead), entries);
2490 /* Assumes channel will be locked when called */
2491 int ast_do_masquerade(struct ast_channel *original)
2496 struct ast_frame *cur, *prev;
2497 const struct ast_channel_tech *t;
2499 struct ast_callerid tmpcid;
2500 struct ast_channel *clone = original->masq;
2501 int rformat = original->readformat;
2502 int wformat = original->writeformat;
2509 ast_log(LOG_DEBUG, "Actually Masquerading %s(%d) into the structure of %s(%d)\n",
2510 clone->name, clone->_state, original->name, original->_state);
2512 /* XXX This is a seriously wacked out operation. We're essentially putting the guts of
2513 the clone channel into the original channel. Start by killing off the original
2514 channel's backend. I'm not sure we're going to keep this function, because
2515 while the features are nice, the cost is very high in terms of pure nastiness. XXX */
2517 /* We need the clone's lock, too */
2518 ast_mutex_lock(&clone->lock);
2520 ast_log(LOG_DEBUG, "Got clone lock on '%s' at %p\n", clone->name, &clone->lock);
2522 /* Having remembered the original read/write formats, we turn off any translation on either
2524 free_translation(clone);
2525 free_translation(original);
2528 /* Unlink the masquerade */
2529 original->masq = NULL;
2530 clone->masqr = NULL;
2532 /* Save the original name */
2533 ast_copy_string(orig, original->name, sizeof(orig));
2534 /* Save the new name */
2535 ast_copy_string(newn, clone->name, sizeof(newn));
2536 /* Create the masq name */
2537 snprintf(masqn, sizeof(masqn), "%s<MASQ>", newn);
2539 /* Copy the name from the clone channel */
2540 ast_copy_string(original->name, newn, sizeof(original->name));
2542 /* Mangle the name of the clone channel */
2543 ast_copy_string(clone->name, masqn, sizeof(clone->name));
2545 /* Notify any managers of the change, first the masq then the other */
2546 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", newn, masqn, clone->uniqueid);
2547 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", orig, newn, original->uniqueid);
2549 /* Swap the technlogies */
2551 original->tech = clone->tech;
2554 t_pvt = original->tech_pvt;
2555 original->tech_pvt = clone->tech_pvt;
2556 clone->tech_pvt = t_pvt;
2558 /* Swap the readq's */
2559 cur = original->readq;
2560 original->readq = clone->readq;
2563 /* Swap the alertpipes */
2564 for (i = 0; i < 2; i++) {
2565 x = original->alertpipe[i];
2566 original->alertpipe[i] = clone->alertpipe[i];
2567 clone->alertpipe[i] = x;
2570 /* Swap the raw formats */
2571 x = original->rawreadformat;
2572 original->rawreadformat = clone->rawreadformat;
2573 clone->rawreadformat = x;
2574 x = original->rawwriteformat;
2575 original->rawwriteformat = clone->rawwriteformat;
2576 clone->rawwriteformat = x;
2578 /* Save any pending frames on both sides. Start by counting
2579 * how many we're going to need... */
2588 /* If we had any, prepend them to the ones already in the queue, and
2589 * load up the alertpipe */
2591 prev->next = original->readq;
2592 original->readq = clone->readq;
2593 clone->readq = NULL;
2594 if (original->alertpipe[1] > -1) {
2596 write(original->alertpipe[1], &x, sizeof(x));
2599 clone->_softhangup = AST_SOFTHANGUP_DEV;
2602 /* And of course, so does our current state. Note we need not
2603 call ast_setstate since the event manager doesn't really consider
2604 these separate. We do this early so that the clone has the proper
2605 state of the original channel. */
2606 origstate = original->_state;
2607 original->_state = clone->_state;
2608 clone->_state = origstate;
2610 if (clone->tech->fixup){
2611 res = clone->tech->fixup(original, clone);
2613 ast_log(LOG_WARNING, "Fixup failed on channel %s, strange things may happen.\n", clone->name);
2616 /* Start by disconnecting the original's physical side */
2617 if (clone->tech->hangup)
2618 res = clone->tech->hangup(clone);
2620 ast_log(LOG_WARNING, "Hangup failed! Strange things may happen!\n");
2621 ast_mutex_unlock(&clone->lock);
2625 snprintf(zombn, sizeof(zombn), "%s<ZOMBIE>", orig);
2626 /* Mangle the name of the clone channel */
2627 ast_copy_string(clone->name, zombn, sizeof(clone->name));
2628 manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", masqn, zombn, clone->uniqueid);
2630 /* Update the type. */
2631 original->type = clone->type;
2633 /* Keep the same language. */
2634 ast_copy_string(original->language, clone->language, sizeof(original->language));
2636 for (x=0;x<AST_MAX_FDS;x++) {
2637 original->fds[x] = clone->fds[x];
2639 clone_variables(original, clone);
2640 clone->varshead.first = NULL;
2641 /* Presense of ADSI capable CPE follows clone */
2642 original->adsicpe = clone->adsicpe;
2643 /* Bridge remains the same */
2644 /* CDR fields remain the same */
2645 /* XXX What about blocking, softhangup, blocker, and lock and blockproc? XXX */
2646 /* Application and data remain the same */
2647 /* Clone exception becomes real one, as with fdno */
2648 ast_copy_flags(original, clone, AST_FLAG_EXCEPTION);
2649 original->fdno = clone->fdno;
2650 /* Schedule context remains the same */
2651 /* Stream stuff stays the same */
2652 /* Keep the original state. The fixup code will need to work with it most likely */
2654 /* Just swap the whole structures, nevermind the allocations, they'll work themselves
2656 tmpcid = original->cid;
2657 original->cid = clone->cid;
2658 clone->cid = tmpcid;
2660 /* Restore original timing file descriptor */
2661 original->fds[AST_MAX_FDS - 2] = original->timingfd;
2663 /* Our native formats are different now */
2664 original->nativeformats = clone->nativeformats;
2666 /* Context, extension, priority, app data, jump table, remain the same */
2667 /* pvt switches. pbx stays the same, as does next */
2669 /* Set the write format */
2670 ast_set_write_format(original, wformat);
2672 /* Set the read format */
2673 ast_set_read_format(original, rformat);
2675 /* Copy the music class */
2676 ast_copy_string(original->musicclass, clone->musicclass, sizeof(original->musicclass));
2678 ast_log(LOG_DEBUG, "Putting channel %s in %d/%d formats\n", original->name, wformat, rformat);
2680 /* Okay. Last thing is to let the channel driver know about all this mess, so he
2681 can fix up everything as best as possible */
2682 if (original->tech->fixup) {
2683 res = original->tech->fixup(clone, original);
2685 ast_log(LOG_WARNING, "Driver for '%s' could not fixup channel %s\n",
2686 original->type, original->name);
2687 ast_mutex_unlock(&clone->lock);
2691 ast_log(LOG_WARNING, "Driver '%s' does not have a fixup routine (for %s)! Bad things may happen.\n",
2692 original->type, original->name);
2694 /* Now, at this point, the "clone" channel is totally F'd up. We mark it as
2695 a zombie so nothing tries to touch it. If it's already been marked as a
2696 zombie, then free it now (since it already is considered invalid). */
2697 if (ast_test_flag(clone, AST_FLAG_ZOMBIE)) {
2698 ast_log(LOG_DEBUG, "Destroying clone '%s'\n", clone->name);
2699 ast_mutex_unlock(&clone->lock);
2700 ast_channel_free(clone);
2701 manager_event(EVENT_FLAG_CALL, "Hangup", "Channel: %s\r\n", zombn);
2703 struct ast_frame null_frame = { AST_FRAME_NULL, };
2704 ast_log(LOG_DEBUG, "Released clone lock on '%s'\n", clone->name);
2705 ast_set_flag(clone, AST_FLAG_ZOMBIE);
2706 ast_queue_frame(clone, &null_frame);
2707 ast_mutex_unlock(&clone->lock);
2710 /* Signal any blocker */
2711 if (ast_test_flag(original, AST_FLAG_BLOCKING))
2712 pthread_kill(original->blocker, SIGURG);
2713 ast_log(LOG_DEBUG, "Done Masquerading %s (%d)\n",
2714 original->name, original->_state);
2718 void ast_set_callerid(struct ast_channel *chan, const char *callerid, const char *calleridname, const char *ani)
2721 if (chan->cid.cid_num)
2722 free(chan->cid.cid_num);
2723 if (ast_strlen_zero(callerid))
2724 chan->cid.cid_num = NULL;
2726 chan->cid.cid_num = strdup(callerid);
2729 if (chan->cid.cid_name)
2730 free(chan->cid.cid_name);
2731 if (ast_strlen_zero(calleridname))
2732 chan->cid.cid_name = NULL;
2734 chan->cid.cid_name = strdup(calleridname);
2737 if (chan->cid.cid_ani)
2738 free(chan->cid.cid_ani);
2739 if (ast_strlen_zero(ani))
2740 chan->cid.cid_ani = NULL;
2742 chan->cid.cid_ani = strdup(ani);
2745 ast_cdr_setcid(chan->cdr, chan);
2746 manager_event(EVENT_FLAG_CALL, "Newcallerid",
2749 "CallerIDName: %s\r\n"
2751 chan->name, chan->cid.cid_num ?
2752 chan->cid.cid_num : "<Unknown>",
2753 chan->cid.cid_name ?
2754 chan->cid.cid_name : "<Unknown>",
2758 int ast_setstate(struct ast_channel *chan, int state)
2760 if (chan->_state != state) {
2761 int oldstate = chan->_state;
2762 chan->_state = state;
2763 if (oldstate == AST_STATE_DOWN) {
2764 ast_device_state_changed(chan->name);
2765 manager_event(EVENT_FLAG_CALL, "Newchannel",
2769 "CallerIDName: %s\r\n"
2771 chan->name, ast_state2str(chan->_state),
2772 chan->cid.cid_num ? chan->cid.cid_num : "<unknown>",
2773 chan->cid.cid_name ? chan->cid.cid_name : "<unknown>",
2776 manager_event(EVENT_FLAG_CALL, "Newstate",
2780 "CallerIDName: %s\r\n"
2782 chan->name, ast_state2str(chan->_state),
2783 chan->cid.cid_num ? chan->cid.cid_num : "<unknown>",
2784 chan->cid.cid_name ? chan->cid.cid_name : "<unknown>",
2791 /*--- Find bridged channel */
2792 struct ast_channel *ast_bridged_channel(struct ast_channel *chan)
2794 struct ast_channel *bridged;
2795 bridged = chan->_bridge;
2796 if (bridged && bridged->tech->bridged_channel)
2797 bridged = bridged->tech->bridged_channel(chan, bridged);
2801 static void bridge_playfile(struct ast_channel *chan, struct ast_channel *peer, char *sound, int remain)
2803 int res=0, min=0, sec=0,check=0;
2805 check = ast_autoservice_start(peer);
2810 if (remain / 60 > 1) {
2818 if (!strcmp(sound,"timeleft")) { /* Queue support */
2819 res = ast_streamfile(chan, "vm-youhave", chan->language);
2820 res = ast_waitstream(chan, "");
2822 res = ast_say_number(chan, min, AST_DIGIT_ANY, chan->language, (char *) NULL);
2823 res = ast_streamfile(chan, "queue-minutes", chan->language);
2824 res = ast_waitstream(chan, "");
2827 res = ast_say_number(chan, sec, AST_DIGIT_ANY, chan->language, (char *) NULL);
2828 res = ast_streamfile(chan, "queue-seconds", chan->language);
2829 res = ast_waitstream(chan, "");
2832 res = ast_streamfile(chan, sound, chan->language);
2833 res = ast_waitstream(chan, "");
2836 check = ast_autoservice_stop(peer);
2839 static int ast_generic_bridge(int *playitagain, int *playit, struct timeval *start_time, struct ast_channel *c0, struct ast_channel *c1, struct ast_bridge_config *config, struct ast_frame **fo, struct ast_channel **rc)
2841 /* Copy voice back and forth between the two channels. Give the peer
2842 the ability to transfer calls with '#<extension' syntax. */
2843 struct ast_channel *cs[3];
2845 struct ast_frame *f;
2846 struct ast_channel *who = NULL;
2849 int o0nativeformats;
2850 int o1nativeformats;
2851 long elapsed_ms=0, time_left_ms=0;
2857 o0nativeformats = c0->nativeformats;
2858 o1nativeformats = c1->nativeformats;
2861 if ((c0->pvt != pvt0) || (c1->pvt != pvt1) ||
2862 (o0nativeformats != c0->nativeformats) ||
2863 (o1nativeformats != c1->nativeformats)) {
2864 /* Check for Masquerade, codec changes, etc */
2869 if (config->timelimit) {
2870 /* If there is a time limit, return now */
2871 elapsed_ms = ast_tvdiff_ms(ast_tvnow(), *start_time);
2872 time_left_ms = config->timelimit - elapsed_ms;
2874 if (*playitagain && ((ast_test_flag(&(config->features_caller), AST_FEATURE_PLAY_WARNING)) || (ast_test_flag(&(config->features_callee), AST_FEATURE_PLAY_WARNING))) && (config->play_warning && time_left_ms <= config->play_warning)) {
2875 if (config->warning_freq == 0 || time_left_ms == config->play_warning || (time_left_ms % config->warning_freq) <= 50) {
2880 if (time_left_ms <= 0) {
2884 if (time_left_ms >= 5000 && *playit) {
2891 who = ast_waitfor_n(cs, 2, &to);
2893 ast_log(LOG_DEBUG, "Nobody there, continuing...\n");
2894 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE || c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE) {
2895 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
2896 c0->_softhangup = 0;
2897 if (c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
2898 c1->_softhangup = 0;
2910 ast_log(LOG_DEBUG, "Didn't get a frame from channel: %s\n",who->name);
2914 if ((f->frametype == AST_FRAME_CONTROL) && !(config->flags & AST_BRIDGE_IGNORE_SIGS)) {
2915 if ((f->subclass == AST_CONTROL_HOLD) || (f->subclass == AST_CONTROL_UNHOLD)) {
2916 ast_indicate(who == c0 ? c1 : c0, f->subclass);
2921 ast_log(LOG_DEBUG, "Got a FRAME_CONTROL (%d) frame on channel %s\n", f->subclass, who->name);
2925 if ((f->frametype == AST_FRAME_VOICE) ||
2926 (f->frametype == AST_FRAME_TEXT) ||
2927 (f->frametype == AST_FRAME_VIDEO) ||
2928 (f->frametype == AST_FRAME_IMAGE) ||
2929 (f->frametype == AST_FRAME_HTML) ||
2930 (f->frametype == AST_FRAME_DTMF)) {
2932 if ((f->frametype == AST_FRAME_DTMF) &&
2933 (config->flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))) {
2935 if ((config->flags & AST_BRIDGE_DTMF_CHANNEL_0)) {
2938 /* Take out of conference mode */
2940 ast_log(LOG_DEBUG, "Got AST_BRIDGE_DTMF_CHANNEL_0 on c0 (%s)\n",c0->name);
2946 if (config->flags & AST_BRIDGE_DTMF_CHANNEL_1) {
2950 ast_log(LOG_DEBUG, "Got AST_BRIDGE_DTMF_CHANNEL_1 on c1 (%s)\n",c1->name);
2957 ast_log(LOG_DEBUG, "Read from %s\n", who->name);
2959 ast_log(LOG_DEBUG, "Servicing channel %s twice in a row?\n", last->name);
2963 /* Don't copy packets if there is a generator on either one, since they're
2964 not supposed to be listening anyway */
2973 /* Swap who gets priority */
2981 /*--- ast_channel_bridge: Bridge two channels together */
2982 int ast_channel_bridge(struct ast_channel *c0, struct ast_channel *c1, struct ast_bridge_config *config, struct ast_frame **fo, struct ast_channel **rc)
2984 /* Copy voice back and forth between the two channels. Give the peer
2985 the ability to transfer calls with '#<extension' syntax. */
2986 struct ast_channel *cs[3];
2987 struct ast_channel *who = NULL;
2991 int o0nativeformats;
2992 int o1nativeformats;
2993 struct timeval start_time;
2994 long elapsed_ms=0, time_left_ms=0;
2995 int playit=0, playitagain=1, first_time=1;
2998 firstpass = config->firstpass;
2999 config->firstpass = 0;
3002 start_time = ast_tvnow();
3003 time_left_ms = config->timelimit;
3005 if ((ast_test_flag(&(config->features_caller), AST_FEATURE_PLAY_WARNING)) && config->start_sound && firstpass)
3006 bridge_playfile(c0,c1,config->start_sound,time_left_ms / 1000);
3007 if ((ast_test_flag(&(config->features_callee), AST_FEATURE_PLAY_WARNING)) && config->start_sound && firstpass)
3008 bridge_playfile(c1,c0,config->start_sound,time_left_ms / 1000);
3010 /* Stop if we're a zombie or need a soft hangup */
3011 if (ast_test_flag(c0, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c0) || ast_test_flag(c1, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c1))
3014 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n",
3015 c0->name, c0->_bridge->name);
3019 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n",
3020 c1->name, c1->_bridge->name);
3024 /* Keep track of bridge */
3030 manager_event(EVENT_FLAG_CALL, "Link",
3036 "CallerID2: %s\r\n",
3037 c0->name, c1->name, c0->uniqueid, c1->uniqueid, c0->cid.cid_num, c1->cid.cid_num);
3039 o1nativeformats = c1->nativeformats;
3040 o0nativeformats = c0->nativeformats;
3041 for (/* ever */;;) {
3043 if (config->timelimit) {
3044 elapsed_ms = ast_tvdiff_ms(ast_tvnow(), start_time);
3045 time_left_ms = config->timelimit - elapsed_ms;
3047 if (playitagain && ((ast_test_flag(&(config->features_caller), AST_FEATURE_PLAY_WARNING)) || (ast_test_flag(&(config->features_callee), AST_FEATURE_PLAY_WARNING))) && (config->play_warning && time_left_ms <= config->play_warning)) {
3048 /* narrowing down to the end */
3049 if (config->warning_freq == 0) {
3053 } else if (first_time) {
3057 if ((time_left_ms % config->warning_freq) <= 50) {
3062 if (time_left_ms <= 0) {
3063 if ((ast_test_flag(&(config->features_caller), AST_FEATURE_PLAY_WARNING)) && config->end_sound)
3064 bridge_playfile(c0,c1,config->end_sound,0);
3065 if ((ast_test_flag(&(config->features_callee), AST_FEATURE_PLAY_WARNING)) && config->end_sound)
3066 bridge_playfile(c1,c0,config->end_sound,0);
3073 if (time_left_ms >= 5000 && playit) {
3074 if ((ast_test_flag(&(config->features_caller), AST_FEATURE_PLAY_WARNING)) && config->warning_sound && config->play_warning)
3075 bridge_playfile(c0,c1,config->warning_sound,time_left_ms / 1000);
3076 if ((ast_test_flag(&(config->features_callee), AST_FEATURE_PLAY_WARNING)) && config->warning_sound && config->play_warning)
3077 bridge_playfile(c1,c0,config->warning_sound,time_left_ms / 1000);
3083 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE || c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE) {
3084 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
3085 c0->_softhangup = 0;
3086 if (c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
3087 c1->_softhangup = 0;
3090 ast_log(LOG_DEBUG, "Unbridge signal received. Ending native bridge.\n");
3094 /* Stop if we're a zombie or need a soft hangup */
3095 if (ast_test_flag(c0, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c0) || ast_test_flag(c1, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c1)) {
3100 ast_log(LOG_DEBUG, "Bridge stops because we're zombie or need a soft hangup: c0=%s, c1=%s, flags: %s,%s,%s,%s\n",c0->name,c1->name,ast_test_flag(c0, AST_FLAG_ZOMBIE)?"Yes":"No",ast_check_hangup(c0)?"Yes":"No",ast_test_flag(c1, AST_FLAG_ZOMBIE)?"Yes":"No",ast_check_hangup(c1)?"Yes":"No");
3103 if (c0->tech->bridge && config->timelimit==0 &&
3104 (c0->tech->bridge == c1->tech->bridge) && !nativefailed && !c0->monitor && !c1->monitor && !c0->spiers && !c1->spiers) {
3105 /* Looks like they share a bridge code */
3106 if (option_verbose > 2)
3107 ast_verbose(VERBOSE_PREFIX_3 "Attempting native bridge of %s and %s\n", c0->name, c1->name);
3108 ast_set_flag(c0, AST_FLAG_NBRIDGE);
3109 ast_set_flag(c1, AST_FLAG_NBRIDGE);
3110 if (!(res = c0->tech->bridge(c0, c1, config->flags, fo, rc))) {