/* ====================================================================
 * Copyright (c) 1995 The Apache Group.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer. 
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. All advertising materials mentioning features or use of this
 *    software must display the following acknowledgment:
 *    "This product includes software developed by the Apache Group
 *    for use in the Apache HTTP server project (http://www.apache.org/)."
 *
 * 4. The names "Apache Server" and "Apache Group" must not be used to
 *    endorse or promote products derived from this software without
 *    prior written permission.
 *
 * 5. Redistributions of any form whatsoever must retain the following
 *    acknowledgment:
 *    "This product includes software developed by the Apache Group
 *    for use in the Apache HTTP server project (http://www.apache.org/)."
 *
 * THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``AS IS'' AND ANY
 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE APACHE GROUP OR
 * IT'S CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Group and was originally based
 * on public domain software written at the National Center for
 * Supercomputing Applications, University of Illinois, Urbana-Champaign.
 * For more information on the Apache Group and the Apache HTTP server
 * project, please see <http://www.apache.org/>.
 *
 */

/********
 Add to Configuration file:
	Module external_auth_module    mod_auth_external.o

Add to server configuration file:
	AddExternalAuth <keyword> <path-to-authenticator>
	AddExternalGroup <keyword> <path-to-group-checker>

Usage in auth config files:

	AuthExternal <keyword>
	AuthExternal afs
	GroupExternal <keyword>
	GroupExternal unix

AuthExternals are passed the userid and passwd in the USER and PASS 
environment variables, and return a success code of 0 to indicate
successful authentication. Non-zero result indicates either a failure to 
authenticate, or a failure to execute the authenticator.

GroupExternals are passed the userid and desired group in the USER and GROUP
environment variables, and return a success code of 0 to indicate successful
authentication. Non-zero result indicates non-membersip or a failure
to execute the group checker.

The need for this module arises from difficulties I have had linking 
apache with other libraries (such as AFS, and database access libs).

Comments/questions/etc. to nneul@umr.edu

********/

/*
 * External authentication module by nneul@umr.edu
 */

#include "httpd.h"
#include "http_config.h"
#include "http_core.h"
#include "http_log.h"
#include "http_protocol.h"
#include <sys/wait.h>

/*
 * Structure for the module itself
 */

module external_auth_module;

/*
 *  Data types for per-dir and server configuration
 */
typedef struct
{
	char *auth_extname;
	char *group_extname;
} extauth_dir_config_rec;

typedef struct 
{
	table *auth_externals;
	table *group_externals;
} extauth_server_config_rec;

/*
 * Creators for per-dir and server configurations
 */

void *create_extauth_dir_config (pool *p, char *d)
{
	return pcalloc (p, sizeof(extauth_dir_config_rec));
}


void *create_extauth_server_config ( pool *p, server_rec *s)
{
	extauth_server_config_rec *scr;

	scr = (extauth_server_config_rec *) palloc(p,
	    sizeof(extauth_server_config_rec) );

	scr->auth_externals = make_table(p, 4);
	scr->group_externals = make_table(p, 4);

	return (void *)scr;
}

/*
 * Handler for a server config line - add a external type to the
 * server configuration
 */

char *add_extauth(cmd_parms *cmd, void *dummy, char *keyword, char *path)
{
	extauth_server_config_rec *sc_rec;

	sc_rec = get_module_config( cmd->server->module_config,
	    &external_auth_module);

	table_set ( sc_rec->auth_externals, keyword, path );

	return NULL;
}

/*
 * Handler for a server config line - add a external type to the
 * server configuration
 */

char *add_extgroup(cmd_parms *cmd, void *dummy, char *keyword, char *path)
{
	extauth_server_config_rec *sc_rec;

	sc_rec = get_module_config( cmd->server->module_config,
	    &external_auth_module);

	table_set ( sc_rec->group_externals, keyword, path );

	return NULL;
}


/*
 * Commands that this module can handle
 */

command_rec extauth_cmds[] = {
	{ "AuthExternal", set_string_slot, 
	(void*)XtOffsetOf(extauth_dir_config_rec,auth_extname),
	OR_AUTHCFG, TAKE1, "a keyword indicating which authenticator to use" },

	{ "AddExternalAuth", add_extauth, NULL, RSRC_CONF, TAKE2,
	"a keyword followed by a path to the authenticator program" },

	{ "GroupExternal", set_string_slot, 
	(void*)XtOffsetOf(extauth_dir_config_rec,group_extname),
	OR_AUTHCFG, TAKE1, "a keyword indicating which group checker to use" },

	{ "AddExternalGroup", add_extgroup, NULL, RSRC_CONF, TAKE2,
	"a keyword followed by a path to the group check program" },
	{ NULL }
};




/*
 * Authenticate a user
 */

int extauth_basic_user (request_rec *r)
{
	extauth_dir_config_rec *dir_config_rec =
	    (extauth_dir_config_rec *)get_module_config (r->per_dir_config,
	    &external_auth_module);

	extauth_server_config_rec *server_config_rec =
	    (extauth_server_config_rec *)get_module_config (r->server->module_config,
	    &external_auth_module);

	char *sent_pw;

	char errstr[MAX_STRING_LEN];
	char env_user[MAX_STRING_LEN];
	char env_pass[MAX_STRING_LEN];
	int res, code;
	char *external, *extname, *extpath;

	conn_rec *c = r->connection;

	/* Get the password, exit if can't get */
	if ((res = get_basic_auth_pw (r, &sent_pw)))
		return res;

	/* Extract which external was chosen */
	extname = dir_config_rec->auth_extname;

	/* Check if we are supposed to handle this authentication */
	if ( !extname )
	{
		return DECLINED;
	}


	/* Get the path associated with that external */
	if (extpath = table_get (server_config_rec->auth_externals, extname))
	{
		/* Set envir vars for the userid and password */
		sprintf(env_user, "%s=%s", "USER", c->user);
		sprintf(env_pass, "%s=%s", "PASS", sent_pw);
		putenv(env_user);
		putenv(env_pass);

		code = system(extpath);

		if(code)
		{
			sprintf(errstr, "External Auth (%s): Failed (%d) for user %s pass %s", 
				extname, code, c->user, sent_pw);
			log_reason(errstr, r->filename, r);
			note_basic_auth_failure(r);
			return AUTH_REQUIRED;
		}
		return OK;
	}
	else
	{
		sprintf(errstr, "External Auth: Invalid external keyword (%s)", extname);
		log_reason(errstr, r->filename, r);
		note_basic_auth_failure(r);
		return AUTH_REQUIRED;
	}


	/* shouldn't get here */
	return OK;
}


int extauth_check_auth(request_rec *r) 
{
	extauth_dir_config_rec *dir_config_rec =
	    (extauth_dir_config_rec *)get_module_config (r->per_dir_config,
	    &external_auth_module);

	extauth_server_config_rec *server_config_rec =
	    (extauth_server_config_rec *)get_module_config (r->server->module_config,
	    &external_auth_module);

	conn_rec *c = r->connection;

	int m = r->method_number;
	char errstr[MAX_STRING_LEN];

	char env_user[MAX_STRING_LEN];
	char env_group[MAX_STRING_LEN];
	int res, code;
	char *external, *extname, *extpath;
    
	array_header *reqs_arr = requires (r);
	require_line *reqs = reqs_arr ? (require_line *)reqs_arr->elts : NULL;

	int x;
	char *t, *w;

	/* Extract which external was chosen */
	extname = dir_config_rec->group_extname;

	/* Check if we are supposed to handle this authentication */
	if ( !extname )
	{
		return DECLINED;
	}

	if (!reqs_arr) return DECLINED;
    
	for(x=0; x < reqs_arr->nelts; x++) 
	{
		if (! (reqs[x].method_mask & (1 << m))) continue;
	
		t = reqs[x].requirement;
		w = getword(r->pool, &t, ' ');
	
	        if(!strcmp(w,"valid-user"))
	            return OK;
	        if(!strcmp(w,"user")) 
		{
	            while(t[0]) 
		    {
                	w = getword_conf (r->pool, &t);
                	if(!strcmp(c->user,w))
				return OK;
		    }
		}
		else if( !strcmp(w,"group") ) 
		{
			while(t[0]) 
			{
				w = getword(r->pool, &t, ' ');

	/* Get the path associated with that external */
				if (extpath = table_get (server_config_rec->group_externals, extname))
				{
					/* Set envir vars for the userid and password */
					sprintf(env_user, "%s=%s", "USER", c->user);
					sprintf(env_group, "%s=%s", "GROUP", w);
					putenv(env_user);
					putenv(env_group);

					code = system(extpath);
					if ( !code ) return OK;
				}
				else
				{
					sprintf(errstr, "External Group: Invalid external keyword (%s)", extname);
					log_reason(errstr, r->filename, r);
					note_basic_auth_failure(r);
					return AUTH_REQUIRED;
				}
			}
		}
	}
    
	return DECLINED;
}




module external_auth_module = {
	STANDARD_MODULE_STUFF,
	    NULL,			/* initializer */
	create_extauth_dir_config,	/* dir config creater */
	NULL,			/* dir merger --- default is to override */
	create_extauth_server_config,	/* server config */
	NULL,			/* merge server config */
	extauth_cmds,		/* command table */
	NULL,			/* handlers */
	NULL,			/* filename translation */
	extauth_basic_user,	/* check_user_id */
	extauth_check_auth,			/* check auth */
	NULL,			/* check access */
	NULL,			/* type_checker */
	NULL,			/* fixups */
	NULL				/* logger */
};
