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.
Luigi Rizzo's avatar
Luigi Rizzo committed
 * \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 #
Luigi Rizzo's avatar
Luigi Rizzo committed
 * 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
/*!
Luigi Rizzo's avatar
Luigi Rizzo 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 {
Luigi Rizzo's avatar
Luigi Rizzo committed
	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 */
/*! \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 */
	AST_LIST_HEAD_NOLOCK(, 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' */
Kevin P. Fleming's avatar
Kevin P. Fleming committed
	const char *description;		/*!< Description (help text) for 'show application &lt;name&gt;' */
	AST_LIST_ENTRY(ast_app) list;		/*!< 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;

static AST_LIST_HEAD_STATIC(acf_root, ast_custom_function);
/*! \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;
Luigi Rizzo's avatar
Luigi Rizzo committed
} builtins[] =
Mark Spencer's avatar
Mark Spencer committed
{
	/* These applications are built into the PBX core and do not
	   need separate modules */
Luigi Rizzo's avatar
Luigi Rizzo 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 an audio file while waiting for digits of an extension to go to.\n",
	"  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 explicitly 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",
Olle Johansson's avatar
Olle Johansson committed
	"  Congestion([timeout]): This application will indicate the congestion\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"
Luigi Rizzo's avatar
Luigi Rizzo committed
	{ "Goto", pbx_builtin_goto,
	"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 specified location\n"
	"in the dialplan if the current time matches the given time specification.\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.\n"
	"Hang up the calling channel",
	"  Hangup([causecode]): This application will hang up the calling channel.\n"
	"If a causecode is given the channel's hangup cause will be set to the given\n"
	"value.\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"
Luigi Rizzo's avatar
Luigi Rizzo committed
	"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"
Luigi Rizzo's avatar
Luigi Rizzo committed
	"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"
Luigi Rizzo's avatar
Luigi Rizzo committed
	"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 application will set the channel's AMA Flags for\n"
 	"  billing 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"
Luigi Rizzo's avatar
Luigi Rizzo committed
	"  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"
Luigi Rizzo's avatar
Luigi Rizzo committed
	{ "Wait", pbx_builtin_wait,
	"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"
Luigi Rizzo's avatar
Luigi Rizzo committed
	"'1.5' will ask the application to wait for 1.5 seconds.\n"
Luigi Rizzo's avatar
Luigi Rizzo committed
	{ "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"
Luigi Rizzo's avatar
Luigi Rizzo committed
	"'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 */
static AST_LIST_HEAD_STATIC(apps, ast_app);
static AST_LIST_HEAD_STATIC(switches, ast_switch);
/* 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
/*! \brief Find application handle in linked list
 */
Luigi Rizzo's avatar
Luigi Rizzo committed
struct ast_app *pbx_findapp(const char *app)
Mark Spencer's avatar
Mark Spencer committed
{
	struct ast_app *tmp;
	AST_LIST_LOCK(&apps);
	AST_LIST_TRAVERSE(&apps, tmp, list) {
Mark Spencer's avatar
Mark Spencer committed
		if (!strcasecmp(tmp->name, app))
			break;
	}
Luigi Rizzo's avatar
Luigi Rizzo committed
	AST_LIST_UNLOCK(&apps);

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;
	AST_LIST_LOCK(&switches);
	AST_LIST_TRAVERSE(&switches, asw, list) {
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);
}

/*
 * Special characters used in patterns:
 *	'_'	underscore is the leading character of a pattern.
 *		In other position it is treated as a regular char.
 *	' ' '-'	space and '-' are separator and ignored.
 *	.	one or more of any character. Only allowed at the end of
 *		a pattern.
 *	!	zero or more of anything. Also impacts the result of CANMATCH
 *		and MATCHMORE. Only allowed at the end of a pattern.
 *		In the core routine, ! causes a match with a return code of 2.
 *		In turn, depending on the search mode: (XXX check if it is implemented)
 *		- E_MATCH retuns 1 (does match)
 *		- E_MATCHMORE returns 0 (no match)
 *		- E_CANMATCH returns 1 (does match)
 *
 *	/	should not appear as it is considered the separator of the CID info.
 *		XXX at the moment we may stop on this char.
 *
 *	X Z N	match ranges 0-9, 1-9, 2-9 respectively.
 *	[	denotes the start of a set of character. Everything inside
 *		is considered literally. We can have ranges a-d and individual
 *		characters. A '[' and '-' can be considered literally if they
 *		are just before ']'.
 *		XXX currently there is no way to specify ']' in a range, nor \ is
 *		considered specially.
 *
 * When we compare a pattern with a specific extension, all characters in the extension
 * itself are considered literally with the only exception of '-' which is considered
 * as a separator and thus ignored.
 * XXX do we want to consider space as a separator as well ?
 * XXX do we want to consider the separators in non-patterns as well ?
 */

/*!
 * \brief helper functions to sort extensions and patterns in the desired way,
 * so that more specific patterns appear first.
 *
 * ext_cmp1 compares individual characters (or sets of), returning
 * an int where bits 0-7 are the ASCII code of the first char in the set,
 * while bit 8-15 are the cardinality of the set minus 1.
 * This way more specific patterns (smaller cardinality) appear first.
 * Wildcards have a special value, so that we can directly compare them to
 * sets by subtracting the two values. In particular:
 * 	0x000xx		one character, xx
 * 	0x0yyxx		yy character set starting with xx
 * 	0x10000		'.' (one or more of anything)
 * 	0x20000		'!' (zero or more of anything)
 * 	0x30000		NUL (end of string)
 * 	0x40000		error in set.
 * The pointer to the string is advanced according to needs.
 * NOTES:
 *	1. the empty set is equivalent to NUL.
 *	2. given that a full set has always 0 as the first element,
 *	   we could encode the special cases as 0xffXX where XX
 *	   is 1, 2, 3, 4 as used above.
 */
static int ext_cmp1(const char **p)
{
	uint32_t chars[8];
	int c, cmin = 0xff, count = 0;
	const char *end;

	/* load, sign extend and advance pointer until we find
	 * a valid character.
	 */
	while ( (c = *(*p)++) && (c == ' ' || c == '-') )
		;	/* ignore some characters */

	/* always return unless we have a set of chars */
	switch (c) {
	default:	/* ordinary character */
		return 0x0000 | (c & 0xff);

	case 'N':	/* 2..9 */
		return 0x0700 | '2' ;

	case 'X':	/* 0..9 */
		return 0x0900 | '0';

	case 'Z':	/* 1..9 */
		return 0x0800 | '1';

	case '.':	/* wildcard */
		return 0x10000;

	case '!':	/* earlymatch */
		return 0x20000;	/* less specific than NULL */

	case '\0':	/* empty string */
		*p = NULL;
		return 0x30000;

	case '[':	/* pattern */
		break;
	}
	/* locate end of set */
	end = strchr(*p, ']');	

	if (end == NULL) {
		ast_log(LOG_WARNING, "Wrong usage of [] in the extension\n");
		return 0x40000;	/* XXX make this entry go last... */
	}

	bzero(chars, sizeof(chars));	/* clear all chars in the set */
	for (; *p < end  ; (*p)++) {
		unsigned char c1, c2;	/* first-last char in range */
		c1 = (unsigned char)((*p)[0]);
		if (*p + 2 < end && (*p)[1] == '-') { /* this is a range */
			c2 = (unsigned char)((*p)[2]);
			*p += 2;	/* skip a total of 3 chars */
		} else			/* individual character */
			c2 = c1;
		if (c1 < cmin)
			cmin = c1;
		for (; c1 <= c2; c1++) {
			uint32_t mask = 1 << (c1 % 32);
			if ( (chars[ c1 / 32 ] & mask) == 0)
				count += 0x100;
			chars[ c1 / 32 ] |= mask;
		}
	}
	(*p)++;
	return count == 0 ? 0x30000 : (count | cmin);
}

/*!
 * \brief the full routine to compare extensions in rules.
 */
static int ext_cmp(const char *a, const char *b)
{
	/* make sure non-patterns come first.
	 * If a is not a pattern, it either comes first or
	 * we use strcmp to compare the strings.
	 */
	int ret = 0;

	if (a[0] != '_')
		return (b[0] == '_') ? -1 : strcmp(a, b);

	/* Now we know a is a pattern; if b is not, a comes first */
	if (b[0] != '_')
		return 1;
#if 0	/* old mode for ext matching */
	return strcmp(a, b);
#endif
	/* ok we need full pattern sorting routine */
	while (!ret && a && b)
		ret = ext_cmp1(&a) - ext_cmp1(&b);
	if (ret == 0)
		return 0;
	else
		return (ret > 0) ? 1 : -1;
}

/*!
 * When looking up extensions, we can have different requests
 * identified by the 'action' argument, as follows.
 * Note that the coding is such that the low 4 bits are the
 * third argument to extension_match_core.
 */
enum ext_match_t {
	E_MATCHMORE = 	0x00,	/* extension can match but only with more 'digits' */
	E_CANMATCH =	0x01,	/* extension can match with or without more 'digits' */
	E_MATCH =	0x02,	/* extension is an exact match */
	E_MATCH_MASK =	0x03,	/* mask for the argument to extension_match_core() */
	E_SPAWN =	0x12,	/* want to spawn an extension. Requires exact match */
	E_FINDLABEL =	0x22	/* returns the priority for a given label. Requires exact match */
};

/*
 * Internal function for ast_extension_{match|close}
 * return 0 on no-match, 1 on match, 2 on early match.
 * mode is as follows:
 *	E_MATCH		success only on exact match
 *	E_MATCHMORE	success only on partial match (i.e. leftover digits in pattern)
 *	E_CANMATCH	either of the above.
 */
static int _extension_match_core(const char *pattern, const char *data, enum ext_match_t mode)
{
	mode &= E_MATCH_MASK;	/* only consider the relevant bits */

	if (pattern[0] != '_') { /* not a pattern, try exact or partial match */
		int ld = strlen(data), lp = strlen(pattern);

		if (lp < ld)		/* pattern too short, cannot match */
			return 0;
		/* depending on the mode, accept full or partial match or both */
		if (mode == E_MATCH)
			return !strcmp(pattern, data); /* 1 on match, 0 on fail */
		if (ld == 0 || !strncasecmp(pattern, data, ld)) /* partial or full match */
			return (mode == E_MATCHMORE) ? lp > ld : 1; /* XXX should consider '!' and '/' ? */
		else
			return 0;
	}
	pattern++; /* skip leading _ */
	/*
	 * XXX below we stop at '/' which is a separator for the CID info. However we should
	 * not store '/' in the pattern at all. When we insure it, we can remove the checks.
	 */
	while (*data && *pattern && *pattern != '/') {
		const char *end;

		if (*data == '-') { /* skip '-' in data (just a separator) */
			data++;
			continue;
		}
		switch (toupper(*pattern)) {
		case '[':	/* a range */
			end = strchr(pattern+1, ']'); /* XXX should deal with escapes ? */
			if (end == NULL) {
				ast_log(LOG_WARNING, "Wrong usage of [] in the extension\n");
				return 0;	/* unconditional failure */
			}
			for (pattern++; pattern != end; pattern++) {
				if (pattern+2 < end && pattern[1] == '-') { /* this is a range */
					if (*data >= pattern[0] && *data <= pattern[2])
						break;	/* match found */
					else {
						pattern += 2; /* skip a total of 3 chars */
						continue;
					}
				} else if (*data == pattern[0])
					break;	/* match found */
			}
			if (pattern == end)
				return 0;
			pattern = end;	/* skip and continue */
			break;
		case 'N':
			if (*data < '2' || *data > '9')
				return 0;
			break;
		case 'X':
			if (*data < '0' || *data > '9')
				return 0;
			break;
		case 'Z':
			if (*data < '1' || *data > '9')
				return 0;
			break;
		case '.':	/* Must match, even with more digits */
			return 1;
		case '!':	/* Early match */
			return 2;
		case ' ':
		case '-':	/* Ignore these in patterns */
			data--; /* compensate the final data++ */
			break;
		default:
			if (*data != *pattern)
				return 0;
		}
		data++;
		pattern++;
	}
	if (*data)			/* data longer than pattern, no match */
		return 0;
	/*
	 * match so far, but ran off the end of the data.
	 * Depending on what is next, determine match or not.
	 */
	if (*pattern == '\0' || *pattern == '/')	/* exact match */
		return (mode == E_MATCHMORE) ? 0 : 1;	/* this is a failure for E_MATCHMORE */
	else if (*pattern == '!')			/* early match */
		return 2;
	else						/* partial match */
		return (mode == E_MATCH) ? 0 : 1;	/* this is a failure for E_MATCH */
}

/*
 * Wrapper around _extension_match_core() to do performance measurement
 * using the profiling code.
 */
static int extension_match_core(const char *pattern, const char *data, enum ext_match_t mode)
{
	int i;
	static int prof_id = -2;	/* marker for 'unallocated' id */
	if (prof_id == -2)
		prof_id = ast_add_profile("ext_match", 0);
	ast_mark(prof_id, 1);
	i = _extension_match_core(pattern, data, mode);
	ast_mark(prof_id, 0);
	return i;
int ast_extension_match(const char *pattern, const char *data)
Mark Spencer's avatar
Mark Spencer committed
{
	return extension_match_core(pattern, data, E_MATCH);
int ast_extension_close(const char *pattern, const char *data, int needmore)
Mark Spencer's avatar
Mark Spencer committed
{
	if (needmore != E_MATCHMORE && needmore != E_CANMATCH)
		ast_log(LOG_WARNING, "invalid argument %d\n", needmore);
	return extension_match_core(pattern, data, needmore);
struct ast_context *ast_context_find(const char *name)
Mark Spencer's avatar
Mark Spencer committed
{
	struct ast_context *tmp = NULL;
	while ( (tmp = ast_walk_contexts(tmp)) ) {
		if (!name || !strcasecmp(name, tmp->name))
			break;
	}
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
	/* 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 */

Luigi Rizzo's avatar
Luigi Rizzo committed
	if (ast_strlen_zero(callerid))
		return ast_strlen_zero(cidpattern) ? 1 : 0;
	return ast_extension_match(cidpattern, callerid);
Luigi Rizzo's avatar
Luigi Rizzo committed
/* request and result for pbx_find_extension */
struct pbx_find_info {
#if 0
	const char *context;
	const char *exten;
	int priority;
#endif

	char *incstack[AST_PBX_MAX_STACK];      /* filled during the search */
	int stacklen;                   /* modified during the search */
	int status;                     /* set on return */
	struct ast_switch *swo;         /* set on return */
	const char *data;               /* set on return */
	const char *foundcontext;       /* set on return */
};

static struct ast_exten *pbx_find_extension(struct ast_channel *chan,
	struct ast_context *bypass, struct pbx_find_info *q,
	const char *context, const char *exten, int priority,
	const char *label, const char *callerid, enum ext_match_t action)
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;
Mark Spencer's avatar
Mark Spencer committed
	/* Initialize status if appropriate */
	if (q->stacklen == 0) {
		q->status = STATUS_NO_CONTEXT;
		q->swo = NULL;
		q->data = NULL;
		q->foundcontext = NULL;
Mark Spencer's avatar
Mark Spencer committed
	}
Mark Spencer's avatar
Mark Spencer committed
	/* Check for stack overflow */
	if (q->stacklen >= AST_PBX_MAX_STACK) {
Mark Spencer's avatar
Mark Spencer committed
		ast_log(LOG_WARNING, "Maximum PBX stack exceeded\n");
		return NULL;
	}
	/* Check first to see if we've already been checked */
	for (x = 0; x < q->stacklen; x++) {
		if (!strcasecmp(q->incstack[x], context))
Mark Spencer's avatar
Mark Spencer committed
			return NULL;
	}
	if (bypass)	/* bypass means we only look there */
	else {	/* look in contexts */
		tmp = NULL;
		while ((tmp = ast_walk_contexts(tmp)) ) {
			if (!strcmp(tmp->name, context))
				break;
		}
		if (!tmp)
			return NULL;
	}
	if (q->status < STATUS_NO_EXTENSION)
		q->status = STATUS_NO_EXTENSION;

	/* scan the list trying to match extension and CID */
	eroot = NULL;
	while ( (eroot = ast_walk_context_extensions(tmp, eroot)) ) {
		int match = extension_match_core(eroot->exten, exten, action);
		/* 0 on fail, 1 on match, 2 on earlymatch */

		if (!match || (eroot->matchcid && !matchcid(eroot->cidmatch, callerid)))
			continue;	/* keep trying */
		if (match == 2 && action == E_MATCHMORE) {
			/* We match an extension ending in '!'.
			 * The decision in this case is final and is NULL (no match).
			 */
			return NULL;
		}
		/* found entry, now look for the right priority */
		if (q->status < STATUS_NO_PRIORITY)
			q->status = STATUS_NO_PRIORITY;
		e = NULL;
		while ( (e = ast_walk_extension_priorities(eroot, e)) ) {
			/* Match label or priority */
			if (action == E_FINDLABEL) {
				if (q->status < STATUS_NO_LABEL)
					q->status = STATUS_NO_LABEL;
				if (label && e->label && !strcmp(label, e->label))
					break;	/* found it */
			} else if (e->priority == priority) {
				break;	/* found it */
			} /* else keep searching */
		}
		if (e) {	/* found a valid match */
			q->status = STATUS_SUCCESS;
			q->foundcontext = context;
			return e;
		}
	}
	/* Check alternative switches */
	AST_LIST_TRAVERSE(&tmp->alts, sw, list) {
		struct ast_switch *asw = pbx_findswitch(sw->name);
		ast_switch_f *aswf = NULL;
		char *datap;

		if (!asw) {
			ast_log(LOG_WARNING, "No such switch '%s'\n", sw->name);
			continue;
		}
		/* Substitute variables now */
		if (sw->eval)
			pbx_substitute_variables_helper(chan, sw->data, sw->tmpdata, SWITCH_DATA_LENGTH - 1);

		/* equivalent of extension_match_core() at the switch level */
		if (action == E_CANMATCH)
			aswf = asw->canmatch;
		else if (action == E_MATCHMORE)
			aswf = asw->matchmore;
		else /* action == E_MATCH */
			aswf = asw->exists;