Skip to content
Snippets Groups Projects
pbx.c 167 KiB
Newer Older
Russell Bryant's avatar
Russell Bryant committed
/*
Mark Spencer's avatar
Mark Spencer committed
 * Asterisk -- A telephony toolkit for Linux.
 *
 * Core PBX routines.
 * 
 * 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
 *
 * This program is free software, distributed under the terms of
 * the GNU General Public License
 */

#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <setjmp.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"
#include "asterisk/say.h"
#include "asterisk/utils.h"
#include "asterisk/causes.h"
#include "asterisk/musiconhold.h"
#include "asterisk/app.h"
Mark Spencer's avatar
Mark Spencer committed

/*
 * I M P O R T A N T :
 *
 *		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_NORMAL		1
#define	VAR_SOFTTRAN	2
#define	VAR_HARDTRAN	3

#define BACKGROUND_SKIP		(1 << 0)
#define BACKGROUND_NOANSWER	(1 << 1)

AST_DECLARE_OPTIONS(background_opts,{
	['s'] = { BACKGROUND_SKIP },
	['n'] = { BACKGROUND_NOANSWER },
});

#define WAITEXTEN_MOH		(1 << 0)

AST_DECLARE_OPTIONS(waitexten_opts,{
	['m'] = { WAITEXTEN_MOH, 1 },
});

Mark Spencer's avatar
Mark Spencer committed
struct ast_context;

/* ast_exten: An extension */
Mark Spencer's avatar
Mark Spencer committed
struct ast_exten {
	char *exten;			/* Extension name */
	int matchcid;			/* Match caller id ? */
	char *cidmatch;			/* Caller id to match for this extension */
	int priority;			/* Priority */
	char *label;			/* Label */
	struct ast_context *parent;	/* The context this extension belongs to  */
	char *app; 			/* Application to execute */
	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 */
/* ast_include: include= support in extensions.conf */
Mark Spencer's avatar
Mark Spencer committed
struct ast_include {
	char *name;		
	char *rname;		/* Context to include */
	const char *registrar;			/* Registrar */
	int hastime;				/* If time construct exists */
	struct ast_timing timing;               /* time construct */
	struct ast_include *next;		/* Link them together */
/* ast_sw: Switch statement in extensions.conf */
Mark Spencer's avatar
Mark Spencer committed
struct ast_sw {
	char *name;
	const char *registrar;			/* Registrar */
	struct ast_sw *next;			/* Link them together */
Mark Spencer's avatar
Mark Spencer committed
};

struct ast_ignorepat {
	const char *registrar;
Mark Spencer's avatar
Mark Spencer committed
	struct ast_ignorepat *next;
/* 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 */
Russell Bryant's avatar
Russell Bryant committed
	char name[0];				/* Name of the context */
/* ast_app: An application */
Mark Spencer's avatar
Mark Spencer committed
struct ast_app {
	int (*execute)(struct ast_channel *chan, void *data);
	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 */
Russell Bryant's avatar
Russell Bryant committed
	char name[0];				/* Name of the application */
/* ast_state_cb: An extension state notify */
Russell Bryant's avatar
Russell Bryant committed
	int id;
	void *data;
	ast_state_cb_type callback;
	struct ast_state_cb *next;
/* ast_devstate_cb: An extension state notify */
Mark Spencer's avatar
Mark Spencer committed
struct ast_devstate_cb {
Russell Bryant's avatar
Russell Bryant committed
	void *data;
	ast_devstate_cb_type callback;
	struct ast_devstate_cb *next;
Mark Spencer's avatar
Mark Spencer committed
};

static struct ast_devstate_cb *devcbs;

/* Hints are pointers from an extension in the dialplan to one or more devices (tech/name) */
Russell Bryant's avatar
Russell Bryant committed
	struct ast_exten *exten;	/* Extension */
	int laststate; 			/* Last known state */
	struct ast_state_cb *callbacks;	/* Callback list for this extension */
	struct ast_hint *next;		/* Pointer to next hint in list */
int ast_pbx_outgoing_cdr_failed(void);
Mark Spencer's avatar
Mark Spencer committed
static int pbx_builtin_prefix(struct ast_channel *, void *);
static int pbx_builtin_suffix(struct ast_channel *, void *);
Mark Spencer's avatar
Mark Spencer committed
static int pbx_builtin_stripmsd(struct ast_channel *, 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_dtimeout(struct ast_channel *, void *);
static int pbx_builtin_rtimeout(struct ast_channel *, void *);
Mark Spencer's avatar
Mark Spencer committed
static int pbx_builtin_atimeout(struct ast_channel *, void *);
Mark Spencer's avatar
Mark Spencer committed
static int pbx_builtin_wait(struct ast_channel *, void *);
static int pbx_builtin_waitexten(struct ast_channel *, void *);
Mark Spencer's avatar
Mark Spencer committed
static int pbx_builtin_setlanguage(struct ast_channel *, void *);
static int pbx_builtin_resetcdr(struct ast_channel *, void *);
static int pbx_builtin_setaccount(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 *);
static int pbx_builtin_setvar_old(struct ast_channel *, void *);
int pbx_builtin_setvar(struct ast_channel *, void *);
static int pbx_builtin_importvar(struct ast_channel *, void *);
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;
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
	   
	    */

	{ "AbsoluteTimeout", pbx_builtin_atimeout,
	"Set absolute maximum time of call",
	"  AbsoluteTimeout(seconds): Set the absolute maximum amount of time permitted\n"
	"for a call.  A setting of 0 disables the timeout.  Always returns 0.\n" 
	"AbsoluteTimeout has been deprecated in favor of Set(TIMEOUT(absolute)=timeout)\n"
Mark Spencer's avatar
Mark Spencer committed
	{ "Answer", pbx_builtin_answer, 
	"Answer a channel if ringing", 
	"  Answer([delay]): If the channel is ringing, answer it, otherwise do nothing. \n"
	"If delay is specified, asterisk will pause execution for the specified amount\n"
	"of milliseconds if an answer is required, in order to give audio a chance to\n"
	"become ready. Returns 0 unless it tries to answer the channel and fails.\n"   
	{ "BackGround", pbx_builtin_background,
	"Play a file while awaiting extension",
	"  Background(filename1[&filename2...][|options[|langoverride]]): Plays\n"
	"given files, while simultaneously waiting for the user to begin typing\n"
	"an extension. The timeouts do not count until the last BackGround\n"
	"application has ended. Options may also be included following a pipe \n"
	"symbol. The 'langoverride' may be a language to use for playing the prompt\n"
	"which differs from the current language of the channel. Returns -1 if \n"
	"the channel was hung up, or if the file does not exist. Returns 0 otherwise.\n\n"
	"  Options:\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"
	"Indicate busy condition and stop",
	"  Busy([timeout]): Requests that the channel indicate busy condition and\n"
	"then waits for the user to hang up or the optional timeout to expire.\n"
	"Always returns -1." 
	},
	"Indicate congestion and stop",
	"  Congestion([timeout]): Requests that the channel indicate congestion\n"
	"and then waits for the user to hang up or for the optional timeout to\n"
	"expire.  Always returns -1." 
	},
Mark Spencer's avatar
Mark Spencer committed
	{ "DigitTimeout", pbx_builtin_dtimeout,
	"Set maximum timeout between digits",
	"  DigitTimeout(seconds): Set the maximum amount of time permitted between\n"
	"digits when the user is typing in an extension. When this timeout expires,\n"
	"after the user has started to type in an extension, the extension will be\n"
	"considered complete, and will be interpreted. Note that if an extension\n"
	"typed in is valid, it will not have to timeout to be tested, so typically\n"
	"at the expiry of this timeout, the extension will be considered invalid\n"
	"(and thus control would be passed to the 'i' extension, or if it doesn't\n"
	"exist the call would be terminated). The default timeout is 5 seconds.\n"
	"Always returns 0.\n" 
	"DigitTimeout has been deprecated in favor of Set(TIMEOUT(digit)=timeout)\n"
	"Goto a particular priority, extension, or context",
	"  Goto([[context|]extension|]priority):  Set the  priority to the specified\n"
	"value, optionally setting the extension and optionally the context as well.\n"
	"The extension BYEXTENSION is special in that it uses the current extension,\n"
	"thus  permitting you to go to a different context, without specifying a\n"
	"specific extension. Always returns 0, even if the given context, extension,\n"
	"or priority is invalid.\n" 
	},
	"Conditional goto",
	"  GotoIf(Condition?label1:label2): Go to label 1 if condition is\n"
	"true, to label2 if condition is false. Either label1 or label2 may be\n"
	"omitted (in that case, we just don't take the particular branch) but not\n"
	"both. Look for the condition syntax in examples or documentation." 
	},
	{ "GotoIfTime", pbx_builtin_gotoiftime,
	"Conditional goto on current time",
	"  GotoIfTime(<times>|<weekdays>|<mdays>|<months>?[[context|]extension|]pri):\n"
	"If the current time matches the specified time, then branch to the specified\n"
	"extension. Each of the elements may be specified either as '*' (for always)\n"
	"or as a range. See the 'include' syntax for details." 
	},

	{ "ExecIfTime", pbx_builtin_execiftime,
	"Conditional application execution on current time",
	"  ExecIfTime(<times>|<weekdays>|<mdays>|<months>?<appname>[|<appdata>]):\n"
	"If the current time matches the specified time, then execute the specified\n"
	"application. Each of the elements may be specified either as '*' (for always)\n"
	"or as a range. See the 'include' syntax for details. It will return whatever\n"
	"<appname> returns, or a non-zero value if the application is not found.\n"
	"Unconditional hangup",
	"  Hangup(): Unconditionally hangs up a given channel by returning -1 always.\n" 
	},
	"No operation",
	"  NoOp(): No-operation; Does nothing." 
	},
Mark Spencer's avatar
Mark Spencer committed

	{ "Prefix", pbx_builtin_prefix, 
	"Prepend leading digits",
	"  Prefix(digits): Prepends the digit string specified by digits to the\n"
	"channel's associated extension. For example, the number 1212 when prefixed\n"
	"with '555' will become 5551212. This app always returns 0, and the PBX will\n"
	"continue processing at the next priority for the *new* extension.\n"
	"  So, for example, if priority  3  of 1212 is  Prefix  555, the next step\n"
	"executed will be priority 4 of 5551212. If you switch into an extension\n"
	"which has no first step, the PBX will treat it as though the user dialed an\n"
	"invalid extension.\n" 
	},
Mark Spencer's avatar
Mark Spencer committed
	{ "Progress", pbx_builtin_progress,
	"Indicate progress",
	"  Progress(): Request that the channel indicate in-band progress is \n"
	"available to the user.\nAlways returns 0.\n" 
	},
	{ "ResetCDR", pbx_builtin_resetcdr,
	"Resets the Call Data Record",
	"  ResetCDR([options]):  Causes the Call Data Record to be reset, optionally\n"
	"storing the current CDR before zeroing it out\b"
	" - if 'w' option is specified record will be stored.\n"
	" - if 'a' option is specified any stacked records will be stored.\n"
	" - if 'v' option is specified any variables will be saved.\n"
	"Always returns 0.\n"  
	{ "ResponseTimeout", pbx_builtin_rtimeout,
	"Set maximum timeout awaiting response",
	"  ResponseTimeout(seconds): Set the maximum amount of time permitted after\n"
	"falling through a series of priorities for a channel in which the user may\n"
	"begin typing an extension. If the user does not type an extension in this\n"
	"amount of time, control will pass to the 't' extension if it exists, and\n"
	"if not the call would be terminated. The default timeout is 10 seconds.\n"
	"Always returns 0.\n"  
	"ResponseTimeout has been deprecated in favor of Set(TIMEOUT(response)=timeout)\n"
Mark Spencer's avatar
Mark Spencer committed

	{ "Ringing", pbx_builtin_ringing,
	"Indicate ringing tone",
	"  Ringing(): Request that the channel indicate ringing tone to the user.\n"
	"Always returns 0.\n" 
	},
	"Say Number",
	"  SayNumber(digits[,gender]): Says the passed number. SayNumber is using\n" 
	"the current language setting for the channel. (See app SetLanguage).\n"
	},
	"Say Digits",
	"  SayDigits(digits): Says the passed digits. SayDigits is using the\n" 
	"current language setting for the channel. (See app setLanguage)\n"
	},
	{ "SayAlpha", pbx_builtin_saycharacters,
	"Say Alpha",
	"  SayAlpha(string): Spells the passed string\n" 
	},

	{ "SayPhonetic", pbx_builtin_sayphonetic,
	"Say Phonetic",
	"  SayPhonetic(string): Spells the passed string with phonetic alphabet\n" 
	},
	{ "SetAccount", pbx_builtin_setaccount,
	"Sets account code",
	"  SetAccount([account]): Set the channel account code for billing\n"
	"purposes. Always returns 0.\n"

	{ "SetAMAFlags", pbx_builtin_setamaflags,
	"Sets AMA Flags",
	"  SetAMAFlags([flag]): Set the channel AMA Flags for billing\n"
	"purposes. Always returns 0.\n"
	{ "SetGlobalVar", pbx_builtin_setglobalvar,
	"Set global variable to value",
	"  SetGlobalVar(#n=value): Sets global variable n to value. Global\n" 
	"variable are available across channels.\n"
	},
	{ "SetLanguage", pbx_builtin_setlanguage,
	"Sets channel language",
	"  SetLanguage(language): Set the channel language to 'language'. This\n"
	"information is used for the syntax in generation of numbers, and to choose\n"
	"a natural language file when available.\n"
	"  For example, if language is set to 'fr' and the file 'demo-congrats' is \n"
	"requested to be played, if the file 'fr/demo-congrats' exists, then\n"
	"it will play that file, and if not will play the normal 'demo-congrats'.\n"
	"For some language codes, SetLanguage also changes the syntax of some\n"
	"Asterisk functions, like SayNumber.\n"
	"Always returns 0.\n"
	"SetLanguage has been deprecated in favor of Set(LANGUAGE()=language)\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\n"
	  "or dialplan functions. It will accept up to 24 name/value pairs.\n"
	  "When setting variables, if the variable name is prefixed with _,\n"
	  "the variable will be inherited into channels created from the\n"
	  "current channel. If the variable name is prefixed with __,\n"
	  "the variable will be inherited into channels created from the\n"
	  "current channel and all child channels.\n"
	  "The last argument, if it does not contain '=', is interpreted\n"
	  "as a string of options. The valid options are:\n"
	  "  g - Set variable globally instead of on the channel\n"
	  "      (applies only to variables, not functions)\n"
	},

	{ "SetVar", pbx_builtin_setvar_old,
	  "Set channel variable(s)",
	  "  SetVar(name1=value1|name2=value2|..[|options])\n"
	  "SetVar has been deprecated in favor of Set.\n"
	{ "ImportVar", pbx_builtin_importvar,
	"Import a variable from a channel into a new variable",
	"  ImportVar(newvar=channelname|variable): This application imports a\n"
	"variable from the specified channel (as opposed to the current one)\n"
	"and stores it as a variable in the current channel (the channel that\n"
	"is calling this application). If the new variable name is prefixed by\n"
	"a single underscore \"_\", then it will be inherited into any channels\n"
	"created from this one. If it is prefixed with two underscores,then\n"
	"the variable will have infinite inheritance, meaning that it will be\n"
	"present in any descendent channel of this one.\n"
	},
	"Strip leading digits",
	"  StripMSD(count): Strips the leading 'count' digits from the channel's\n"
	"associated extension. For example, the number 5551212 when stripped with a\n"
	"count of 3 would be changed to 1212. This app always returns 0, and the PBX\n"
	"will continue processing at the next priority for the *new* extension.\n"
	"  So, for example, if priority 3 of 5551212 is StripMSD 3, the next step\n"
	"executed will be priority 4 of 1212. If you switch into an extension which\n"
	"has no first step, the PBX will treat it as though the user dialed an\n"
	"invalid extension.\n" 
	},

	{ "Suffix", pbx_builtin_suffix, 
	"Append trailing digits",
	"  Suffix(digits): Appends the digit string specified by digits to the\n"
	"channel's associated extension. For example, the number 555 when suffixed\n"
	"with '1212' will become 5551212. This app always returns 0, and the PBX will\n"
	"continue processing at the next priority for the *new* extension.\n"
	"  So, for example, if priority 3 of 555 is Suffix 1212, the next step\n"
	"executed will be priority 4 of 5551212. If you switch into an extension\n"
	"which has no first step, the PBX will treat it as though the user dialed an\n"
	"invalid extension.\n" 
	},
Mark Spencer's avatar
Mark Spencer committed

	"Waits for some time", 
	"  Wait(seconds): Waits for a specified number of seconds, then returns 0.\n"
	"seconds can be passed with fractions of a second. (eg: 1.5 = 1.5 seconds)\n" 
	},

	{ "WaitExten", pbx_builtin_waitexten, 
	"Waits for an extension to be entered", 
	"  WaitExten([seconds][|options]): Waits for the user to enter a new extension for the \n"
	"specified number of seconds, then returns 0. Seconds can be passed with\n"
Mark Spencer's avatar
Mark Spencer committed
	"fractions of a seconds (eg: 1.5 = 1.5 seconds) or if unspecified the\n"
	"default extension timeout will be used.\n"
	"  Options:\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;
AST_MUTEX_DEFINE_STATIC(conlock); 		/* Lock for the ast_context list */
Mark Spencer's avatar
Mark Spencer committed
static struct ast_app *apps = NULL;
AST_MUTEX_DEFINE_STATIC(applock); 		/* Lock for the application list */
Mark Spencer's avatar
Mark Spencer committed
struct ast_switch *switches = NULL;
AST_MUTEX_DEFINE_STATIC(switchlock);		/* Lock for switches */
AST_MUTEX_DEFINE_STATIC(hintlock);		/* Lock for extension state notifys */
static int stateid = 1;
struct ast_hint *hints = NULL;
struct ast_state_cb *statecbs = NULL;
int pbx_exec(struct ast_channel *c, 		/* Channel */
		struct ast_app *app,		/* Application */
		void *data,			/* Data for execution */
		int newstack)			/* Force stack increment */
Mark Spencer's avatar
Mark Spencer committed
{
	/* This function is special. It saves the stack so that no matter
Mark Spencer's avatar
Mark Spencer committed
	   how many times it is called, it returns to the same place */
	int res;
	
	char *saved_c_appl;
	char *saved_c_data;
	
Mark Spencer's avatar
Mark Spencer committed
	int (*execute)(struct ast_channel *chan, void *data) = app->execute; 
	if (newstack) {
Mark Spencer's avatar
Mark Spencer committed
		if (c->cdr)
			ast_cdr_setapp(c->cdr, app->name, data);
		/* save channel values */
		saved_c_appl= c->appl;
		saved_c_data= c->data;

Mark Spencer's avatar
Mark Spencer committed
		c->appl = app->name;
		c->data = data;		
Mark Spencer's avatar
Mark Spencer committed
		res = execute(c, data);
		/* restore channel values */
		c->appl= saved_c_appl;
		c->data= saved_c_data;
		return res;
	} else
		ast_log(LOG_WARNING, "You really didn't want to call this function with newstack set to 0\n");
	return -1;
Mark Spencer's avatar
Mark Spencer committed
/* 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
#define HELPER_EXEC 2
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
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;
	}
	tmp = apps;
	while(tmp) {
		if (!strcasecmp(tmp->name, app))
			break;
		tmp = tmp->next;
	}
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;
	}
	asw = switches;
	while(asw) {
		if (!strcasecmp(asw->name, sw))
			break;
		asw = asw->next;
	}
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) {
		tmp = contexts;
		while(tmp) {
			if (!strcasecmp(name, tmp->name))
				break;
			tmp = tmp->next;
		}
	} else
		tmp = contexts;
Mark Spencer's avatar
Mark Spencer committed
	return tmp;
}

Mark Spencer's avatar
Mark Spencer committed
#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 */
Mark Spencer's avatar
Mark Spencer committed
		if (!strcasecmp(incstack[x], context))
			return NULL;
	}
	if (bypass)
		tmp = bypass;
	else
		tmp = contexts;
Mark Spencer's avatar
Mark Spencer committed
	while(tmp) {
		/* 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;
			for (eroot = tmp->root; eroot; eroot=eroot->next) {
				int match = 0;
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)))) &&
				    (!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
						e = eroot;
						if (*status < STATUS_NO_PRIORITY)
							*status = STATUS_NO_PRIORITY;
						while(e) {
							/* 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;
							}
							e = e->peer;
						}
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 */
			sw = tmp->alts;
			while(sw) {
				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);
				}
				sw = sw->next;
			}
Mark Spencer's avatar
Mark Spencer committed
			/* Setup the stack */
			incstack[*stacklen] = tmp->name;
			(*stacklen)++;
			/* Now try any includes we have in this context */
			i = tmp->includes;
			while(i) {
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
				i = i->next;
			}
Mark Spencer's avatar
Mark Spencer committed
		}
		tmp = tmp->next;
	}
	return NULL;
}

/*--- 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)
	char *first,*second;
	char tmpvar[80] = "";
	time_t thistime;
	struct tm brokentime;
	int offset,offset2;
Mark Spencer's avatar
Mark Spencer committed
	struct ast_var_t *variables;
	if ((first=strchr(var,':'))) {	/* : Remove characters counting from end or start of string */
		ast_copy_string(tmpvar, var, sizeof(tmpvar));
		first = strchr(tmpvar, ':');
		if (!first)
			first = tmpvar + strlen(tmpvar);
		*first='\0';
		pbx_retrieve_variable(c,tmpvar,ret,workspace,workspacelen - 1, headp);
		if (!(*ret)) 
			return;
		offset=atoi(first+1);	/* The number of characters, 
					   positive: remove # of chars from start
					   negative: keep # of chars from end */
						
	 	if ((second=strchr(first+1,':'))) {	
			*second='\0';
			offset2 = atoi(second+1);		/* Number of chars to copy */
		} else if (offset >= 0) {
			offset2 = strlen(*ret)-offset;	/* Rest of string */
		} else {
			offset2 = abs(offset);
		}

		if (abs(offset) > strlen(*ret)) {	/* Offset beyond string */
			if (offset >= 0) 
				offset=strlen(*ret);
			else 
				offset=-strlen(*ret);	
		if ((offset < 0 && offset2 > -offset) || (offset >= 0 && offset+offset2 > strlen(*ret))) {
			if (offset >= 0) 
				offset2=strlen(*ret)-offset;
			else 
				offset2=strlen(*ret)+offset;
		if (offset >= 0)
			*ret += offset;
			*ret += strlen(*ret)+offset;
		(*ret)[offset2] = '\0';		/* Cut at offset2 position */
	} else if (c && !strncmp(var, "CALL", 4)) {
		if (!strncmp(var + 4, "ER", 2)) {
			if (!strncmp(var + 6, "ID", 2)) {
				if (!var[8]) { 			/* CALLERID */
					if (c->cid.cid_num) {
						if (c->cid.cid_name) {
							snprintf(workspace, workspacelen, "\"%s\" <%s>", c->cid.cid_name, c->cid.cid_num);
						} else {
							ast_copy_string(workspace, c->cid.cid_num, workspacelen);
						}
						*ret = workspace;
					} else if (c->cid.cid_name) {
						ast_copy_string(workspace, c->cid.cid_name, workspacelen);
						*ret = workspace;
					} else
						*ret = NULL;
				} else if (!strcmp(var + 8, "NUM")) {
					/* CALLERIDNUM */
					if (c->cid.cid_num) {
						ast_copy_string(workspace, c->cid.cid_num, workspacelen);
						*ret = workspace;
					} else
						*ret = NULL;
				} else if (!strcmp(var + 8, "NAME")) {
					/* CALLERIDNAME */
					if (c->cid.cid_name) {
						ast_copy_string(workspace, c->cid.cid_name, workspacelen);
						*ret = workspace;
					} else
						*ret = NULL;
				}
			} else if (!strcmp(var + 6, "ANI")) {
				/* CALLERANI */
				if (c->cid.cid_ani) {
					ast_copy_string(workspace, c->cid.cid_ani, workspacelen);
					*ret = workspace;
				} else
					*ret = NULL;
Mark Spencer's avatar
Mark Spencer committed
			} else
				goto icky;
		} else if (!strncmp(var + 4, "ING", 3)) {
			if (!strcmp(var + 7, "PRES")) {
				/* CALLINGPRES */
				snprintf(workspace, workspacelen, "%d", c->cid.cid_pres);