Skip to content
Snippets Groups Projects
app.c 54.4 KiB
Newer Older
  • Learn to ignore specific revisions
  • Mark Spencer's avatar
    Mark Spencer committed
    /*
    
     * Asterisk -- An open source telephony toolkit.
    
    Mark Spencer's avatar
    Mark Spencer committed
     *
    
     * Copyright (C) 1999 - 2005, Digium, Inc.
    
    Mark Spencer's avatar
    Mark Spencer committed
     *
    
     * Mark Spencer <markster@digium.com>
    
    Mark Spencer's avatar
    Mark Spencer committed
     *
    
     * See http://www.asterisk.org for more information about
     * the Asterisk project. Please do not directly contact
     * any of the maintainers of this project for assistance;
     * the project provides a web site, mailing lists and IRC
     * channels for your use.
     *
    
    Mark Spencer's avatar
    Mark Spencer committed
     * This program is free software, distributed under the terms of
    
     * the GNU General Public License Version 2. See the LICENSE file
     * at the top of the source tree.
     */
    
    
     * \brief Convenient Application Routines
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
     * \author Mark Spencer <markster@digium.com>
    
    #include "asterisk.h"
    
    ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
    
    
    #ifdef HAVE_SYS_STAT_H
    
    #include <sys/stat.h>
    
    #endif
    
    #include <regex.h>          /* for regcomp(3) */
    #include <sys/file.h>       /* for flock(2) */
    #include <signal.h>         /* for pthread_sigmask(3) */
    
    #include <stdlib.h>         /* for closefrom(3) */
    
    #include <sys/types.h>
    #include <sys/wait.h>       /* for waitpid(2) */
    #ifndef HAVE_CLOSEFROM
    #include <dirent.h>         /* for opendir(3)   */
    #endif
    
    #ifdef HAVE_CAP
    #include <sys/capability.h>
    #endif /* HAVE_CAP */
    
    #include "asterisk/paths.h"	/* use ast_config_AST_DATA_DIR */
    
    #include "asterisk/channel.h"
    #include "asterisk/pbx.h"
    #include "asterisk/file.h"
    #include "asterisk/app.h"
    #include "asterisk/dsp.h"
    #include "asterisk/utils.h"
    #include "asterisk/lock.h"
    #include "asterisk/indications.h"
    
    #include "asterisk/linkedlists.h"
    
    AST_THREADSTORAGE_PUBLIC(ast_str_thread_global_buf);
    
    static pthread_t shaun_of_the_dead_thread = AST_PTHREADT_NULL;
    
    struct zombie {
    	pid_t pid;
    	AST_LIST_ENTRY(zombie) list;
    };
    
    static AST_LIST_HEAD_STATIC(zombies, zombie);
    
    static void *shaun_of_the_dead(void *data)
    {
    	struct zombie *cur;
    	int status;
    	for (;;) {
    		if (!AST_LIST_EMPTY(&zombies)) {
    			/* Don't allow cancellation while we have a lock. */
    			pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
    			AST_LIST_LOCK(&zombies);
    			AST_LIST_TRAVERSE_SAFE_BEGIN(&zombies, cur, list) {
    				if (waitpid(cur->pid, &status, WNOHANG) != 0) {
    					AST_LIST_REMOVE_CURRENT(list);
    					ast_free(cur);
    				}
    			}
    			AST_LIST_TRAVERSE_SAFE_END
    			AST_LIST_UNLOCK(&zombies);
    			pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
    		}
    		pthread_testcancel();
    		/* Wait for 60 seconds, without engaging in a busy loop. */
    		ast_poll(NULL, 0, AST_LIST_FIRST(&zombies) ? 5000 : 60000);
    	}
    	return NULL;
    }
    
    
    #define AST_MAX_FORMATS 10
    
    static AST_RWLIST_HEAD_STATIC(groups, ast_group_info);
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
     * \brief This function presents a dialtone and reads an extension into 'collect'
     * which must be a pointer to a **pre-initialized** array of char having a
     * size of 'size' suitable for writing to.  It will collect no more than the smaller
    
     * of 'maxlen' or 'size' minus the original strlen() of collect digits.
     * \param chan struct.
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
     * \param context
     * \param collect
     * \param size
    
     * \param maxlen
     * \param timeout timeout in seconds
     *
     * \return 0 if extension does not exist, 1 if extension exists
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    int ast_app_dtget(struct ast_channel *chan, const char *context, char *collect, size_t size, int maxlen, int timeout)
    
    	struct ast_tone_zone_sound *ts;
    
    	int res = 0, x = 0;
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    	if (maxlen > size) {
    
    Mark Spencer's avatar
    Mark Spencer committed
    		maxlen = size;
    
    	if (!timeout && chan->pbx) {
    
    		timeout = chan->pbx->dtimeoutms / 1000.0;
    
    	if ((ts = ast_get_indication_tone(chan->zone, "dial"))) {
    
    		res = ast_playtones_start(chan, 0, ts->data, 0);
    
    		ts = ast_tone_zone_sound_unref(ts);
    	} else {
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    		ast_log(LOG_NOTICE, "Huh....? no dial for indications?\n");
    
    	for (x = strlen(collect); x < maxlen; ) {
    
    		res = ast_waitfordigit(chan, timeout);
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    		if (!ast_ignore_pattern(context, collect)) {
    
    			ast_playtones_stop(chan);
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    		}
    		if (res < 1) {
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    		}
    		if (res == '#') {
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    		}
    
    		if (!ast_matchmore_extension(chan, context, collect, 1,
    			S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL))) {
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    		}
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    	if (res >= 0) {
    
    		res = ast_exists_extension(chan, context, collect, 1,
    			S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL)) ? 1 : 0;
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    	}
    
    /*!
     * \brief ast_app_getdata
     * \param c The channel to read from
     * \param prompt The file to stream to the channel
     * \param s The string to read in to.  Must be at least the size of your length
     * \param maxlen How many digits to read (maximum)
     * \param timeout set timeout to 0 for "standard" timeouts. Set timeout to -1 for 
    
     *      "ludicrous time" (essentially never times out) */
    
    enum ast_getdata_result ast_app_getdata(struct ast_channel *c, const char *prompt, char *s, int maxlen, int timeout)
    
    Mark Spencer's avatar
    Mark Spencer committed
    {
    
    	/* XXX Merge with full version? XXX */
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    		prompt = "";
    
    
    	filename = ast_strdupa(prompt);
    	while ((front = strsep(&filename, "&"))) {
    
    		if (!ast_strlen_zero(front)) {
    			res = ast_streamfile(c, front, c->language);
    			if (res)
    				continue;
    		}
    
    		if (ast_strlen_zero(filename)) {
    			/* set timeouts for the last prompt */
    
    			fto = c->pbx ? c->pbx->rtimeoutms : 6000;
    			to = c->pbx ? c->pbx->dtimeoutms : 2000;
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    			if (timeout > 0) {
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    			}
    			if (timeout < 0) {
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    			}
    
    		} else {
    			/* there is more than one prompt, so
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    			 * get rid of the long timeout between
    			 * prompts, and make it 50ms */
    
    			to = c->pbx ? c->pbx->dtimeoutms : 2000;
    
    		}
    		res = ast_readstring(c, s, maxlen, to, fto, "#");
    
    		if (res == AST_GETDATA_EMPTY_END_TERMINATED) {
    
    Mark Spencer's avatar
    Mark Spencer committed
    			return res;
    
    Mark Spencer's avatar
    Mark Spencer committed
    	}
    
    Mark Spencer's avatar
    Mark Spencer committed
    	return res;
    }
    
    
    Russell Bryant's avatar
    Russell Bryant committed
    /* The lock type used by ast_lock_path() / ast_unlock_path() */
    static enum AST_LOCK_TYPE ast_lock_type = AST_LOCK_TYPE_LOCKFILE;
    
    int ast_app_getdata_full(struct ast_channel *c, const char *prompt, char *s, int maxlen, int timeout, int audiofd, int ctrlfd)
    
    	int res, to = 2000, fto = 6000;
    
    	if (!ast_strlen_zero(prompt)) {
    
    		res = ast_streamfile(c, prompt, c->language);
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    		if (res < 0) {
    
    			return res;
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    		}
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    
    	if (timeout > 0) {
    
    		fto = to = timeout;
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    	}
    	if (timeout < 0) {
    
    		fto = to = 1000000000;
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    	}
    
    	res = ast_readstring_full(c, s, maxlen, to, fto, "#", audiofd, ctrlfd);
    
    int ast_app_run_macro(struct ast_channel *autoservice_chan, struct ast_channel *macro_chan, const char * const macro_name, const char * const macro_args)
    {
    	struct ast_app *macro_app;
    	int res;
    	char buf[1024];
    
    	macro_app = pbx_findapp("Macro");
    	if (!macro_app) {
    		ast_log(LOG_WARNING, "Cannot run macro '%s' because the 'Macro' application in not available\n", macro_name);
    		return -1;
    	}
    	snprintf(buf, sizeof(buf), "%s%s%s", macro_name, ast_strlen_zero(macro_args) ? "" : ",", S_OR(macro_args, ""));
    	if (autoservice_chan) {
    		ast_autoservice_start(autoservice_chan);
    	}
    	res = pbx_exec(macro_chan, macro_app, buf);
    	if (autoservice_chan) {
    		ast_autoservice_stop(autoservice_chan);
    	}
    	return res;
    }
    
    
    static int (*ast_has_voicemail_func)(const char *mailbox, const char *folder) = NULL;
    
    static int (*ast_inboxcount_func)(const char *mailbox, int *newmsgs, int *oldmsgs) = NULL;
    static int (*ast_inboxcount2_func)(const char *mailbox, int *urgentmsgs, int *newmsgs, int *oldmsgs) = NULL;
    
    static int (*ast_sayname_func)(struct ast_channel *chan, const char *mailbox, const char *context) = NULL;
    
    static int (*ast_messagecount_func)(const char *context, const char *mailbox, const char *folder) = NULL;
    
    
    void ast_install_vm_functions(int (*has_voicemail_func)(const char *mailbox, const char *folder),
    
    			      int (*inboxcount_func)(const char *mailbox, int *newmsgs, int *oldmsgs),
    			      int (*inboxcount2_func)(const char *mailbox, int *urgentmsgs, int *newmsgs, int *oldmsgs),
    
    			      int (*messagecount_func)(const char *context, const char *mailbox, const char *folder),
    			      int (*sayname_func)(struct ast_channel *chan, const char *mailbox, const char *context))
    
    {
    	ast_has_voicemail_func = has_voicemail_func;
    
    	ast_inboxcount2_func = inboxcount2_func;
    
    	ast_messagecount_func = messagecount_func;
    
    }
    
    void ast_uninstall_vm_functions(void)
    {
    	ast_has_voicemail_func = NULL;
    
    	ast_inboxcount2_func = NULL;
    
    	ast_messagecount_func = NULL;
    
    int ast_app_has_voicemail(const char *mailbox, const char *folder)
    
    Mark Spencer's avatar
    Mark Spencer committed
    {
    
    	static int warned = 0;
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    	if (ast_has_voicemail_func) {
    
    		return ast_has_voicemail_func(mailbox, folder);
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    	}
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    	if (warned++ % 10 == 0) {
    
    		ast_verb(3, "Message check requested for mailbox %s/folder %s but voicemail not loaded.\n", mailbox, folder ? folder : "INBOX");
    
    Mark Spencer's avatar
    Mark Spencer committed
    	return 0;
    }
    
    int ast_app_inboxcount(const char *mailbox, int *newmsgs, int *oldmsgs)
    
    	static int warned = 0;
    
    	}
    	if (oldmsgs) {
    		*oldmsgs = 0;
    	}
    	if (ast_inboxcount_func) {
    		return ast_inboxcount_func(mailbox, newmsgs, oldmsgs);
    	}
    
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    	if (warned++ % 10 == 0) {
    
    		ast_verb(3, "Message count requested for mailbox %s but voicemail not loaded.\n", mailbox);
    	}
    
    	return 0;
    }
    
    int ast_app_inboxcount2(const char *mailbox, int *urgentmsgs, int *newmsgs, int *oldmsgs)
    {
    	static int warned = 0;
    	if (newmsgs) {
    		*newmsgs = 0;
    	}
    	if (oldmsgs) {
    
    	}
    	if (ast_inboxcount_func) {
    		return ast_inboxcount2_func(mailbox, urgentmsgs, newmsgs, oldmsgs);
    	}
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    	if (warned++ % 10 == 0) {
    
    		ast_verb(3, "Message count requested for mailbox %s but voicemail not loaded.\n", mailbox);
    
    int ast_app_sayname(struct ast_channel *chan, const char *mailbox, const char *context)
    {
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    	if (ast_sayname_func) {
    
    		return ast_sayname_func(chan, mailbox, context);
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    	}
    
    int ast_app_messagecount(const char *context, const char *mailbox, const char *folder)
    
    {
    	static int warned = 0;
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    	if (ast_messagecount_func) {
    
    		return ast_messagecount_func(context, mailbox, folder);
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    	}
    
    		warned++;
    
    		ast_verb(3, "Message count requested for mailbox %s@%s/%s but voicemail not loaded.\n", mailbox, context, folder);
    
    Russell Bryant's avatar
    Russell Bryant committed
    int ast_dtmf_stream(struct ast_channel *chan, struct ast_channel *peer, const char *digits, int between, unsigned int duration)
    
    James Golovich's avatar
    James Golovich committed
    {
    
    	struct ast_silence_generator *silgen = NULL;
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    	if (!between) {
    
    James Golovich's avatar
    James Golovich committed
    		between = 100;
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    	}
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    	if (peer) {
    
    James Golovich's avatar
    James Golovich committed
    		res = ast_autoservice_start(peer);
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    	}
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    	if (!res) {
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    	}
    
    
    	/* ast_waitfor will return the number of remaining ms on success */
    
    	if (res < 0) {
    		if (peer) {
    			ast_autoservice_stop(peer);
    		}
    
    	if (ast_opt_transmit_silence) {
    		silgen = ast_channel_start_silence_generator(chan);
    	}
    
    
    	for (ptr = digits; *ptr; ptr++) {
    		if (*ptr == 'w') {
    			/* 'w' -- wait half a second */
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    			if ((res = ast_safe_sleep(chan, 500))) {
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    			}
    
    		} else if (strchr("0123456789*#abcdfABCDF", *ptr)) {
    			/* Character represents valid DTMF */
    			if (*ptr == 'f' || *ptr == 'F') {
    				/* ignore return values if not supported by channel */
    				ast_indicate(chan, AST_CONTROL_FLASH);
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    			} else {
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    			}
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    			if ((res = ast_safe_sleep(chan, between))) {
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    			}
    		} else {
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    			ast_log(LOG_WARNING, "Illegal DTMF character '%c' in string. (0-9*#aAbBcCdD allowed)\n", *ptr);
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    		}
    
    James Golovich's avatar
    James Golovich committed
    	}
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    		/* Stop autoservice on the peer channel, but don't overwrite any error condition
    
    		   that has occurred previously while acting on the primary channel */
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    		if (ast_autoservice_stop(peer) && !res) {
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    		}
    
    	if (silgen) {
    		ast_channel_stop_silence_generator(chan, silgen);
    	}
    
    
    James Golovich's avatar
    James Golovich committed
    	return res;
    
    
    struct linear_state {
    	int fd;
    	int autoclose;
    	int allowoverride;
    	int origwfmt;
    };
    
    static void linear_release(struct ast_channel *chan, void *params)
    {
    	struct linear_state *ls = params;
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    
    	if (ls->origwfmt && ast_set_write_format(chan, ls->origwfmt)) {
    
    		ast_log(LOG_WARNING, "Unable to restore channel '%s' to format '%d'\n", chan->name, ls->origwfmt);
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    	}
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    	if (ls->autoclose) {
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    	}
    
    }
    
    static int linear_generator(struct ast_channel *chan, void *data, int len, int samples)
    {
    	short buf[2048 + AST_FRIENDLY_OFFSET / 2];
    	struct linear_state *ls = data;
    
    	struct ast_frame f = {
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    		.frametype = AST_FRAME_VOICE,
    
    		.subclass.codec = AST_FORMAT_SLINEAR,
    
    		.data.ptr = buf + AST_FRIENDLY_OFFSET / 2,
    
    		.offset = AST_FRIENDLY_OFFSET,
    
    	len = samples * 2;
    	if (len > sizeof(buf) - AST_FRIENDLY_OFFSET) {
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    		ast_log(LOG_WARNING, "Can't generate %d bytes of data!\n" , len);
    
    		len = sizeof(buf) - AST_FRIENDLY_OFFSET;
    	}
    	res = read(ls->fd, buf + AST_FRIENDLY_OFFSET/2, len);
    	if (res > 0) {
    		f.datalen = res;
    		f.samples = res / 2;
    		ast_write(chan, &f);
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    		if (res == len) {
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    		}
    
    	}
    	return -1;
    }
    
    static void *linear_alloc(struct ast_channel *chan, void *params)
    {
    
    	struct linear_state *ls = params;
    
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    	if (!params) {
    
    		return NULL;
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    	}
    
    	/* In this case, params is already malloc'd */
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    	if (ls->allowoverride) {
    
    		ast_set_flag(chan, AST_FLAG_WRITE_INT);
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    	} else {
    
    		ast_clear_flag(chan, AST_FLAG_WRITE_INT);
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    	}
    
    
    	ls->origwfmt = chan->writeformat;
    
    	if (ast_set_write_format(chan, AST_FORMAT_SLINEAR)) {
    		ast_log(LOG_WARNING, "Unable to set '%s' to linear format (write)\n", chan->name);
    		ast_free(ls);
    		ls = params = NULL;
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    static struct ast_generator linearstream =
    
    {
    	alloc: linear_alloc,
    	release: linear_release,
    	generate: linear_generator,
    };
    
    int ast_linear_stream(struct ast_channel *chan, const char *filename, int fd, int allowoverride)
    {
    	struct linear_state *lin;
    
    	int res = -1;
    	int autoclose = 0;
    	if (fd < 0) {
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    		if (ast_strlen_zero(filename)) {
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    		}
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    		if (filename[0] == '/') {
    
    			ast_copy_string(tmpf, filename, sizeof(tmpf));
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    		} else {
    
    Luigi Rizzo's avatar
    Luigi Rizzo committed
    			snprintf(tmpf, sizeof(tmpf), "%s/%s/%s", ast_config_AST_DATA_DIR, "sounds", filename);
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    		}
    
    		if ((fd = open(tmpf, O_RDONLY)) < 0) {
    
    			ast_log(LOG_WARNING, "Unable to open file '%s': %s\n", tmpf, strerror(errno));
    			return -1;
    		}
    	}
    
    	if ((lin = ast_calloc(1, sizeof(*lin)))) {
    
    		lin->fd = fd;
    		lin->allowoverride = allowoverride;
    		lin->autoclose = autoclose;
    		res = ast_activate_generator(chan, &linearstream, lin);
    	}
    	return res;
    }
    
    int ast_control_streamfile(struct ast_channel *chan, const char *file,
    			   const char *fwd, const char *rev,
    
    			   const char *stop, const char *suspend,
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    			   const char *restart, int skipms, long *offsetms)
    
    James Golovich's avatar
    James Golovich committed
    {
    
    	char *breaks = NULL;
    	char *end = NULL;
    	int blen = 2;
    	int res;
    
    	long pause_restart_point = 0;
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    	if (offsetms) {
    
    		offset = *offsetms * 8; /* XXX Assumes 8kHz */
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    	}
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    	if (stop) {
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    	}
    	if (suspend) {
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    	}
    	if (restart) {
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    	}
    
    James Golovich's avatar
    James Golovich committed
    	if (blen > 2) {
    
    		breaks = alloca(blen + 1);
    		breaks[0] = '\0';
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    		if (stop) {
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    		}
    		if (suspend) {
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    		}
    		if (restart) {
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    		}
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    	if (chan->_state != AST_STATE_UP) {
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    	}
    
    James Golovich's avatar
    James Golovich committed
    	if (file) {
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    		if ((end = strchr(file, ':'))) {
    
    James Golovich's avatar
    James Golovich committed
    			if (!strcasecmp(end, ":end")) {
    
    Anthony Minessale II's avatar
    Anthony Minessale II committed
    				*end = '\0';
    				end++;
    			}
    
    James Golovich's avatar
    James Golovich committed
    		}
    
    James Golovich's avatar
    James Golovich committed
    	}
    
    James Golovich's avatar
    James Golovich committed
    	for (;;) {
    
    		res = ast_streamfile(chan, file, chan->language);
    
    James Golovich's avatar
    James Golovich committed
    		if (!res) {
    
    			if (pause_restart_point) {
    				ast_seekstream(chan->stream, pause_restart_point, SEEK_SET);
    				pause_restart_point = 0;
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    				if (offset == -8) {
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    				}
    
    				ast_verb(3, "ControlPlayback seek to offset %ld from end\n", offset);
    
    
    				ast_seekstream(chan->stream, offset, SEEK_END);
    
    				ast_verb(3, "ControlPlayback seek to offset %ld\n", offset);
    
    				ast_seekstream(chan->stream, offset, SEEK_SET);
    				offset = 0;
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    			}
    
    			res = ast_waitstream_fr(chan, breaks, fwd, rev, skipms);
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    		if (res < 1) {
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    		}
    
    		/* We go at next loop if we got the restart char */
    		if (restart && strchr(restart, res)) {
    
    			ast_debug(1, "we'll restart the stream here at next loop\n");
    
    		if (suspend && strchr(suspend, res)) {
    
    			pause_restart_point = ast_tellstream(chan->stream);
    			for (;;) {
    				ast_stopstream(chan);
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    				if (!(res = ast_waitfordigit(chan, 1000))) {
    
    					continue;
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    				} else if (res == -1 || strchr(suspend, res) || (stop && strchr(stop, res))) {
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    				}
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    		if (res == -1) {
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    		}
    
    		/* if we get one of our stop chars, return it to the calling function */
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    		if (stop && strchr(stop, res)) {
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    		}
    
    	if (pause_restart_point) {
    		offset = pause_restart_point;
    	} else {
    		if (chan->stream) {
    			offset = ast_tellstream(chan->stream);
    		} else {
    			offset = -8;  /* indicate end of file */
    		}
    	}
    
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    	if (offsetms) {
    
    		*offsetms = offset / 8; /* samples --> ms ... XXX Assumes 8 kHz */
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    	}
    
    	/* If we are returning a digit cast it as char */
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    	if (res > 0 || chan->stream) {
    
    		res = (char)res;
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    	}
    
    James Golovich's avatar
    James Golovich committed
    	return res;
    
    int ast_play_and_wait(struct ast_channel *chan, const char *fn)
    
    	int d = 0;
    
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    	if ((d = ast_streamfile(chan, fn, chan->language))) {
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    	}
    
    	d = ast_waitstream(chan, AST_DIGIT_ANY);
    
    	return d;
    }
    
    static int global_silence_threshold = 128;
    static int global_maxsilence = 0;
    
    
    /*! Optionally play a sound file or a beep, then record audio and video from the channel.
    
     * \param chan Channel to playback to/record from.
     * \param playfile Filename of sound to play before recording begins.
     * \param recordfile Filename to record to.
     * \param maxtime Maximum length of recording (in milliseconds).
     * \param fmt Format(s) to record message in. Multiple formats may be specified by separating them with a '|'.
     * \param duration Where to store actual length of the recorded message (in milliseconds).
     * \param beep Whether to play a beep before starting to record.
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
     * \param silencethreshold
    
     * \param maxsilence Length of silence that will end a recording (in milliseconds).
     * \param path Optional filesystem path to unlock.
     * \param prepend If true, prepend the recorded audio to an existing file.
     * \param acceptdtmf DTMF digits that will end the recording.
     * \param canceldtmf DTMF digits that will cancel the recording.
    
     */
    
    static int __ast_play_and_record(struct ast_channel *chan, const char *playfile, const char *recordfile, int maxtime, const char *fmt, int *duration, int beep, int silencethreshold, int maxsilence, const char *path, int prepend, const char *acceptdtmf, const char *canceldtmf)
    
    BJ Weschke's avatar
    BJ Weschke committed
    	int x, fmtcnt = 1, res = -1, outmsg = 0;
    
    	struct ast_filestream *others[AST_MAX_FORMATS];
    	char *sfmt[AST_MAX_FORMATS];
    
    BJ Weschke's avatar
    BJ Weschke committed
    	char *stringp = NULL;
    
    BJ Weschke's avatar
    BJ Weschke committed
    	struct ast_dsp *sildet = NULL;   /* silence detector dsp */
    
    	int dspsilence = 0;
    
    BJ Weschke's avatar
    BJ Weschke committed
    	int rfmt = 0;
    
    	struct ast_silence_generator *silgen = NULL;
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    	if (silencethreshold < 0) {
    
    		silencethreshold = global_silence_threshold;
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    	}
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    	if (maxsilence < 0) {
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    	}
    
    
    	/* barf if no pointer passed to store duration in */
    
    		ast_log(LOG_WARNING, "Error play_and_record called without duration pointer\n");
    		return -1;
    	}
    
    
    	ast_debug(1, "play_and_record: %s, %s, '%s'\n", playfile ? playfile : "<None>", recordfile, fmt);
    
    BJ Weschke's avatar
    BJ Weschke committed
    	snprintf(comment, sizeof(comment), "Playing %s, Recording to: %s on %s\n", playfile ? playfile : "<None>", recordfile, chan->name);
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    		if (!beep) {
    
    			d = ast_play_and_wait(chan, playfile);
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    		}
    		if (d > -1) {
    
    			d = ast_stream_and_wait(chan, "beep", "");
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    		}
    		if (d < 0) {
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    		}
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    		ast_copy_string(prependfile, recordfile, sizeof(prependfile));
    
    		strncat(prependfile, "-prepend", sizeof(prependfile) - strlen(prependfile) - 1);
    	}
    
    
    BJ Weschke's avatar
    BJ Weschke committed
    	stringp = fmts;
    
    	ast_debug(1, "Recording Formats: sfmts=%s\n", fmts);
    
    	while ((fmt = strsep(&stringp, "|"))) {
    
    		if (fmtcnt > AST_MAX_FORMATS - 1) {
    			ast_log(LOG_WARNING, "Please increase AST_MAX_FORMATS in file.h\n");
    
    	end = start = time(NULL);  /* pre-initialize end to be same as start in case we never get into loop */
    
    BJ Weschke's avatar
    BJ Weschke committed
    	for (x = 0; x < fmtcnt; x++) {
    
    		others[x] = ast_writefile(prepend ? prependfile : recordfile, sfmt[x], comment, O_TRUNC, 0, AST_FILE_MODE);
    
    		ast_verb(3, "x=%d, open writing:  %s format: %s, %p\n", x, prepend ? prependfile : recordfile, sfmt[x], others[x]);
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    		if (!others[x]) {
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    		}
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    	if (path) {
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    	}
    
    		sildet = ast_dsp_new(); /* Create the silence detector */
    		if (!sildet) {
    			ast_log(LOG_WARNING, "Unable to create silence detector :(\n");
    			return -1;
    		}
    		ast_dsp_set_threshold(sildet, silencethreshold);
    
    		rfmt = chan->readformat;
    		res = ast_set_read_format(chan, AST_FORMAT_SLINEAR);
    		if (res < 0) {
    			ast_log(LOG_WARNING, "Unable to set to linear mode, giving up\n");
    
    	if (!prepend) {
    		/* Request a video update */
    		ast_indicate(chan, AST_CONTROL_VIDUPDATE);
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    		if (ast_opt_transmit_silence) {
    
    			silgen = ast_channel_start_silence_generator(chan);
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    		}
    
    		/* Loop forever, writing the packets we read to the writer(s), until
    		   we read a digit or get a hangup */
    		struct ast_frame *f;
    
    BJ Weschke's avatar
    BJ Weschke committed
    		for (;;) {
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    			if (!(res = ast_waitfor(chan, 2000))) {
    
    				ast_debug(1, "One waitfor failed, trying another\n");
    
    				/* Try one more time in case of masq */
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    				if (!(res = ast_waitfor(chan, 2000))) {
    
    					ast_log(LOG_WARNING, "No audio available on %s??\n", chan->name);
    					res = -1;
    				}
    			}
    
    			if (res < 0) {
    				f = NULL;
    				break;
    			}
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    			if (!(f = ast_read(chan))) {
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    			}
    
    			if (f->frametype == AST_FRAME_VOICE) {
    				/* write each format */
    
    BJ Weschke's avatar
    BJ Weschke committed
    				for (x = 0; x < fmtcnt; x++) {
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    					if (prepend && !others[x]) {
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    					}
    
    					res = ast_writestream(others[x], f);
    				}
    
    				/* Silence Detection */
    				if (maxsilence > 0) {
    
    					ast_dsp_silence(sildet, f, &dspsilence);
    
    					if (olddspsilence > dspsilence) {
    						totalsilence += olddspsilence;
    					}
    					olddspsilence = dspsilence;
    
    					if (dspsilence > maxsilence) {
    
    						ast_verb(3, "Recording automatically stopped after a silence of %d seconds\n", dspsilence/1000);
    
    BJ Weschke's avatar
    BJ Weschke committed
    						outmsg = 2;
    
    					}
    				}
    				/* Exit on any error */
    				if (res) {
    					ast_log(LOG_WARNING, "Error writing frame\n");
    					break;
    				}
    			} else if (f->frametype == AST_FRAME_VIDEO) {
    				/* Write only once */
    				ast_writestream(others[0], f);
    			} else if (f->frametype == AST_FRAME_DTMF) {
    
    				if (prepend) {
    				/* stop recording with any digit */
    
    					ast_verb(3, "User ended message by pressing %c\n", f->subclass.integer);
    
    				if (strchr(acceptdtmf, f->subclass.integer)) {
    					ast_verb(3, "User ended message by pressing %c\n", f->subclass.integer);
    					res = f->subclass.integer;
    
    				if (strchr(canceldtmf, f->subclass.integer)) {
    					ast_verb(3, "User cancelled message by pressing %c\n", f->subclass.integer);
    					res = f->subclass.integer;
    
    				end = time(NULL);
    
    					ast_verb(3, "Took too long, cutting it short...\n");
    
    			ast_verb(3, "User hung up\n");
    
    BJ Weschke's avatar
    BJ Weschke committed
    			outmsg = 1;
    
    		}
    	} else {
    		ast_log(LOG_WARNING, "Error creating writestream '%s', format '%s'\n", recordfile, sfmt[x]);
    	}
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    		if (silgen) {
    
    			ast_channel_stop_silence_generator(chan, silgen);
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    		}
    
    
    	/*!\note
    	 * Instead of asking how much time passed (end - start), calculate the number
    	 * of seconds of audio which actually went into the file.  This fixes a
    	 * problem where audio is stopped up on the network and never gets to us.
    	 *
    	 * Note that we still want to use the number of seconds passed for the max
    	 * message, otherwise we could get a situation where this stream is never
    	 * closed (which would create a resource leak).
    	 */
    
    	*duration = others[0] ? ast_tellstream(others[0]) / 8000 : 0;
    
    		/* Reduce duration by a total silence amount */
    
    		if (olddspsilence <= dspsilence) {
    			totalsilence += dspsilence;
    		}
    
    
    Olle Johansson's avatar
    Olle Johansson committed
    		if (totalsilence > 0) {
    
    			*duration -= (totalsilence - 200) / 1000;
    
    Olle Johansson's avatar
    Olle Johansson committed
    		}
    
    		if (*duration < 0) {
    			*duration = 0;
    		}
    
    BJ Weschke's avatar
    BJ Weschke committed
    		for (x = 0; x < fmtcnt; x++) {
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    			if (!others[x]) {
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    			}
    
    			/*!\note
    			 * If we ended with silence, trim all but the first 200ms of silence
    			 * off the recording.  However, if we ended with '#', we don't want
    			 * to trim ANY part of the recording.
    			 */
    
    			if (res > 0 && dspsilence) {
    
    Olle Johansson's avatar
    Olle Johansson committed
    				/* rewind only the trailing silence */
    
    				ast_stream_rewind(others[x], dspsilence - 200);
    
    			ast_truncstream(others[x]);
    			ast_closestream(others[x]);
    
    		struct ast_filestream *realfiles[AST_MAX_FORMATS];
    
    BJ Weschke's avatar
    BJ Weschke committed
    
    		for (x = 0; x < fmtcnt; x++) {
    
    			snprintf(comment, sizeof(comment), "Opening the real file %s.%s\n", recordfile, sfmt[x]);
    			realfiles[x] = ast_readfile(recordfile, sfmt[x], comment, O_RDONLY, 0, 0);
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    			if (!others[x] || !realfiles[x]) {
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    			}
    
    			/*!\note Same logic as above. */
    
    			if (dspsilence) {
    				ast_stream_rewind(others[x], dspsilence - 200);
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    			}
    
    			ast_truncstream(others[x]);
    			/* add the original file too */
    			while ((fr = ast_readframe(realfiles[x]))) {
    
    BJ Weschke's avatar
    BJ Weschke committed
    				ast_writestream(others[x], fr);