Skip to content
Snippets Groups Projects
pbx.c 125 KiB
Newer Older
Mark Spencer's avatar
Mark Spencer committed
/*
 * Asterisk -- A telephony toolkit for Linux.
 *
 * Core PBX routines.
 * 
Mark Spencer's avatar
Mark Spencer committed
 * Copyright (C) 1999, Mark Spencer
Mark Spencer's avatar
Mark Spencer committed
 *
 * Mark Spencer <markster@linux-support.net>
 *
 * This program is free software, distributed under the terms of
 * the GNU General Public License
 */

Mark Spencer's avatar
Mark Spencer committed
#include <asterisk/lock.h>
Mark Spencer's avatar
Mark Spencer committed
#include <asterisk/cli.h>
Mark Spencer's avatar
Mark Spencer committed
#include <asterisk/pbx.h>
#include <asterisk/channel.h>
#include <asterisk/options.h>
#include <asterisk/logger.h>
#include <asterisk/file.h>
Mark Spencer's avatar
Mark Spencer committed
#include <asterisk/callerid.h>
Mark Spencer's avatar
Mark Spencer committed
#include <asterisk/cdr.h>
#include <asterisk/config.h>
Mark Spencer's avatar
Mark Spencer committed
#include <asterisk/term.h>
Mark Spencer's avatar
Mark Spencer committed
#include <asterisk/manager.h>
#include <asterisk/ast_expr.h>
#include <asterisk/channel_pvt.h>
#include <asterisk/linkedlists.h>
Mark Spencer's avatar
Mark Spencer committed
#include <asterisk/say.h>
#include <asterisk/utils.h>
Mark Spencer's avatar
Mark Spencer committed
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <setjmp.h>
#include <ctype.h>
Mark Spencer's avatar
Mark Spencer committed
#include <errno.h>
#include <time.h>
#include <sys/time.h>
Mark Spencer's avatar
Mark Spencer committed
#include "asterisk.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
Mark Spencer's avatar
Mark Spencer committed

struct ast_context;

/* An extension */
struct ast_exten {
	char exten[AST_MAX_EXTENSION];
Mark Spencer's avatar
Mark Spencer committed
	int matchcid;
	char cidmatch[AST_MAX_EXTENSION];
Mark Spencer's avatar
Mark Spencer committed
	int priority;
	/* An extension */
	struct ast_context *parent;
	/* Application to execute */
	char app[AST_MAX_EXTENSION];
	/* Data to use */
	void *data;
	/* Data destructor */
	void (*datad)(void *);
Mark Spencer's avatar
Mark Spencer committed
	/* Next higher priority with our extension */
Mark Spencer's avatar
Mark Spencer committed
	struct ast_exten *peer;
Mark Spencer's avatar
Mark Spencer committed
	/* Registrar */
	char *registrar;
Mark Spencer's avatar
Mark Spencer committed
	/* Extension with a greater ID */
	struct ast_exten *next;
};

Mark Spencer's avatar
Mark Spencer committed
struct ast_include {
	char name[AST_MAX_EXTENSION];
Mark Spencer's avatar
Mark Spencer committed
	char rname[AST_MAX_EXTENSION];
Mark Spencer's avatar
Mark Spencer committed
	char *registrar;
Mark Spencer's avatar
Mark Spencer committed
	int hastime;
	unsigned int monthmask;
	unsigned int daymask;
	unsigned int dowmask;
	unsigned int minmask[24];
Mark Spencer's avatar
Mark Spencer committed
	struct ast_include *next;
};

Mark Spencer's avatar
Mark Spencer committed
struct ast_sw {
	char name[AST_MAX_EXTENSION];
	char *registrar;
	char data[AST_MAX_EXTENSION];
	struct ast_sw *next;
};

struct ast_ignorepat {
	char pattern[AST_MAX_EXTENSION];
	char *registrar;
	struct ast_ignorepat *next;
};

Mark Spencer's avatar
Mark Spencer committed
/* An extension context */
struct ast_context {
	/* Name of the context */
	char name[AST_MAX_EXTENSION];
	/* A lock to prevent multiple threads from clobbering the context */
Mark Spencer's avatar
Mark Spencer committed
	/* The root of the list of extensions */
	struct ast_exten *root;
	/* Link them together */
	struct ast_context *next;
Mark Spencer's avatar
Mark Spencer committed
	/* Include other contexts */
	struct ast_include *includes;
Mark Spencer's avatar
Mark Spencer committed
	/* Patterns for which to continue playing dialtone */
	struct ast_ignorepat *ignorepats;
Mark Spencer's avatar
Mark Spencer committed
	/* Registrar */
	char *registrar;
Mark Spencer's avatar
Mark Spencer committed
	/* Alternative switches */
	struct ast_sw *alts;
Mark Spencer's avatar
Mark Spencer committed
};


/* An application */
struct ast_app {
	/* Name of the application */
	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
	struct ast_app *next;
};

/* An extension state notify */
    ast_state_cb_type callback;
    struct ast_state_cb *next;
    struct ast_exten *exten;
    int laststate; 
    struct ast_state_cb *callbacks;
    struct ast_hint *next;
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 *);
Mark Spencer's avatar
Mark Spencer committed
static int pbx_builtin_ringing(struct ast_channel *, void *);
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 *);
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 *);
Mark Spencer's avatar
Mark Spencer committed
void pbx_builtin_setvar_helper(struct ast_channel *chan, char *name, char *value);
Mark Spencer's avatar
Mark Spencer committed
char *pbx_builtin_getvar_helper(struct ast_channel *chan, char *name);
static struct varshead globals;
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" },

Mark Spencer's avatar
Mark Spencer committed
	{ "Answer", pbx_builtin_answer, 
Mark Spencer's avatar
Mark Spencer committed
"Answer a channel if ringing", 
"  Answer(): If the channel is ringing, answer it, otherwise do nothing. \n"
"Returns 0 unless it tries to answer the channel and fails.\n"   },

	{ "BackGround", pbx_builtin_background,
"Play a file while awaiting extension",
"  Background(filename): Plays a given file, while simultaneously waiting for\n"
"the user to begin typing an extension. The  timeouts  do not count until the\n"
"last BackGround application as ended. Always returns 0.\n" },
	{ "Busy", pbx_builtin_busy,
"Indicate busy condition and stop",
"  Busy(): Requests that the channel indicate busy condition and then waits\n"
"for the user to hang up.  Always returns -1." },

	{ "Congestion", pbx_builtin_congestion,
"Indicate congestion and stop",
"  Congestion(): Requests that the channel indicate congestion and then\n"
"waits for the user to hang up.  Always returns -1." },
Mark Spencer's avatar
Mark Spencer committed
	{ "DigitTimeout", pbx_builtin_dtimeout,
Mark Spencer's avatar
Mark Spencer committed
"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).  Always returns 0.\n" },

	{ "Goto", pbx_builtin_goto, 
"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" },
	{ "GotoIf", pbx_builtin_gotoif,
"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." },

	{ "Hangup", pbx_builtin_hangup,
"Unconditional hangup",
"  Hangup(): Unconditionally hangs up a given channel by returning -1 always.\n" },
	{ "NoOp", pbx_builtin_noop,
"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" },

	{ "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 (if 'w' option is specifed).\n"
"record WILL be stored.  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.  Always returns 0.\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" },

	{ "SayNumber", pbx_builtin_saynumber,
"Say Number",
"  SayNumber(digits[,gender]): Says the passed number\n" },
	{ "SayDigits", pbx_builtin_saydigits,
"Say Digits",
"  SayDigits(digits): Says the passed digits\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"  },
	{ "SetGlobalVar", pbx_builtin_setglobalvar,
"Set variable to value",
Martin Pycko's avatar
Martin Pycko committed
"  SetGlobalVar(#n=value): Sets global variable n to value" },
	{ "SetLanguage", pbx_builtin_setlanguage,
"Sets user language",
"  SetLanguage(language):  Set  the  channel  language to 'language'.  This\n"
"information is used for the generation of numbers, and to choose a natural\n"
"language file when available.  For example, if language is set to 'fr' and\n"
"the file 'demo-congrats' is requested  to  be  played,  if the file 'fr/demo-\n"
"congrats' exists, then it will play that file, and if not will play the\n"
"normal 'demo-congrats'. Always returns 0.\n"  },
	{ "SetVar", pbx_builtin_setvar,
"Set variable to value",
"  Setvar(#n=value): Sets variable n to value" },
	{ "StripMSD", pbx_builtin_stripmsd,
"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"
Mark Spencer's avatar
Mark Spencer committed

	{ "Wait", pbx_builtin_wait, 
"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 some time", 
"  Wait(seconds): 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"
"fractions of a second. (eg: 1.5 = 1.5 seconds)\n" },

Mark Spencer's avatar
Mark Spencer committed
};

/* Lock for the application list */
AST_MUTEX_DEFINE_STATIC(applock);
Mark Spencer's avatar
Mark Spencer committed
static struct ast_context *contexts = NULL;
/* Lock for the ast_context list */
AST_MUTEX_DEFINE_STATIC(conlock);
Mark Spencer's avatar
Mark Spencer committed
static struct ast_app *apps = NULL;

Mark Spencer's avatar
Mark Spencer committed
/* Lock for switches */
AST_MUTEX_DEFINE_STATIC(switchlock);
Mark Spencer's avatar
Mark Spencer committed
struct ast_switch *switches = NULL;

/* Lock for extension state notifys */
AST_MUTEX_DEFINE_STATIC(hintlock);
static int stateid = 1;
struct ast_hint *hints = NULL;
struct ast_state_cb *statecbs = NULL;
Mark Spencer's avatar
Mark Spencer committed
int pbx_exec(struct ast_channel *c, /* Channel */
					struct ast_app *app,
Mark Spencer's avatar
Mark Spencer committed
					void *data,				/* Data for execution */
					int newstack)			/* Force stack increment */
{
	/* 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 res;
	
	char *saved_c_appl;
	char *saved_c_data;
	
Mark Spencer's avatar
Mark Spencer committed
	int stack = c->stack;
Mark Spencer's avatar
Mark Spencer committed
	int (*execute)(struct ast_channel *chan, void *data) = app->execute; 
Mark Spencer's avatar
Mark Spencer committed
	if (newstack && stack > AST_CHANNEL_MAX_STACK - 2) {
		/* Don't allow us to go over the max number of stacks we
		   permit saving. */
		ast_log(LOG_WARNING, "Stack overflow, cannot create another stack\n");
		return -1;
	}
	if (newstack && (res = setjmp(c->jmp[++c->stack]))) {
		/* Okay, here's where it gets weird.  If newstack is non-zero, 
		   then we increase the stack increment, but setjmp is not going
		   to return until longjmp is called -- when the application
		   exec'd is finished running. */
		if (res == 1)
			res = 0;
		if (c->stack != stack + 1) 
			ast_log(LOG_WARNING, "Stack returned to an unexpected place!\n");
		else if (c->app[c->stack])
			ast_log(LOG_WARNING, "Application may have forgotten to free its memory\n");
		c->stack = stack;
		return res;
	} else {
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;

Mark Spencer's avatar
Mark Spencer committed
		/* Any application that returns, we longjmp back, just in case. */
		if (c->stack != stack + 1)
			ast_log(LOG_WARNING, "Stack is not at expected value\n");
		longjmp(c->jmp[stack+1], res);
		/* Never returns */
	}
}


Mark Spencer's avatar
Mark Spencer committed
/* Go no deeper than this through includes (not counting loops) */
#define AST_PBX_MAX_STACK	64

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
Mark Spencer's avatar
Mark Spencer committed
struct ast_app *pbx_findapp(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;
}

Mark Spencer's avatar
Mark Spencer committed
static struct ast_switch *pbx_findswitch(char *sw)
{
	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)
{
Mark Spencer's avatar
Mark Spencer committed
	time_t t;
	if (!i->hastime)
		return 1;
	time(&t);
	localtime_r(&t,&tm);
Mark Spencer's avatar
Mark Spencer committed

	/* If it's not the right month, return */
	if (!(i->monthmask & (1 << tm.tm_mon))) {
Mark Spencer's avatar
Mark Spencer committed
		return 0;
	}

	/* If it's not that time of the month.... */
Mark Spencer's avatar
Mark Spencer committed
	/* Warning, tm_mday has range 1..31! */
	if (!(i->daymask & (1 << (tm.tm_mday-1))))
Mark Spencer's avatar
Mark Spencer committed
		return 0;

	/* If it's not the right day of the week */
	if (!(i->dowmask & (1 << tm.tm_wday)))
Mark Spencer's avatar
Mark Spencer committed
		return 0;

	/* Sanity check the hour just to be safe */
	if ((tm.tm_hour < 0) || (tm.tm_hour > 23)) {
Mark Spencer's avatar
Mark Spencer committed
		ast_log(LOG_WARNING, "Insane time...\n");
		return 0;
	}

	/* Now the tough part, we calculate if it fits
	   in the right time based on min/hour */
	if (!(i->minmask[tm.tm_hour] & (1 << (tm.tm_min / 2))))
Mark Spencer's avatar
Mark Spencer committed
		return 0;

	/* If we got this far, then we're good */
	return 1;
}

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 != '/')) {\
		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++;\
	}\
Mark Spencer's avatar
Mark Spencer committed
int ast_extension_match(char *pattern, 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;
}

Mark Spencer's avatar
Mark Spencer committed
static int extension_close(char *pattern, 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);
Mark Spencer's avatar
Mark Spencer committed
	/* If there's more or we don't care about more, return non-zero, otlherwise it's a miss */
	if (!needmore || *pattern) {
		return match;
	} else
		return 0;
Mark Spencer's avatar
Mark Spencer committed
struct ast_context *ast_context_find(char *name)
{
	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_SUCCESS	    4

Mark Spencer's avatar
Mark Spencer committed
static int matchcid(char *cidpattern, char *callerid)
Mark Spencer's avatar
Mark Spencer committed
{
Mark Spencer's avatar
Mark Spencer committed
	char tmp[AST_MAX_EXTENSION];
	int failresult;
	char *name, *num;
	
	/* 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;

	/* Copy original Caller*ID */
Mark Spencer's avatar
Mark Spencer committed
	strncpy(tmp, callerid, sizeof(tmp)-1);
Mark Spencer's avatar
Mark Spencer committed
	/* Parse Number */
	if (ast_callerid_parse(tmp, &name, &num)) 
		return failresult;
	if (!num)
		return failresult;
	ast_shrink_phone_number(num);
	return ast_extension_match(cidpattern, num);
}

static struct ast_exten *pbx_find_extension(struct ast_channel *chan, char *context, char *exten, int priority, char *callerid, int action, char *incstack[], int *stacklen, int *status, struct ast_switch **swo, char **data)
{
	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 */
	for (x=0;x<*stacklen;x++) {
		if (!strcasecmp(incstack[x], context))
			return NULL;
	}
	tmp = contexts;
	while(tmp) {
		/* Match context */
Mark Spencer's avatar
Mark Spencer committed
		if (!strcmp(tmp->name, context)) {
Mark Spencer's avatar
Mark Spencer committed
			if (*status < STATUS_NO_EXTENSION)
				*status = STATUS_NO_EXTENSION;
			eroot = tmp->root;
			while(eroot) {
				/* Match extension */
Mark Spencer's avatar
Mark Spencer committed
				if ((((action != HELPER_MATCHMORE) && ast_extension_match(eroot->exten, exten)) ||
						((action == HELPER_CANMATCH) && (extension_close(eroot->exten, exten, 0))) ||
						((action == HELPER_MATCHMORE) && (extension_close(eroot->exten, exten, 1)))) &&
Mark Spencer's avatar
Mark Spencer committed
						(!eroot->matchcid || matchcid(eroot->cidmatch, callerid))) {
Mark Spencer's avatar
Mark Spencer committed
						e = eroot;
						if (*status < STATUS_NO_PRIORITY)
							*status = STATUS_NO_PRIORITY;
						while(e) {
							/* Match priority */
							if (e->priority == priority) {
								*status = STATUS_SUCCESS;
								return e;
							}
							e = e->peer;
						}
				}
				eroot = eroot->next;
			}
Mark Spencer's avatar
Mark Spencer committed
			/* Check alternative switches */
			sw = tmp->alts;
			while(sw) {
				if ((asw = pbx_findswitch(sw->name))) {
					if (action == HELPER_CANMATCH)
						res = asw->canmatch ? asw->canmatch(chan, context, exten, priority, callerid, 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->data) : 0;
Mark Spencer's avatar
Mark Spencer committed
					else
						res = asw->exists ? asw->exists(chan, context, exten, priority, callerid, sw->data) : 0;
					if (res) {
						/* Got a match */
						*swo = asw;
						*data = sw->data;
						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, i->rname, exten, priority, callerid, action, incstack, stacklen, status, swo, data))) 
						return e;
					if (*swo) 
						return NULL;
				}
Mark Spencer's avatar
Mark Spencer committed
				i = i->next;
			}
		}
		tmp = tmp->next;
	}
	return NULL;
}

static void pbx_substitute_variables_temp(struct ast_channel *c,const char *var,char **ret, char *workspace, int workspacelen)
	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;
	char *name, *num; /* for callerid name + num variables */
	*ret=NULL;
	/* Now we have the variable name on cp3 */
	if (!strncasecmp(var,"LEN(",4)) {
		int len=strlen(var);
		int len_len=4;
		if (strrchr(var,')')) {
			char cp3[80];
			strncpy(cp3, var, sizeof(cp3) - 1);
			cp3[len-len_len-1]='\0';
			sprintf(workspace,"%d",(int)strlen(cp3));
			*ret = workspace;
		} else {
			/* length is zero */
			*ret = "0";
		}
	} else if ((first=strchr(var,':'))) {
		strncpy(tmpvar, var, sizeof(tmpvar) - 1);
		first = strchr(tmpvar, ':');
		if (!first)
			first = tmpvar + strlen(tmpvar);
		*first='\0';
Mark Spencer's avatar
Mark Spencer committed
		pbx_substitute_variables_temp(c,tmpvar,ret,workspace,workspacelen - 1);
		if (!(*ret)) return;
		offset=atoi(first+1);
	 	if ((second=strchr(first+1,':'))) {
			*second='\0';
			offset2=atoi(second+1);
			offset2=strlen(*ret)-offset;
		if (abs(offset)>strlen(*ret)) {
			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';
	} else if (c && !strcmp(var, "CALLERIDNUM")) {
		if (c->callerid)
			strncpy(workspace, c->callerid, workspacelen - 1);
		ast_callerid_parse(workspace, &name, &num);
		if (num) {
			ast_shrink_phone_number(num);
			*ret = num;
Mark Spencer's avatar
Mark Spencer committed
			*ret = workspace;
	} else if (c && !strcmp(var, "CALLERIDNAME")) {
		if (c->callerid)
			strncpy(workspace, c->callerid, workspacelen - 1);
		ast_callerid_parse(workspace, &name, &num);
		if (name)
			*ret = name;
Mark Spencer's avatar
Mark Spencer committed
			*ret = workspace;
	} else if (c && !strcmp(var, "CALLERID")) {
		if (c->callerid) {
			strncpy(workspace, c->callerid, workspacelen - 1);
			*ret = workspace;
		} else 
			*ret = NULL;
Mark Spencer's avatar
Mark Spencer committed
	} else if (c && !strcmp(var, "DNID")) {
		if (c->dnid) {
			strncpy(workspace, c->dnid, workspacelen - 1);
			*ret = workspace;
		} else
			*ret = NULL;
	} else if (c && !strcmp(var, "HINT")) {
		if (!ast_get_hint(workspace, workspacelen - 1, c, c->context, c->exten))
			*ret = NULL;
			*ret = workspace;
	} else if (c && !strcmp(var, "EXTEN")) {
		strncpy(workspace, c->exten, workspacelen - 1);
		*ret = workspace;
	} else if (c && !strncmp(var, "EXTEN-", strlen("EXTEN-")) && 
		/* XXX Remove me eventually */
		(sscanf(var + strlen("EXTEN-"), "%d", &offset) == 1)) {
		if (offset < 0)
			offset=0;
		if (offset > strlen(c->exten))
			offset = strlen(c->exten);
		strncpy(workspace, c->exten + offset, workspacelen - 1);
		*ret = workspace;
		ast_log(LOG_WARNING, "The use of 'EXTEN-foo' has been deprecated in favor of 'EXTEN:foo'\n");
	} else if (c && !strcmp(var, "RDNIS")) {
		if (c->rdnis) {
			strncpy(workspace, c->rdnis, workspacelen - 1);
			*ret = workspace;
		} else
			*ret = NULL;
	} else if (c && !strcmp(var, "CONTEXT")) {
		strncpy(workspace, c->context, workspacelen - 1);
		*ret = workspace;
	} else if (c && !strcmp(var, "PRIORITY")) {
		snprintf(workspace, workspacelen, "%d", c->priority);
		*ret = workspace;
	} else if (c && !strcmp(var, "CHANNEL")) {
		strncpy(workspace, c->name, workspacelen - 1);
		*ret = workspace;
	} else if (c && !strcmp(var, "EPOCH")) {
		snprintf(workspace, workspacelen -1, "%u",(int)time(NULL));
		*ret = workspace;
	} else if (c && !strcmp(var, "DATETIME")) {
		thistime=time(NULL);
		localtime_r(&thistime, &brokentime);
		snprintf(workspace, workspacelen -1, "%02d%02d%04d-%02d:%02d:%02d",
			brokentime.tm_mday,
			brokentime.tm_mon+1,
			brokentime.tm_year+1900,
			brokentime.tm_hour,
			brokentime.tm_min,
			brokentime.tm_sec
		);
		*ret = workspace;
	} else if (c && !strcmp(var, "TIMESTAMP")) {
		thistime=time(NULL);
		localtime_r(&thistime, &brokentime);
		snprintf(workspace, workspacelen -1, "%04d%02d%02d-%02d%02d%02d",
			brokentime.tm_year+1900,
			brokentime.tm_mon+1,
			brokentime.tm_mday,
			brokentime.tm_hour,
			brokentime.tm_min,
			brokentime.tm_sec
		);
		*ret = workspace;
	} else if (c && !strcmp(var, "UNIQUEID")) {
		snprintf(workspace, workspacelen -1, "%s", c->uniqueid);
		*ret = workspace;
	} else if (c && !strcmp(var, "HANGUPCAUSE")) {
		snprintf(workspace, workspacelen -1, "%i", c->hangupcause);
		*ret = workspace;
	} else if (c && !strcmp(var, "ACCOUNTCODE")) {
		strncpy(workspace, c->accountcode, workspacelen - 1);
		*ret = workspace;
	} else if (c && !strcmp(var, "LANGUAGE")) {
		strncpy(workspace, c->language, workspacelen - 1);
		*ret = workspace;
		if (c) {
			AST_LIST_TRAVERSE(headp,variables,entries) {
				ast_log(LOG_WARNING,"Comparing variable '%s' with '%s'\n",var,ast_var_name(variables));
				if (strcasecmp(ast_var_name(variables),var)==0) {
					*ret=ast_var_value(variables);
					if (*ret) {
						strncpy(workspace, *ret, workspacelen - 1);
						*ret = workspace;
					}
		if (!(*ret)) {
			/* Try globals */
			AST_LIST_TRAVERSE(&globals,variables,entries) {
#if 0
				ast_log(LOG_WARNING,"Comparing variable '%s' with '%s'\n",var,ast_var_name(variables));
				if (strcasecmp(ast_var_name(variables),var)==0) {
					*ret=ast_var_value(variables);
					if (*ret) {
						strncpy(workspace, *ret, workspacelen - 1);
						*ret = workspace;
					}
				}
		if (!(*ret)) {
			int len=strlen(var);
			int len_env=strlen("ENV(");
			if (len > (len_env+1) && !strncasecmp(var,"ENV(",len_env) && !strcmp(var+len-1,")")) {
				char cp3[80] = "";
				strncpy(cp3, var, sizeof(cp3) - 1);
				cp3[len-1]='\0';
				*ret=getenv(cp3+len_env);
				if (*ret) {
					strncpy(workspace, *ret, workspacelen - 1);
					*ret = workspace;
				}
void pbx_substitute_variables_helper(struct ast_channel *c,const char *cp1,char *cp2,int count)
	char *cp4;
	const char *tmp, *whereweare;
	int length;
	char ltmp[256], var[256];
	char *nextvar, *nextexp;
	char *vars, *vare;
	int pos, brackets, needsub, len;

	/* Substitutes variables into cp2, based on string cp1, and assuming cp2 to be
	   zero-filled */
	whereweare=tmp=cp1;
	while(!ast_strlen_zero(whereweare) && count) {
		/* Assume we're copying the whole remaining string */
		pos = strlen(whereweare);