Skip to content
Snippets Groups Projects
pbx.c 164 KiB
Newer Older
Russell Bryant's avatar
Russell Bryant committed
/*
 * Asterisk -- An open source telephony toolkit.
Mark Spencer's avatar
Mark Spencer committed
 *
 * Copyright (C) 1999 - 2006, 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 Core PBX routines.
 *
 * \author Mark Spencer <markster@digium.com> 
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include <errno.h>
#include <time.h>
#include <sys/time.h>

#include "asterisk.h"

Kevin P. Fleming's avatar
Kevin P. Fleming committed
ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
#include "asterisk/lock.h"
#include "asterisk/cli.h"
#include "asterisk/pbx.h"
#include "asterisk/channel.h"
#include "asterisk/options.h"
#include "asterisk/logger.h"
#include "asterisk/file.h"
#include "asterisk/callerid.h"
#include "asterisk/cdr.h"
#include "asterisk/config.h"
#include "asterisk/term.h"
#include "asterisk/manager.h"
#include "asterisk/ast_expr.h"
#include "asterisk/linkedlists.h"
#define	SAY_STUBS	/* generate declarations and stubs for say methods */
#include "asterisk/say.h"
#include "asterisk/utils.h"
#include "asterisk/causes.h"
#include "asterisk/musiconhold.h"
#include "asterisk/app.h"
#include "asterisk/compat.h"
#include "asterisk/stringfields.h"
/*!
 * \note I M P O R T A N T :
Mark Spencer's avatar
Mark Spencer committed
 *
 *		The speed of extension handling will likely be among the most important
 * aspects of this PBX.  The switching scheme as it exists right now isn't
 * terribly bad (it's O(N+M), where N is the # of extensions and M is the avg #
 * of priorities, but a constant search time here would be great ;-) 
 *
 */

#ifdef LOW_MEMORY
#define EXT_DATA_SIZE 256
#else
#define EXT_DATA_SIZE 8192
#endif
#define VAR_BUF_SIZE 4096
#define	VAR_NORMAL		1
#define	VAR_SOFTTRAN	2
#define	VAR_HARDTRAN	3

#define BACKGROUND_SKIP		(1 << 0)
#define BACKGROUND_NOANSWER	(1 << 1)
#define BACKGROUND_MATCHEXTEN	(1 << 2)
#define BACKGROUND_PLAYBACK	(1 << 3)
AST_APP_OPTIONS(background_opts, {
	AST_APP_OPTION('s', BACKGROUND_SKIP),
	AST_APP_OPTION('n', BACKGROUND_NOANSWER),
	AST_APP_OPTION('m', BACKGROUND_MATCHEXTEN),
	AST_APP_OPTION('p', BACKGROUND_PLAYBACK),
AST_APP_OPTIONS(waitexten_opts, {
	AST_APP_OPTION_ARG('m', WAITEXTEN_MOH, 1),
Mark Spencer's avatar
Mark Spencer committed
struct ast_context;

Russell Bryant's avatar
Russell Bryant committed
/*!
   \brief ast_exten: An extension 
	The dialplan is saved as a linked list with each context
	having it's own linked list of extensions - one item per
	priority.
*/
Mark Spencer's avatar
Mark Spencer committed
struct ast_exten {
Russell Bryant's avatar
Russell Bryant committed
	char *exten;			/*!< Extension name */
	int matchcid;			/*!< Match caller id ? */
	const char *cidmatch;		/*!< Caller id to match for this extension */
Russell Bryant's avatar
Russell Bryant committed
	int priority;			/*!< Priority */
Russell Bryant's avatar
Russell Bryant committed
	struct ast_context *parent;	/*!< The context this extension belongs to  */
	const char *app; 		/*!< Application to execute */
Russell Bryant's avatar
Russell Bryant committed
	void *data;			/*!< Data to use (arguments) */
	void (*datad)(void *);		/*!< Data destructor */
	struct ast_exten *peer;		/*!< Next higher priority with our extension */
	const char *registrar;		/*!< Registrar */
	struct ast_exten *next;		/*!< Extension with a greater ID */
/*! \brief ast_include: include= support in extensions.conf */
Mark Spencer's avatar
Mark Spencer committed
struct ast_include {
	const char *name;		
	const char *rname;			/*!< Context to include */
Russell Bryant's avatar
Russell Bryant committed
	const char *registrar;			/*!< Registrar */
	int hastime;				/*!< If time construct exists */
	struct ast_timing timing;               /*!< time construct */
	struct ast_include *next;		/*!< Link them together */
/*! \brief ast_sw: Switch statement in extensions.conf */
Mark Spencer's avatar
Mark Spencer committed
struct ast_sw {
Russell Bryant's avatar
Russell Bryant committed
	const char *registrar;			/*!< Registrar */
	char *data;				/*!< Data load */
Russell Bryant's avatar
Russell Bryant committed
	struct ast_sw *next;			/*!< Link them together */
/*! \brief ast_ignorepat: Ignore patterns in dial plan */
Mark Spencer's avatar
Mark Spencer committed
struct ast_ignorepat {
	const char *registrar;
Mark Spencer's avatar
Mark Spencer committed
	struct ast_ignorepat *next;
/*! \brief ast_context: An extension context */
Mark Spencer's avatar
Mark Spencer committed
struct ast_context {
	ast_mutex_t lock; 			/*!< A lock to prevent multiple threads from clobbering the context */
	struct ast_exten *root;			/*!< The root of the list of extensions */
	struct ast_context *next;		/*!< Link them together */
	struct ast_include *includes;		/*!< Include other contexts */
	struct ast_ignorepat *ignorepats;	/*!< Patterns for which to continue playing dialtone */
	const char *registrar;			/*!< Registrar */
	struct ast_sw *alts;			/*!< Alternative switches */
	char name[0];				/*!< Name of the context */
/*! \brief ast_app: A registered application */
Mark Spencer's avatar
Mark Spencer committed
struct ast_app {
	int (*execute)(struct ast_channel *chan, void *data);
Russell Bryant's avatar
Russell Bryant committed
	const char *synopsis;			/*!< Synopsis text for 'show applications' */
	const char *description;		/*!< Description (help text) for 'show application <name>' */
	struct ast_app *next;			/*!< Next app in list */
	struct module *module;			/*!< Module this app belongs to */
Russell Bryant's avatar
Russell Bryant committed
	char name[0];				/*!< Name of the application */
/*! \brief ast_state_cb: An extension state notify register item */
Russell Bryant's avatar
Russell Bryant committed
	int id;
	void *data;
	ast_state_cb_type callback;
	struct ast_state_cb *next;
/*! \brief Structure for dial plan hints

  Hints are pointers from an extension in the dialplan to one or
  more devices (tech/name) */
	struct ast_exten *exten;	/*!< Extension */
	int laststate; 			/*!< Last known state */
	struct ast_state_cb *callbacks;	/*!< Callback list for this extension */
	AST_LIST_ENTRY(ast_hint) list;	/*!< Pointer to next hint in list */
static const struct cfextension_states {
	int extension_state;
	const char * const text;
} extension_states[] = {
	{ AST_EXTENSION_NOT_INUSE,                     "Idle" },
	{ AST_EXTENSION_INUSE,                         "InUse" },
	{ AST_EXTENSION_BUSY,                          "Busy" },
	{ AST_EXTENSION_UNAVAILABLE,                   "Unavailable" },
	{ AST_EXTENSION_RINGING,                       "Ringing" },
	{ AST_EXTENSION_INUSE | AST_EXTENSION_RINGING, "InUse&Ringing" }
};

int ast_pbx_outgoing_cdr_failed(void);
Mark Spencer's avatar
Mark Spencer committed
static int pbx_builtin_answer(struct ast_channel *, void *);
static int pbx_builtin_goto(struct ast_channel *, void *);
static int pbx_builtin_hangup(struct ast_channel *, void *);
static int pbx_builtin_background(struct ast_channel *, void *);
static int pbx_builtin_wait(struct ast_channel *, void *);
static int pbx_builtin_waitexten(struct ast_channel *, void *);
static int pbx_builtin_resetcdr(struct ast_channel *, void *);
static int pbx_builtin_setamaflags(struct ast_channel *, void *);
Mark Spencer's avatar
Mark Spencer committed
static int pbx_builtin_ringing(struct ast_channel *, void *);
Mark Spencer's avatar
Mark Spencer committed
static int pbx_builtin_progress(struct ast_channel *, void *);
Mark Spencer's avatar
Mark Spencer committed
static int pbx_builtin_congestion(struct ast_channel *, void *);
static int pbx_builtin_busy(struct ast_channel *, void *);
static int pbx_builtin_setglobalvar(struct ast_channel *, void *);
static int pbx_builtin_noop(struct ast_channel *, void *);
Mark Spencer's avatar
Mark Spencer committed
static int pbx_builtin_gotoif(struct ast_channel *, void *);
static int pbx_builtin_gotoiftime(struct ast_channel *, void *);
static int pbx_builtin_execiftime(struct ast_channel *, void *);
Mark Spencer's avatar
Mark Spencer committed
static int pbx_builtin_saynumber(struct ast_channel *, void *);
static int pbx_builtin_saydigits(struct ast_channel *, void *);
static int pbx_builtin_saycharacters(struct ast_channel *, void *);
static int pbx_builtin_sayphonetic(struct ast_channel *, void *);
int pbx_builtin_setvar(struct ast_channel *, void *);
static int pbx_builtin_importvar(struct ast_channel *, void *);
AST_MUTEX_DEFINE_STATIC(globalslock);
static struct varshead globals;
Mark Spencer's avatar
Mark Spencer committed
static int autofallthrough = 0;

Mark Spencer's avatar
Mark Spencer committed
AST_MUTEX_DEFINE_STATIC(maxcalllock);
static int countcalls = 0;

AST_MUTEX_DEFINE_STATIC(acflock); 		/*!< Lock for the custom function list */
static struct ast_custom_function *acf_root = NULL;
/*! \brief Declaration of builtin applications */
Mark Spencer's avatar
Mark Spencer committed
static struct pbx_builtin {
	char name[AST_MAX_APP];
	int (*execute)(struct ast_channel *chan, void *data);
Mark Spencer's avatar
Mark Spencer committed
	char *synopsis;
	char *description;
Mark Spencer's avatar
Mark Spencer committed
} builtins[] = 
{
	/* These applications are built into the PBX core and do not
	   need separate modules */
Mark Spencer's avatar
Mark Spencer committed
	{ "Answer", pbx_builtin_answer, 
	"Answer a channel if ringing", 
	"  Answer([delay]): If the call has not been answered, this application will\n"
	"answer it. Otherwise, it has no effect on the call. If a delay is specified,\n"
	"Asterisk will wait this number of milliseconds before answering the call.\n"
	{ "BackGround", pbx_builtin_background,
	"Play a file while awaiting extension",
	"  Background(filename1[&filename2...][|options[|langoverride][|context]]):\n"
	"This application will play the given list of files while waiting for an\n"
	"extension to be dialed by the calling channel. To continue waiting for digits\n"
	"after this application has finished playing files, the WaitExten application\n"
	"should be used. The 'langoverride' option explicity specifies which language\n"
	"to attempt to use for the requested sound files. If a 'context' is specified,\n"
	"this is the dialplan context that this application will use when exiting to a\n"
	"dialed extension."
	"  If one of the requested sound files does not exist, call processing will be\n"
	"terminated.\n"
	"    s - causes the playback of the message to be skipped\n"
	"          if the channel is not in the 'up' state (i.e. it\n"
	"          hasn't been answered yet.) If this happens, the\n"
	"          application will return immediately.\n"
	"    n - don't answer the channel before playing the files\n"
	"    m - only break if a digit hit matches a one digit\n"
	"          extension in the destination context\n"
	"Indicate the Busy condition",
	"  Busy([timeout]): This application will indicate the busy condition to\n"
	"the calling channel. If the optional timeout is specified, the calling channel\n"
	"will be hung up after the specified number of seconds. Otherwise, this\n"
	"application will wait until the calling channel hangs up.\n"
	"Indicate the Congestion condition",
	"  Congestion([timeout]): This application will indicate the congenstion\n"
	"condition to the calling channel. If the optional timeout is specified, the\n"
	"calling channel will be hung up after the specified number of seconds.\n"
	"Otherwise, this application will wait until the calling channel hangs up.\n"
	"Jump to a particular priority, extension, or context",
	"  Goto([[context|]extension|]priority): This application will cause the\n"
	"calling channel to continue dialplan execution at the specified priority.\n"
	"If no specific extension, or extension and context, are specified, then this\n"
	"application will jump to the specified priority of the current extension.\n"
	"  If the attempt to jump to another location in the dialplan is not successful,\n"
	"then the channel will continue at the next priority of the current extension.\n"
	"Conditional goto",
	"  GotoIf(condition?[labeliftrue]:[labeliffalse]): This application will cause\n"
	"the calling channel to jump to the specified location in the dialplan based on\n"
	"the evaluation of the given condition. The channel will continue at\n"
	"'labeliftrue' if the condition is true, or 'labeliffalse' if the condition is\n"
	"false. The labels are specified with the same syntax as used within the Goto\n"
	"application.  If the label chosen by the condition is omitted, no jump is\n"
	"performed, but execution continues with the next priority in the dialplan.\n"
	{ "GotoIfTime", pbx_builtin_gotoiftime,
	"Conditional Goto based on the current time",
	"  GotoIfTime(<times>|<weekdays>|<mdays>|<months>?[[context|]exten|]priority):\n"
	"This application will have the calling channel jump to the speicified location\n"
	"int the dialplan if the current time matches the given time specification.\n"
	"Further information on the time specification can be found in examples\n"
	"illustrating how to do time-based context includes in the dialplan.\n" 

	{ "ExecIfTime", pbx_builtin_execiftime,
	"Conditional application execution based on the current time",
	"  ExecIfTime(<times>|<weekdays>|<mdays>|<months>?appname[|appargs]):\n"
	"This application will execute the specified dialplan application, with optional\n"
	"arguments, if the current time matches the given time specification. Further\n"
	"information on the time speicification can be found in examples illustrating\n"
	"how to do time-based context includes in the dialplan.\n"
	"Hang up the calling channel",
	"  Hangup(): This application will hang up the calling channel.\n"
	"Do Nothing",
	"  NoOp(): This applicatiion does nothing. However, it is useful for debugging\n"
	"purposes. Any text that is provided as arguments to this application can be\n"
	"viewed at the Asterisk CLI. This method can be used to see the evaluations of\n"
	"variables or functions without having any effect." 
Mark Spencer's avatar
Mark Spencer committed
	{ "Progress", pbx_builtin_progress,
	"Indicate progress",
	"  Progress(): This application will request that in-band progress information\n"
	"be provided to the calling channel.\n"
	{ "ResetCDR", pbx_builtin_resetcdr,
	"Resets the Call Data Record",
	"  ResetCDR([options]):  This application causes the Call Data Record to be\n"
	"reset.\n"
	"  Options:\n"
	"    w -- Store the current CDR record before resetting it.\n"
	"    a -- Store any stacked records.\n"
	"    v -- Save CDR variables.\n"
Mark Spencer's avatar
Mark Spencer committed
	{ "Ringing", pbx_builtin_ringing,
	"Indicate ringing tone",
	"  Ringing(): This application will request that the channel indicate a ringing\n"
	"tone to the user.\n"
	"Say Number",
	"  SayNumber(digits[,gender]): This application will play the sounds that\n"
	"correspond to the given number. Optionally, a gender may be specified.\n"
	"This will use the language that is currently set for the channel. See the\n"
	"LANGUAGE function for more information on setting the language for the channel.\n"	
	"Say Digits",
	"  SayDigits(digits): This application will play the sounds that correspond\n"
	"to the digits of the given number. This will use the language that is currently\n"
	"set for the channel. See the LANGUAGE function for more information on setting\n"
	"the language for the channel.\n"
	{ "SayAlpha", pbx_builtin_saycharacters,
	"Say Alpha",
	"  SayAlpha(string): This application will play the sounds that correspond to\n"
	"the letters of the given string.\n" 

	{ "SayPhonetic", pbx_builtin_sayphonetic,
	"Say Phonetic",
	"  SayPhonetic(string): This application will play the sounds from the phonetic\n"
	"alphabet that correspond to the letters in the given string.\n"
	{ "SetAMAFlags", pbx_builtin_setamaflags,
	"Set the AMA Flags",
	"  SetAMAFlags([flag]): This channel will set the channel's AMA Flags for billing\n"
	"purposes.\n"
	{ "SetGlobalVar", pbx_builtin_setglobalvar,
	"Set a global variable to a given value",
	"  SetGlobalVar(variable=value): This application sets a given global variable to\n"
	"the specified value.\n"
	{ "Set", pbx_builtin_setvar,
	"Set channel variable(s) or function value(s)",
	"  Set(name1=value1|name2=value2|..[|options])\n"
	"This function can be used to set the value of channel variables or dialplan\n"
	"functions. It will accept up to 24 name/value pairs. When setting variables,\n"
	"if the variable name is prefixed with _, the variable will be inherited into\n"
	"channels created from the current channel. If the variable name is prefixed\n"
	"with __, the variable will be inherited into channels created from the current\n"
	"channel and all children channels.\n"
	"  Options:\n" 
	"    g - Set variable globally instead of on the channel\n"
	"        (applies only to variables, not functions)\n"
	{ "ImportVar", pbx_builtin_importvar,
	"Import a variable from a channel into a new variable",
	"  ImportVar(newvar=channelname|variable): This application imports a variable\n"
	"from the specified channel (as opposed to the current one) and stores it as\n"
	"a variable in the current channel (the channel that is calling this\n"
	"application). Variables created by this application have the same inheritance\n"
	"properties as those created with the Set application. See the documentation for\n"
	"Set for more information.\n"
	"Waits for some time", 
	"  Wait(seconds): This application waits for a specified number of seconds.\n"
	"Then, dialplan execution will continue at the next priority.\n"
	"  Note that the seconds can be passed with fractions of a second. For example,\n"
	"'1.5' will ask the application to wait for 1.5 seconds.\n" 

	{ "WaitExten", pbx_builtin_waitexten, 
	"Waits for an extension to be entered", 
	"  WaitExten([seconds][|options]): This application waits for the user to enter\n"
	"a new extension for a specified number of seconds.\n"
	"  Note that the seconds can be passed with fractions of a second. For example,\n"
	"'1.5' will ask the application to wait for 1.5 seconds.\n" 
	"    m[(x)] - Provide music on hold to the caller while waiting for an extension.\n"
	"               Optionally, specify the class for music on hold within parenthesis.\n"
Mark Spencer's avatar
Mark Spencer committed
};

static struct ast_context *contexts = NULL;
Russell Bryant's avatar
Russell Bryant committed
AST_MUTEX_DEFINE_STATIC(conlock); 		/*!< Lock for the ast_context list */
Mark Spencer's avatar
Mark Spencer committed
static struct ast_app *apps = NULL;
Russell Bryant's avatar
Russell Bryant committed
AST_MUTEX_DEFINE_STATIC(applock); 		/*!< Lock for the application list */
Mark Spencer's avatar
Mark Spencer committed
struct ast_switch *switches = NULL;
Russell Bryant's avatar
Russell Bryant committed
AST_MUTEX_DEFINE_STATIC(switchlock);		/*!< Lock for switches */
/* WARNING:
   When holding this list's lock, do _not_ do anything that will cause conlock
   to be taken, unless you _already_ hold it. The ast_merge_contexts_and_delete
   function will take the locks in conlock/hints order, so any other
   paths that require both locks must also take them in that order.
*/
static AST_LIST_HEAD_STATIC(hints, ast_hint);
struct ast_state_cb *statecbs = NULL;
/* 
   \note This function is special. It saves the stack so that no matter
   how many times it is called, it returns to the same place */
int pbx_exec(struct ast_channel *c, 		/*!< Channel */
		struct ast_app *app,		/*!< Application */
		void *data)			/*!< Data for execution */
Mark Spencer's avatar
Mark Spencer committed
{
	int res;
	const char *saved_c_appl;
	const char *saved_c_data;
	if (c->cdr)
		ast_cdr_setapp(c->cdr, app->name, data);
	/* save channel values */
	saved_c_appl= c->appl;
	saved_c_data= c->data;
	c->data = data;
	/* XXX remember what to to when we have linked apps to modules */
	if (app->module) {
		/* XXX LOCAL_USER_ADD(app->module) */
	}
	res = app->execute(c, data);
	if (app->module) {
		/* XXX LOCAL_USER_REMOVE(app->module) */
	}
	/* restore channel values */
	c->appl = saved_c_appl;
	c->data = saved_c_data;
/*! Go no deeper than this through includes (not counting loops) */
#define AST_PBX_MAX_STACK	128
Mark Spencer's avatar
Mark Spencer committed
#define HELPER_EXISTS 0
#define HELPER_SPAWN 1
Mark Spencer's avatar
Mark Spencer committed
#define HELPER_CANMATCH 3
Mark Spencer's avatar
Mark Spencer committed
#define HELPER_MATCHMORE 4
#define HELPER_FINDLABEL 5
/*! \brief Find application handle in linked list
 */
struct ast_app *pbx_findapp(const char *app) 
Mark Spencer's avatar
Mark Spencer committed
{
	struct ast_app *tmp;
Mark Spencer's avatar
Mark Spencer committed
		ast_log(LOG_WARNING, "Unable to obtain application lock\n");
		return NULL;
	}
Russell Bryant's avatar
Russell Bryant committed
	for (tmp = apps; tmp; tmp = tmp->next) {
Mark Spencer's avatar
Mark Spencer committed
		if (!strcasecmp(tmp->name, app))
			break;
	}
Mark Spencer's avatar
Mark Spencer committed
	return tmp;
}

static struct ast_switch *pbx_findswitch(const char *sw)
Mark Spencer's avatar
Mark Spencer committed
{
	struct ast_switch *asw;
Mark Spencer's avatar
Mark Spencer committed
		ast_log(LOG_WARNING, "Unable to obtain application lock\n");
		return NULL;
	}
Russell Bryant's avatar
Russell Bryant committed
	for (asw = switches; asw; asw = asw->next) {
Mark Spencer's avatar
Mark Spencer committed
		if (!strcasecmp(asw->name, sw))
			break;
	}
Mark Spencer's avatar
Mark Spencer committed
	return asw;
}

Mark Spencer's avatar
Mark Spencer committed
static inline int include_valid(struct ast_include *i)
{
	if (!i->hastime)
		return 1;

	return ast_check_timing(&(i->timing));
Mark Spencer's avatar
Mark Spencer committed
static void pbx_destroy(struct ast_pbx *p)
{
	free(p);
}

#define EXTENSION_MATCH_CORE(data,pattern,match) {\
	/* All patterns begin with _ */\
	if (pattern[0] != '_') \
		return 0;\
	/* Start optimistic */\
	match=1;\
	pattern++;\
	while(match && *data && *pattern && (*pattern != '/')) {\
		while (*data == '-' && (*(data+1) != '\0')) data++;\
		switch(toupper(*pattern)) {\
		case '[': \
		{\
			int i,border=0;\
			char *where;\
			match=0;\
			pattern++;\
			where=strchr(pattern,']');\
			if (where)\
				border=(int)(where-pattern);\
			if (!where || border > strlen(pattern)) {\
				ast_log(LOG_WARNING, "Wrong usage of [] in the extension\n");\
				return match;\
			}\
			for (i=0; i<border; i++) {\
				int res=0;\
				if (i+2<border)\
					if (pattern[i+1]=='-') {\
						if (*data >= pattern[i] && *data <= pattern[i+2]) {\
							res=1;\
						} else {\
							i+=2;\
							continue;\
						}\
					}\
				if (res==1 || *data==pattern[i]) {\
					match = 1;\
					break;\
				}\
			}\
			pattern+=border;\
			break;\
		}\
		case 'N':\
			if ((*data < '2') || (*data > '9'))\
				match=0;\
			break;\
		case 'X':\
			if ((*data < '0') || (*data > '9'))\
				match = 0;\
			break;\
		case 'Z':\
			if ((*data < '1') || (*data > '9'))\
				match = 0;\
			break;\
		case '.':\
			/* Must match */\
			return 1;\
		case ' ':\
		case '-':\
			/* Ignore these characters */\
			data--;\
			break;\
		default:\
			if (*data != *pattern)\
				match =0;\
		}\
		data++;\
		pattern++;\
	}\
	/* If we ran off the end of the data and the pattern ends in '!', match */\
	if (match && !*data && (*pattern == '!'))\
int ast_extension_match(const char *pattern, const char *data)
Mark Spencer's avatar
Mark Spencer committed
{
	int match;
	/* If they're the same return */
	if (!strcmp(pattern, data))
		return 1;
	EXTENSION_MATCH_CORE(data,pattern,match);
	/* Must be at the end of both */
	if (*data || (*pattern && (*pattern != '/')))
		match = 0;
Mark Spencer's avatar
Mark Spencer committed
	return match;
}

int ast_extension_close(const char *pattern, const char *data, int needmore)
Mark Spencer's avatar
Mark Spencer committed
{
	int match;
Mark Spencer's avatar
Mark Spencer committed
	/* If "data" is longer, it can'be a subset of pattern unless
	   pattern is a pattern match */
	if ((strlen(pattern) < strlen(data)) && (pattern[0] != '_'))
Mark Spencer's avatar
Mark Spencer committed
		return 0;
	
	if ((ast_strlen_zero((char *)data) || !strncasecmp(pattern, data, strlen(data))) && 
Mark Spencer's avatar
Mark Spencer committed
		(!needmore || (strlen(pattern) > strlen(data)))) {
Mark Spencer's avatar
Mark Spencer committed
		return 1;
	}
	EXTENSION_MATCH_CORE(data,pattern,match);
	/* If there's more or we don't care about more, or if it's a possible early match, 
	   return non-zero; otherwise it's a miss */
	if (!needmore || *pattern || match == 2) {
Mark Spencer's avatar
Mark Spencer committed
		return match;
	} else
		return 0;
struct ast_context *ast_context_find(const char *name)
Mark Spencer's avatar
Mark Spencer committed
{
	struct ast_context *tmp;
Mark Spencer's avatar
Mark Spencer committed
	if (name) {
Russell Bryant's avatar
Russell Bryant committed
		for (tmp = contexts; tmp; tmp = tmp->next) {
Mark Spencer's avatar
Mark Spencer committed
			if (!strcasecmp(name, tmp->name))
				break;
		}
	} else
		tmp = contexts;
Mark Spencer's avatar
Mark Spencer committed
	return tmp;
}

#define STATUS_NO_CONTEXT	1
#define STATUS_NO_EXTENSION	2
#define STATUS_NO_PRIORITY	3
#define STATUS_NO_LABEL		4
#define STATUS_SUCCESS		5
static int matchcid(const char *cidpattern, const char *callerid)
Mark Spencer's avatar
Mark Spencer committed
{
Mark Spencer's avatar
Mark Spencer committed
	int failresult;
	
	/* If the Caller*ID pattern is empty, then we're matching NO Caller*ID, so
	   failing to get a number should count as a match, otherwise not */

	if (!ast_strlen_zero(cidpattern))
Mark Spencer's avatar
Mark Spencer committed
		failresult = 0;
	else
		failresult = 1;

	if (!callerid)
		return failresult;

	return ast_extension_match(cidpattern, callerid);
static struct ast_exten *pbx_find_extension(struct ast_channel *chan, struct ast_context *bypass, const char *context, const char *exten, int priority, const char *label, const char *callerid, int action, char *incstack[], int *stacklen, int *status, struct ast_switch **swo, char **data, const char **foundcontext)
Mark Spencer's avatar
Mark Spencer committed
{
	int x, res;
Mark Spencer's avatar
Mark Spencer committed
	struct ast_context *tmp;
Mark Spencer's avatar
Mark Spencer committed
	struct ast_exten *e, *eroot;
	struct ast_include *i;
Mark Spencer's avatar
Mark Spencer committed
	struct ast_sw *sw;
	struct ast_switch *asw;
Mark Spencer's avatar
Mark Spencer committed
	/* Initialize status if appropriate */
Mark Spencer's avatar
Mark Spencer committed
	if (!*stacklen) {
Mark Spencer's avatar
Mark Spencer committed
		*status = STATUS_NO_CONTEXT;
Mark Spencer's avatar
Mark Spencer committed
		*swo = NULL;
		*data = NULL;
	}
Mark Spencer's avatar
Mark Spencer committed
	/* Check for stack overflow */
	if (*stacklen >= AST_PBX_MAX_STACK) {
		ast_log(LOG_WARNING, "Maximum PBX stack exceeded\n");
		return NULL;
	}
	/* Check first to see if we've already been checked */
Russell Bryant's avatar
Russell Bryant committed
	for (x = 0; x < *stacklen; x++) {
Mark Spencer's avatar
Mark Spencer committed
		if (!strcasecmp(incstack[x], context))
			return NULL;
	}
	if (bypass)
		tmp = bypass;
	else
		tmp = contexts;
Russell Bryant's avatar
Russell Bryant committed
	for (; tmp; tmp = tmp->next) {
Mark Spencer's avatar
Mark Spencer committed
		/* Match context */
		if (bypass || !strcmp(tmp->name, context)) {
			struct ast_exten *earlymatch = NULL;

Mark Spencer's avatar
Mark Spencer committed
			if (*status < STATUS_NO_EXTENSION)
				*status = STATUS_NO_EXTENSION;
Russell Bryant's avatar
Russell Bryant committed
			for (eroot = tmp->root; eroot; eroot = eroot->next) {
Mark Spencer's avatar
Mark Spencer committed
				/* Match extension */
Mark Spencer's avatar
Mark Spencer committed
				if ((((action != HELPER_MATCHMORE) && ast_extension_match(eroot->exten, exten)) ||
				     ((action == HELPER_CANMATCH) && (ast_extension_close(eroot->exten, exten, 0))) ||
				     ((action == HELPER_MATCHMORE) && (match = ast_extension_close(eroot->exten, exten, 1)))) &&
Russell Bryant's avatar
Russell Bryant committed
				     (!eroot->matchcid || matchcid(eroot->cidmatch, callerid))) {

					if (action == HELPER_MATCHMORE && match == 2 && !earlymatch) {
						/* It matched an extension ending in a '!' wildcard
						   So ignore it for now, unless there's a better match */
						earlymatch = eroot;
					} else {
Mark Spencer's avatar
Mark Spencer committed
						if (*status < STATUS_NO_PRIORITY)
							*status = STATUS_NO_PRIORITY;
Russell Bryant's avatar
Russell Bryant committed
						for (e = eroot; e; e = e->peer) {
Mark Spencer's avatar
Mark Spencer committed
							/* Match priority */
							if (action == HELPER_FINDLABEL) {
								if (*status < STATUS_NO_LABEL)
									*status = STATUS_NO_LABEL;
							 	if (label && e->label && !strcmp(label, e->label)) {
									*status = STATUS_SUCCESS;
									*foundcontext = context;
									return e;
								}
							} else if (e->priority == priority) {
Mark Spencer's avatar
Mark Spencer committed
								*status = STATUS_SUCCESS;
								*foundcontext = context;
Mark Spencer's avatar
Mark Spencer committed
								return e;
							}
						}
Mark Spencer's avatar
Mark Spencer committed
				}
			}
			if (earlymatch) {
				/* Bizarre logic for HELPER_MATCHMORE. We return zero to break out 
				   of the loop waiting for more digits, and _then_ match (normally)
				   the extension we ended up with. We got an early-matching wildcard
				   pattern, so return NULL to break out of the loop. */
				return NULL;
Mark Spencer's avatar
Mark Spencer committed
			}
Mark Spencer's avatar
Mark Spencer committed
			/* Check alternative switches */
Russell Bryant's avatar
Russell Bryant committed
			for (sw = tmp->alts; sw; sw = sw->next) {
Mark Spencer's avatar
Mark Spencer committed
				if ((asw = pbx_findswitch(sw->name))) {
					/* Substitute variables now */
					if (sw->eval) 
						pbx_substitute_variables_helper(chan, sw->data, sw->tmpdata, SWITCH_DATA_LENGTH - 1);
Mark Spencer's avatar
Mark Spencer committed
					if (action == HELPER_CANMATCH)
						res = asw->canmatch ? asw->canmatch(chan, context, exten, priority, callerid, sw->eval ? sw->tmpdata : sw->data) : 0;
Mark Spencer's avatar
Mark Spencer committed
					else if (action == HELPER_MATCHMORE)
						res = asw->matchmore ? asw->matchmore(chan, context, exten, priority, callerid, sw->eval ? sw->tmpdata : sw->data) : 0;
Mark Spencer's avatar
Mark Spencer committed
					else
						res = asw->exists ? asw->exists(chan, context, exten, priority, callerid, sw->eval ? sw->tmpdata : sw->data) : 0;
Mark Spencer's avatar
Mark Spencer committed
					if (res) {
						/* Got a match */
						*swo = asw;
						*data = sw->eval ? sw->tmpdata : sw->data;
						*foundcontext = context;
Mark Spencer's avatar
Mark Spencer committed
						return NULL;
					}
				} else {
					ast_log(LOG_WARNING, "No such switch '%s'\n", sw->name);
				}
			}
Mark Spencer's avatar
Mark Spencer committed
			/* Setup the stack */
			incstack[*stacklen] = tmp->name;
			(*stacklen)++;
			/* Now try any includes we have in this context */
Russell Bryant's avatar
Russell Bryant committed
			for (i = tmp->includes; i; i = i->next) {
Mark Spencer's avatar
Mark Spencer committed
				if (include_valid(i)) {
					if ((e = pbx_find_extension(chan, bypass, i->rname, exten, priority, label, callerid, action, incstack, stacklen, status, swo, data, foundcontext))) 
Mark Spencer's avatar
Mark Spencer committed
						return e;
					if (*swo) 
						return NULL;
				}
Mark Spencer's avatar
Mark Spencer committed
			}
Mark Spencer's avatar
Mark Spencer committed
		}
	}
	return NULL;
}

/* Note that it's negative -- that's important later. */
#define DONT_HAVE_LENGTH	0x80000000

/*! \brief extract offset:length from variable name.
 * Returns 1 if there is a offset:length part, which is
 * trimmed off (values go into variables)
 */
static int parse_variable_name(char *var, int *offset, int *length, int *isfunc)
{
	int parens=0;

	*offset = 0;
	*length = DONT_HAVE_LENGTH;
	*isfunc = 0;
	for (; *var; var++) {
		if (*var == '(') {
		} else if (*var == ':' && parens == 0) {
			*var++ = '\0';
			sscanf(var, "%d:%d", offset, length);
			return 1; /* offset:length valid */
/*! \brief takes a substring. It is ok to call with value == workspace.
 *
 * offset < 0 means start from the end of the string and set the beginning
 *   to be that many characters back.
 * length is the length of the substring, -1 means unlimited
 * (we take any negative value).
 * Always return a copy in workspace.
 */
static char *substring(const char *value, int offset, int length, char *workspace, size_t workspace_len)
	int lr;	/* length of the input string after the copy */
	ast_copy_string(workspace, value, workspace_len); /* always make a copy */
	if (offset == 0 && length < 0)	/* take the whole string */
		return ret;
	lr = strlen(ret); /* compute length after copy, so we never go out of the workspace */
	if (offset < 0)	{	/* translate negative offset into positive ones */
		offset = lr + offset;
		if (offset < 0) /* If the negative offset was greater than the length of the string, just start at the beginning */
			offset = 0;
	/* too large offset result in empty string so we know what to return */
	if (offset >= lr)
		return ret + lr;	/* the final '\0' */
	ret += offset;		/* move to the start position */
	if (length >= 0 && length < lr - offset)	/* truncate if necessary */
/*! \brief  pbx_retrieve_variable: Support for Asterisk built-in variables and
      functions in the dialplan
  ---*/
void pbx_retrieve_variable(struct ast_channel *c, const char *var, char **ret, char *workspace, int workspacelen, struct varshead *headp)
	const char *s;	/* the result */
	int offset, length;
	int i, need_substring;
	struct varshead *places[2] = { headp, &globals };	/* list of places where we may look */

	if (c) {
		places[0] = &c->varshead;
	}
	/*
	 * Make a copy of var because parse_variable_name() modifies the string.
	 * Then if called directly, we might need to run substring() on the result;
	 * remember this for later in 'need_substring', 'offset' and 'length'
	 */
	tmpvar = ast_strdupa(var);	/* parse_variable_name modifies the string */
	need_substring = parse_variable_name(tmpvar, &offset, &length, &i /* ignored */);

	/*
	 * Look first into predefined variables, then into variable lists.
	 * Variable 's' points to the result, according to the following rules:
	 * s == &not_found (set at the beginning) means that we did not find a
	 *	matching variable and need to look into more places.
	 * If s != &not_found, s is a valid result string as follows:
	 * s = NULL if the variable does not have a value;
	 *	you typically do this when looking for an unset predefined variable.
	 * s = workspace if the result has been assembled there;
	 *	typically done when the result is built e.g. with an snprintf(),
	 *	so we don't need to do an additional copy.
	 * s != workspace in case we have a string, that needs to be copied
	 *	(the ast_copy_string is done once for all at the end).
	 *	Typically done when the result is already available in some string.
	 */
	s = &not_found;	/* default value */
	if (c) {	/* This group requires a valid channel */
		/* Names with common parts are looked up a piece at a time using strncmp. */
		if (!strncmp(var, "CALL", 4)) {
			if (!strncmp(var + 4, "ING", 3)) {
				if (!strcmp(var + 7, "PRES")) {			/* CALLINGPRES */
					snprintf(workspace, workspacelen, "%d", c->cid.cid_pres);
					s = workspace;
				} else if (!strcmp(var + 7, "ANI2")) {		/* CALLINGANI2 */
					snprintf(workspace, workspacelen, "%d", c->cid.cid_ani2);
					s = workspace;
				} else if (!strcmp(var + 7, "TON")) {		/* CALLINGTON */
					snprintf(workspace, workspacelen, "%d", c->cid.cid_ton);
					s = workspace;
				} else if (!strcmp(var + 7, "TNS")) {		/* CALLINGTNS */
					snprintf(workspace, workspacelen, "%d", c->cid.cid_tns);
					s = workspace;
		} else if (!strcmp(var, "HINT")) {
			s = ast_get_hint(workspace, workspacelen, NULL, 0, c, c->context, c->exten) ? workspace : NULL;
		} else if (!strcmp(var, "HINTNAME")) {
			s = ast_get_hint(NULL, 0, workspace, workspacelen, c, c->context, c->exten) ? workspace : NULL;
		} else if (!strcmp(var, "EXTEN")) {
			s = c->exten;
		} else if (!strcmp(var, "CONTEXT")) {
			s = c->context;
		} else if (!strcmp(var, "PRIORITY")) {
			snprintf(workspace, workspacelen, "%d", c->priority);
			s = workspace;
		} else if (!strcmp(var, "CHANNEL")) {
			s = c->name;
		} else if (!strcmp(var, "UNIQUEID")) {
			s = c->uniqueid;
		} else if (!strcmp(var, "HANGUPCAUSE")) {
			snprintf(workspace, workspacelen, "%d", c->hangupcause);
			s = workspace;
	}
	if (s == &not_found) { /* look for more */
		if (!strcmp(var, "EPOCH")) {
			snprintf(workspace, workspacelen, "%u",(int)time(NULL));
			s = workspace;
		} else if (!strcmp(var, "SYSTEMNAME")) {
		}
	}
	/* if not found, look into chanvars or global vars */
	for (i = 0; s == &not_found && i < (sizeof(places) / sizeof(places[0])); i++) {
		struct ast_var_t *variables;
		if (!places[i])
			continue;
		if (places[i] == &globals)
			ast_mutex_lock(&globalslock);