Skip to content
Snippets Groups Projects
pbx.c 70.4 KiB
Newer Older
  • Learn to ignore specific revisions
  • 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
     */
    
    #include <pthread.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 <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>
    
    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 ;-) 
     *
     */
    
    
    struct ast_context;
    
    struct ast_pbx {
    	int dtimeout;					/* Timeout between digits (seconds) */
    	int rtimeout;					/* Timeout for response (seconds) */
    };
    
    /* 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 *registrar;
    
    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 */
    	pthread_mutex_t lock;
    	/* 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;
    };
    
    
    Mark Spencer's avatar
    Mark Spencer committed
    static int pbx_builtin_prefix(struct ast_channel *, void *);
    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 *);
    static int pbx_builtin_wait(struct ast_channel *, void *);
    
    Mark Spencer's avatar
    Mark Spencer committed
    static int pbx_builtin_setlanguage(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 *);
    
    Mark Spencer's avatar
    Mark Spencer committed
    
    static struct pbx_builtin {
    	char name[AST_MAX_APP];
    	int (*execute)(struct ast_channel *chan, void *data);
    
    Mark Spencer's avatar
    Mark Spencer committed
    	char *synopsis;
    	char *description;
    
    Mark Spencer's avatar
    Mark Spencer committed
    } builtins[] = 
    {
    	/* These applications are built into the PBX core and do not
    	   need separate modules */
    
    Mark Spencer's avatar
    Mark Spencer committed
    	{ "Answer", pbx_builtin_answer, 
    
    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"   },
    
    
    Mark Spencer's avatar
    Mark Spencer committed
    	{ "Goto", pbx_builtin_goto, 
    
    Mark Spencer's avatar
    Mark Spencer committed
    "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" },
    
    
    Mark Spencer's avatar
    Mark Spencer committed
    	{ "Hangup", pbx_builtin_hangup,
    
    Mark Spencer's avatar
    Mark Spencer committed
    "Unconditional hangup",
    "  Hangup(): Unconditionally hangs up a given channel by returning -1 always.\n" },
    
    
    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" },
    
    
    Mark Spencer's avatar
    Mark Spencer committed
    	{ "ResponseTimeout", pbx_builtin_rtimeout,
    
    Mark Spencer's avatar
    Mark Spencer committed
    "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
    	{ "BackGround", pbx_builtin_background,
    
    Mark Spencer's avatar
    Mark Spencer committed
    "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" },
    
    
    Mark Spencer's avatar
    Mark Spencer committed
    	{ "Wait", pbx_builtin_wait, 
    
    Mark Spencer's avatar
    Mark Spencer committed
    "Waits for some time", 
    "  Wait(seconds): Waits for a specified number of seconds, then returns 0.\n" },
    
    	{ "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" },
    
    	{ "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" },
    
    	{ "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 select 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 'demo-\n"
    "congrats-fr' exists, then it will play that file, and if not will play the\n"
    "normal 'demo-congrats'. Always returns 0.\n"  },
    
    	{ "Ringing", pbx_builtin_ringing,
    "Indicate ringing tone",
    "  Ringing(): Request that the channel indicate ringing tone to the user.\n"
    "Always returns 0.\n" },
    
    	{ "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." },
    
    	{ "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." },
    
    
    Mark Spencer's avatar
    Mark Spencer committed
    };
    
    /* Lock for the application list */
    static pthread_mutex_t applock = PTHREAD_MUTEX_INITIALIZER;
    static struct ast_context *contexts = NULL;
    /* Lock for the ast_context list */
    static pthread_mutex_t conlock = PTHREAD_MUTEX_INITIALIZER;
    static struct ast_app *apps = NULL;
    
    
    Mark Spencer's avatar
    Mark Spencer committed
    /* Lock for switches */
    static pthread_mutex_t switchlock = PTHREAD_MUTEX_INITIALIZER;
    struct ast_switch *switches = NULL;
    
    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;
    	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
    		c->appl = app->name;
    		c->data = data;		
    
    Mark Spencer's avatar
    Mark Spencer committed
    		res = execute(c, data);
    
    Mark Spencer's avatar
    Mark Spencer committed
    		c->appl = NULL;
    		c->data = NULL;		
    
    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
    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
    	if (ast_pthread_mutex_lock(&applock)) {
    
    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
    	ast_pthread_mutex_unlock(&applock);
    
    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;
    	if (ast_pthread_mutex_lock(&switchlock)) {
    		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;
    	}
    	ast_pthread_mutex_unlock(&switchlock);
    	return asw;
    }
    
    
    Mark Spencer's avatar
    Mark Spencer committed
    static void pbx_destroy(struct ast_pbx *p)
    {
    	free(p);
    }
    
    
    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 (!strcasecmp(pattern, data))
    		return 1;
    	/* All patterns begin with _ */
    	if (pattern[0] != '_') 
    		return 0;
    	/* Start optimistic */
    	match=1;
    	pattern++;
    
    Mark Spencer's avatar
    Mark Spencer committed
    	while(match && *data && *pattern && (*pattern != '/')) {
    
    Mark Spencer's avatar
    Mark Spencer committed
    		switch(toupper(*pattern)) {
    		case 'N':
    			if ((*data < '2') || (*data > '9'))
    				match=0;
    			break;
    		case 'X':
    			if ((*data < '0') || (*data > '9'))
    				match = 0;
    			break;
    
    Mark Spencer's avatar
    Mark Spencer committed
    		case '.':
    			/* Must match */
    			return 1;
    		case ' ':
    		case '-':
    			/* Ignore these characters */
    			data--;
    			break;
    
    Mark Spencer's avatar
    Mark Spencer committed
    		default:
    			if (*data != *pattern)
    				match =0;
    		}
    		data++;
    		pattern++;
    	}
    
    Mark Spencer's avatar
    Mark Spencer committed
    	/* 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 match;
    	/* If "data" is longer, it can'be a subset of pattern */
    	if (strlen(pattern) < strlen(data)) 
    		return 0;
    	
    
    Mark Spencer's avatar
    Mark Spencer committed
    	
    	if (!strlen((char *)data) || !strncasecmp(pattern, data, strlen(data))) {
    
    Mark Spencer's avatar
    Mark Spencer committed
    		return 1;
    	}
    	/* All patterns begin with _ */
    	if (pattern[0] != '_') 
    		return 0;
    	/* Start optimistic */
    	match=1;
    	pattern++;
    
    Mark Spencer's avatar
    Mark Spencer committed
    	while(match && *data && *pattern && (*pattern != '/')) {
    
    Mark Spencer's avatar
    Mark Spencer committed
    		switch(toupper(*pattern)) {
    		case 'N':
    			if ((*data < '2') || (*data > '9'))
    				match=0;
    			break;
    		case 'X':
    			if ((*data < '0') || (*data > '9'))
    				match = 0;
    			break;
    
    Mark Spencer's avatar
    Mark Spencer committed
    		case '.':
    			/* Must match */
    			return 1;
    		case ' ':
    		case '-':
    			/* Ignore these characters */
    			data--;
    			break;
    
    Mark Spencer's avatar
    Mark Spencer committed
    		default:
    			if (*data != *pattern)
    				match =0;
    		}
    		data++;
    		pattern++;
    	}
    	return match;
    }
    
    
    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
    	ast_pthread_mutex_lock(&conlock);
    	if (name) {
    		tmp = contexts;
    		while(tmp) {
    			if (!strcasecmp(name, tmp->name))
    				break;
    			tmp = tmp->next;
    		}
    	} else
    		tmp = contexts;
    	ast_pthread_mutex_unlock(&conlock);
    
    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 (strlen(cidpattern))
    		failresult = 0;
    	else
    		failresult = 1;
    
    	if (!callerid)
    		return failresult;
    
    	/* Copy original Caller*ID */
    	strncpy(tmp, callerid, sizeof(tmp));
    	/* 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 */
    		if (!strcasecmp(tmp->name, context)) {
    			if (*status < STATUS_NO_EXTENSION)
    				*status = STATUS_NO_EXTENSION;
    			eroot = tmp->root;
    			while(eroot) {
    				/* Match extension */
    
    Mark Spencer's avatar
    Mark Spencer committed
    				if ((ast_extension_match(eroot->exten, exten) ||
    						((action == HELPER_CANMATCH) && (extension_close(eroot->exten, exten)))) &&
    						(!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;
    					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 ((e = pbx_find_extension(chan, i->name, exten, priority, callerid, action, incstack, stacklen, status, swo, data))) 
    
    Mark Spencer's avatar
    Mark Spencer committed
    					return e;
    
    Mark Spencer's avatar
    Mark Spencer committed
    				if (*swo) 
    					return NULL;
    
    Mark Spencer's avatar
    Mark Spencer committed
    				i = i->next;
    			}
    		}
    		tmp = tmp->next;
    	}
    	return NULL;
    }
    
    
    Mark Spencer's avatar
    Mark Spencer committed
    static int pbx_extension_helper(struct ast_channel *c, char *context, char *exten, int priority, char *callerid, int action) 
    
    Mark Spencer's avatar
    Mark Spencer committed
    {
    	struct ast_exten *e;
    
    Mark Spencer's avatar
    Mark Spencer committed
    	struct ast_app *app;
    
    Mark Spencer's avatar
    Mark Spencer committed
    	struct ast_switch *sw;
    	char *data;
    
    Mark Spencer's avatar
    Mark Spencer committed
    	int newstack = 0;
    
    Mark Spencer's avatar
    Mark Spencer committed
    	int res;
    
    Mark Spencer's avatar
    Mark Spencer committed
    	int status = 0;
    	char *incstack[AST_PBX_MAX_STACK];
    	int stacklen = 0;
    
    Mark Spencer's avatar
    Mark Spencer committed
    	if (ast_pthread_mutex_lock(&conlock)) {
    
    Mark Spencer's avatar
    Mark Spencer committed
    		ast_log(LOG_WARNING, "Unable to obtain lock\n");
    
    Mark Spencer's avatar
    Mark Spencer committed
    		if ((action == HELPER_EXISTS) || (action == HELPER_CANMATCH))
    
    Mark Spencer's avatar
    Mark Spencer committed
    			return 0;
    		else
    			return -1;
    	}
    
    Mark Spencer's avatar
    Mark Spencer committed
    	e = pbx_find_extension(c, context, exten, priority, callerid, action, incstack, &stacklen, &status, &sw, &data);
    
    Mark Spencer's avatar
    Mark Spencer committed
    	if (e) {
    		switch(action) {
    		case HELPER_CANMATCH:
    			pthread_mutex_unlock(&conlock);
    			return -1;
    		case HELPER_EXISTS:
    			pthread_mutex_unlock(&conlock);
    			return -1;
    		case HELPER_SPAWN:
    			newstack++;
    			/* Fall through */
    		case HELPER_EXEC:
    			app = pbx_findapp(e->app);
    			pthread_mutex_unlock(&conlock);
    			if (app) {
    				strncpy(c->context, context, sizeof(c->context));
    				strncpy(c->exten, exten, sizeof(c->exten));
    				c->priority = priority;
    				if (option_debug)
    						ast_log(LOG_DEBUG, "Launching '%s'\n", app->name);
    				else if (option_verbose > 2)
    						ast_verbose( VERBOSE_PREFIX_3 "Executing %s(\"%s\", \"%s\") %s\n", 
    								app->name, c->name, (e->data ? (char *)e->data : NULL), (newstack ? "in new stack" : "in same stack"));
    
    Mark Spencer's avatar
    Mark Spencer committed
    				res = pbx_exec(c, app, e->data, newstack);
    
    Mark Spencer's avatar
    Mark Spencer committed
    				return res;
    			} else {
    				ast_log(LOG_WARNING, "No application '%s' for extension (%s, %s, %d)\n", e->app, context, exten, priority);
    				return -1;
    			}
    		default:
    			ast_log(LOG_WARNING, "Huh (%d)?\n", action);
    			return -1;
    		}
    
    Mark Spencer's avatar
    Mark Spencer committed
    	} else if (sw) {
    		switch(action) {
    		case HELPER_CANMATCH:
    			pthread_mutex_unlock(&conlock);
    			return -1;
    		case HELPER_EXISTS:
    			pthread_mutex_unlock(&conlock);
    			return -1;
    		case HELPER_SPAWN:
    			newstack++;
    			/* Fall through */
    		case HELPER_EXEC:
    			pthread_mutex_unlock(&conlock);
    			if (sw->exec)
    				res = sw->exec(c, context, exten, priority, callerid, newstack, data);
    			else {
    				ast_log(LOG_WARNING, "No execution engine for switch %s\n", sw->name);
    				res = -1;
    			}
    			return res;
    		default:
    			ast_log(LOG_WARNING, "Huh (%d)?\n", action);
    			return -1;
    		}
    
    Mark Spencer's avatar
    Mark Spencer committed
    	} else {
    		pthread_mutex_unlock(&conlock);
    		switch(status) {
    		case STATUS_NO_CONTEXT:
    			if (action != HELPER_EXISTS)
    				ast_log(LOG_NOTICE, "Cannot find extension context '%s'\n", context);
    			break;
    		case STATUS_NO_EXTENSION:
    			if ((action != HELPER_EXISTS) && (action !=  HELPER_CANMATCH))
    				ast_log(LOG_NOTICE, "Cannot find extension '%s' in context '%s'\n", exten, context);
    			break;
    		case STATUS_NO_PRIORITY:
    			if ((action != HELPER_EXISTS) && (action !=  HELPER_CANMATCH))
    				ast_log(LOG_NOTICE, "No such priority %d in extension '%s' in context '%s'\n", priority, exten, context);
    			break;
    		default:
    			ast_log(LOG_DEBUG, "Shouldn't happen!\n");
    		}
    		if ((action != HELPER_EXISTS) && (action != HELPER_CANMATCH))
    			return -1;
    		else
    			return 0;
    	}
    
    
    Mark Spencer's avatar
    Mark Spencer committed
    }
    
    Mark Spencer's avatar
    Mark Spencer committed
    #if 0
    
    Mark Spencer's avatar
    Mark Spencer committed
    int ast_pbx_longest_extension(char *context) 
    {
    
    Mark Spencer's avatar
    Mark Spencer committed
    	/* XXX Not include-aware XXX */
    
    Mark Spencer's avatar
    Mark Spencer committed
    	struct ast_context *tmp;
    	struct ast_exten *e;
    	int len = 0;
    
    Mark Spencer's avatar
    Mark Spencer committed
    	if (ast_pthread_mutex_lock(&conlock)) {
    
    Mark Spencer's avatar
    Mark Spencer committed
    		ast_log(LOG_WARNING, "Unable to obtain lock\n");
    		return -1;
    	}
    	tmp = contexts;
    	while(tmp) {
    		if (!strcasecmp(tmp->name, context)) {
    			/* By locking tmp, not only can the state of its entries not
    			   change, but it cannot be destroyed either. */
    
    Mark Spencer's avatar
    Mark Spencer committed
    			ast_pthread_mutex_lock(&tmp->lock);
    
    Mark Spencer's avatar
    Mark Spencer committed
    			/* But we can relieve the conlock, as tmp will not change */
    
    Mark Spencer's avatar
    Mark Spencer committed
    			ast_pthread_mutex_unlock(&conlock);
    
    Mark Spencer's avatar
    Mark Spencer committed
    			e = tmp->root;
    			while(e) {
    				if (strlen(e->exten) > len)
    					len = strlen(e->exten);
    				e = e->next;
    			}
    
    Mark Spencer's avatar
    Mark Spencer committed
    			ast_pthread_mutex_unlock(&tmp->lock);
    
    Mark Spencer's avatar
    Mark Spencer committed
    			return len;
    		}
    		tmp = tmp->next;
    	}
    	ast_log(LOG_WARNING, "No such context '%s'\n", context);
    	return -1;
    }
    
    Mark Spencer's avatar
    Mark Spencer committed
    #endif
    
    Mark Spencer's avatar
    Mark Spencer committed
    int ast_exists_extension(struct ast_channel *c, char *context, char *exten, int priority, char *callerid) 
    
    Mark Spencer's avatar
    Mark Spencer committed
    {
    
    Mark Spencer's avatar
    Mark Spencer committed
    	return pbx_extension_helper(c, context, exten, priority, callerid, HELPER_EXISTS);
    
    Mark Spencer's avatar
    Mark Spencer committed
    int ast_canmatch_extension(struct ast_channel *c, char *context, char *exten, int priority, char *callerid)
    
    Mark Spencer's avatar
    Mark Spencer committed
    {
    
    Mark Spencer's avatar
    Mark Spencer committed
    	return pbx_extension_helper(c, context, exten, priority, callerid, HELPER_CANMATCH);
    
    Mark Spencer's avatar
    Mark Spencer committed
    int ast_spawn_extension(struct ast_channel *c, char *context, char *exten, int priority, char *callerid) 
    
    Mark Spencer's avatar
    Mark Spencer committed
    {
    
    Mark Spencer's avatar
    Mark Spencer committed
    	return pbx_extension_helper(c, context, exten, priority, callerid, HELPER_SPAWN);
    
    Mark Spencer's avatar
    Mark Spencer committed
    int ast_pbx_run(struct ast_channel *c)
    
    Mark Spencer's avatar
    Mark Spencer committed
    {
    	int firstpass = 1;
    	char digit;
    	char exten[256];
    	int pos;
    	int waittime;
    
    Mark Spencer's avatar
    Mark Spencer committed
    	int res=0;
    
    Mark Spencer's avatar
    Mark Spencer committed
    
    	/* A little initial setup here */
    	if (c->pbx)
    		ast_log(LOG_WARNING, "%s already has PBX structure??\n");
    	c->pbx = malloc(sizeof(struct ast_pbx));
    	if (!c->pbx) {
    		ast_log(LOG_WARNING, "Out of memory\n");
    		return -1;
    	}
    	memset(c->pbx, 0, sizeof(struct ast_pbx));
    	/* Set reasonable defaults */
    	c->pbx->rtimeout = 10;
    	c->pbx->dtimeout = 5;
    
    
    Mark Spencer's avatar
    Mark Spencer committed
    	if (option_debug)
    		ast_log(LOG_DEBUG, "PBX_THREAD(%s)\n", c->name);
    
    Mark Spencer's avatar
    Mark Spencer committed
    	else if (option_verbose > 1) {
    		if (c->callerid)
    			ast_verbose( VERBOSE_PREFIX_2 "Accepting call on '%s' (%s)\n", c->name, c->callerid);
    		else
    			ast_verbose( VERBOSE_PREFIX_2 "Accepting call on '%s'\n", c->name);
    	}
    
    Mark Spencer's avatar
    Mark Spencer committed
    		
    	
    	/* Start by trying whatever the channel is set to */
    
    Mark Spencer's avatar
    Mark Spencer committed
    	if (!ast_exists_extension(c, c->context, c->exten, c->priority, c->callerid)) {
    
    Mark Spencer's avatar
    Mark Spencer committed
    		strncpy(c->context, "default", sizeof(c->context));
    		strncpy(c->exten, "s", sizeof(c->exten));
    		c->priority = 1;
    	}
    	for(;;) {
    		pos = 0;
    		digit = 0;
    
    Mark Spencer's avatar
    Mark Spencer committed
    		while(ast_exists_extension(c, c->context, c->exten, c->priority, c->callerid)) {
    
    Mark Spencer's avatar
    Mark Spencer committed
    			memset(exten, 0, sizeof(exten));
    
    Mark Spencer's avatar
    Mark Spencer committed
    			if ((res = ast_spawn_extension(c, c->context, c->exten, c->priority, c->callerid))) {
    
    Mark Spencer's avatar
    Mark Spencer committed
    				/* Something bad happened, or a hangup has been requested. */
    
    Mark Spencer's avatar
    Mark Spencer committed
    				switch(res) {
    				case AST_PBX_KEEPALIVE:
    					if (option_debug)
    						ast_log(LOG_DEBUG, "Spawn extension (%s,%s,%d) exited KEEPALIVE on '%s'\n", c->context, c->exten, c->priority, c->name);
    					else if (option_verbose > 1)
    						ast_verbose( VERBOSE_PREFIX_2 "Spawn extension (%s, %s, %d) exited KEEPALIVE on '%s'\n", c->context, c->exten, c->priority, c->name);
    				break;
    				default:
    					if (option_debug)
    						ast_log(LOG_DEBUG, "Spawn extension (%s,%s,%d) exited non-zero on '%s'\n", c->context, c->exten, c->priority, c->name);
    					else if (option_verbose > 1)
    						ast_verbose( VERBOSE_PREFIX_2 "Spawn extension (%s, %s, %d) exited non-zero on '%s'\n", c->context, c->exten, c->priority, c->name);
    				}
    
    Mark Spencer's avatar
    Mark Spencer committed
    				goto out;
    			}
    
    Mark Spencer's avatar
    Mark Spencer committed
    			if (c->softhangup) {
    				ast_log(LOG_WARNING, "Extension %s, priority %d returned normally even though call was hung up\n",
    					c->exten, c->priority);
    				goto out;
    			}
    
    Mark Spencer's avatar
    Mark Spencer committed
    			/* If we're playing something in the background, wait for it to finish or for a digit */
    
    Mark Spencer's avatar
    Mark Spencer committed
    			if (c->stream) {
    
    Mark Spencer's avatar
    Mark Spencer committed
    				digit = ast_waitstream(c, AST_DIGIT_ANY);
    				ast_stopstream(c);
    				/* Hang up if something goes wrong */
    
    Mark Spencer's avatar
    Mark Spencer committed
    				if (digit < 0) {
    					if (option_verbose > 2)
    						ast_verbose(VERBOSE_PREFIX_3 "Lost connection on %s\n", c->name);
    
    Mark Spencer's avatar
    Mark Spencer committed
    					goto out;
    
    Mark Spencer's avatar
    Mark Spencer committed
    				}
    
    Mark Spencer's avatar
    Mark Spencer committed
    				else if (digit) {
    					exten[pos++] = digit;
    					break;
    				}
    			}
    			firstpass = 0;
    			c->priority++;
    		}
    
    Mark Spencer's avatar
    Mark Spencer committed
    		if (!ast_exists_extension(c, c->context, c->exten, 1, c->callerid)) {
    
    Mark Spencer's avatar
    Mark Spencer committed
    			/* It's not a valid extension anymore */
    
    Mark Spencer's avatar
    Mark Spencer committed
    			if (ast_exists_extension(c, c->context, "i", 1, c->callerid)) {
    
    Mark Spencer's avatar
    Mark Spencer committed
    				if (option_verbose > 2)
    					ast_verbose(VERBOSE_PREFIX_3 "Sent into invalid extension '%s' in context '%s' on %s\n", c->exten, c->context, c->name);
    				strncpy(c->exten, "i", sizeof(c->exten));
    				c->priority = 1;
    			} else {
    				ast_log(LOG_WARNING, "Channel '%s' sent into invalid extension '%s' in context '%s', but no invalid handler\n",
    					c->name, c->exten, c->context);
    
    Mark Spencer's avatar
    Mark Spencer committed
    				goto out;
    
    Mark Spencer's avatar
    Mark Spencer committed
    			}
    
    Mark Spencer's avatar
    Mark Spencer committed
    		} else {
    
    Mark Spencer's avatar
    Mark Spencer committed
    			/* Done, wait for an extension */
    			if (digit)
    				waittime = c->pbx->dtimeout;
    			else
    				waittime = c->pbx->rtimeout;
    
    Mark Spencer's avatar
    Mark Spencer committed
    			while(!ast_exists_extension(c, c->context, exten, 1, c->callerid) && 
    			       ast_canmatch_extension(c, c->context, exten, 1, c->callerid)) {
    
    Mark Spencer's avatar
    Mark Spencer committed
    				/* As long as we're willing to wait, and as long as it's not defined, 
    				   keep reading digits until we can't possibly get a right answer anymore.  */
    				digit = ast_waitfordigit(c, waittime * 1000);
    				if (!digit)
    					/* No entry */
    					break;
    				if (digit < 0)
    					/* Error, maybe a  hangup */
    
    Mark Spencer's avatar
    Mark Spencer committed
    					goto out;
    
    Mark Spencer's avatar
    Mark Spencer committed
    				exten[pos++] = digit;
    				waittime = c->pbx->dtimeout;
    			}
    
    Mark Spencer's avatar
    Mark Spencer committed
    			if (ast_exists_extension(c, c->context, exten, 1, c->callerid)) {
    
    Mark Spencer's avatar
    Mark Spencer committed
    				/* Prepare the next cycle */
    				strncpy(c->exten, exten, sizeof(c->exten));
    				c->priority = 1;
    
    Mark Spencer's avatar
    Mark Spencer committed
    			} else {
    
    Mark Spencer's avatar
    Mark Spencer committed
    				/* No such extension */
    				if (strlen(exten)) {
    					/* An invalid extension */
    
    Mark Spencer's avatar
    Mark Spencer committed
    					if (ast_exists_extension(c, c->context, "i", 1, c->callerid)) {
    
    Mark Spencer's avatar
    Mark Spencer committed
    						if (option_verbose > 2)
    							ast_verbose( VERBOSE_PREFIX_3 "Invalid extension '%s' in context '%s' on %s\n", exten, c->context, c->name);
    						strncpy(c->exten, "i", sizeof(c->exten));
    						c->priority = 1;
    					} else {
    						ast_log(LOG_WARNING, "Invalid extension, but no rule 'i' in context '%s'\n", c->context);
    						goto out;
    					}
    
    Mark Spencer's avatar
    Mark Spencer committed
    				} else {
    
    Mark Spencer's avatar
    Mark Spencer committed
    					/* A simple timeout */
    
    Mark Spencer's avatar
    Mark Spencer committed
    					if (ast_exists_extension(c, c->context, "t", 1, c->callerid)) {
    
    Mark Spencer's avatar
    Mark Spencer committed
    						if (option_verbose > 2)
    							ast_verbose( VERBOSE_PREFIX_3 "Timeout on %s\n", c->name);
    						strncpy(c->exten, "t", sizeof(c->exten));
    						c->priority = 1;
    					} else {
    						ast_log(LOG_WARNING, "Timeout, but no rule 't' in context '%s'\n", c->context);
    						goto out;
    					}
    				}	
    			}
    
    Mark Spencer's avatar
    Mark Spencer committed
    		}
    	}
    	if (firstpass) 
    		ast_log(LOG_WARNING, "Don't know what to do with '%s'\n", c->name);
    out:
    	pbx_destroy(c->pbx);
    	c->pbx = NULL;
    
    Mark Spencer's avatar
    Mark Spencer committed
    	if (res != AST_PBX_KEEPALIVE)
    		ast_hangup(c);
    
    Mark Spencer's avatar
    Mark Spencer committed
    	return 0;
    }
    
    static void *pbx_thread(void *data)
    {
    	/* Oh joyeous kernel, we're a new thread, with nothing to do but
    	   answer this channel and get it going.  The setjmp stuff is fairly
    	   confusing, but necessary to get smooth transitions between
    	   the execution of different applications (without the use of
    	   additional threads) */
    	struct ast_channel *c = data;
    	ast_pbx_run(c);
    
    Mark Spencer's avatar
    Mark Spencer committed
    	pthread_exit(NULL);
    
    Mark Spencer's avatar
    Mark Spencer committed
    	return NULL;
    
    Mark Spencer's avatar
    Mark Spencer committed
    }
    
    int ast_pbx_start(struct ast_channel *c)
    {
    	pthread_t t;
    
    Mark Spencer's avatar
    Mark Spencer committed
    	pthread_attr_t attr;
    
    Mark Spencer's avatar
    Mark Spencer committed
    	if (!c) {
    		ast_log(LOG_WARNING, "Asked to start thread on NULL channel?\n");
    		return -1;
    	}
    	/* Start a new thread, and get something handling this channel. */
    
    Mark Spencer's avatar
    Mark Spencer committed
    	pthread_attr_init(&attr);
    	pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
    	if (pthread_create(&t, &attr, pbx_thread, c)) {
    
    Mark Spencer's avatar
    Mark Spencer committed
    		ast_log(LOG_WARNING, "Failed to create new channel thread\n");
    		return -1;
    	}
    	return 0;
    }
    
    Mark Spencer's avatar
    Mark Spencer committed
    
    /*
     * This function locks contexts list by &conlist, search for the rigt context
     * structure, leave context list locked and call ast_context_remove_include2
     * which removes include, unlock contexts list and return ...
     */
    int ast_context_remove_include(char *context, char *include, char *registrar)
    {
    	struct ast_context *c;
    
    	if (ast_lock_contexts()) return -1;
    
    	/* walk contexts and search for the right one ...*/
    	c = ast_walk_contexts(NULL);
    	while (c) {
    		/* we found one ... */
    		if (!strcmp(ast_get_context_name(c), context)) {
    			int ret;
    			/* remove include from this context ... */	
    			ret = ast_context_remove_include2(c, include, registrar);
    
    			ast_unlock_contexts();
    
    			/* ... return results */
    			return ret;
    		}
    		c = ast_walk_contexts(c);
    	}
    
    	/* we can't find the right one context */
    	ast_unlock_contexts();
    	return -1;
    }
    
    /*
     * When we call this function, &conlock lock must be locked, because when
     * we giving *con argument, some process can remove/change this context
     * and after that there can be segfault.
     *
     * This function locks given context, removes include, unlock context and
     * return.
     */
    int ast_context_remove_include2(struct ast_context *con, char *include, char *registrar)
    {
    	struct ast_include *i, *pi = NULL;
    
    	if (pthread_mutex_lock(&con->lock)) return -1;
    
    	/* walk includes */
    	i = con->includes;
    	while (i) {
    		/* find our include */
    		if (!strcmp(i->name, include) && 
    			(!strcmp(i->registrar, registrar) || !registrar)) {
    			/* remove from list */
    			if (pi)
    				pi->next = i->next;
    			else
    				con->includes = i->next;
    			/* free include and return */
    			free(i);
    			ast_pthread_mutex_unlock(&con->lock);
    			return 0;
    		}
    		pi = i;
    		i = i->next;
    	}
    
    	/* we can't find the right include */
    	ast_pthread_mutex_unlock(&con->lock);
    	return -1;
    }
    
    /*
     * This function locks contexts list by &conlist, search for the rigt context
     * structure, leave context list locked and call ast_context_remove_switch2
     * which removes switch, unlock contexts list and return ...
     */
    int ast_context_remove_switch(char *context, char *sw, char *data, char *registrar)
    
    Mark Spencer's avatar
    Mark Spencer committed
    {
    
    Mark Spencer's avatar
    Mark Spencer committed
    	struct ast_context *c;
    
    	if (ast_lock_contexts()) return -1;
    
    	/* walk contexts and search for the right one ...*/
    	c = ast_walk_contexts(NULL);
    	while (c) {
    		/* we found one ... */
    		if (!strcmp(ast_get_context_name(c), context)) {
    			int ret;
    			/* remove switch from this context ... */	
    			ret = ast_context_remove_switch2(c, sw, data, registrar);
    
    			ast_unlock_contexts();