#include "sbox.h"

#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <libgen.h>
#include <stdarg.h>
#include <string.h>
#include <strings.h>
#include <unistd.h>
#include <time.h>
#include <pwd.h>
#include <grp.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/param.h>
#include <sys/stat.h>
//#if SET_LIMITS
#include <sys/resource.h>
//#endif

// The dotconf library to parse /etc/sbox.conf
#include <dotconf.h>

//#define DEBUG 1

/* DESCRIPTION
   sbox is designed to allow untrusted users to run CGI scripts without endangering
   the security of the site as a whole.
   $Revision: 1.8 $

   Call as "http://your.site.com/cgi-bin/sbox/path/to/end_user/script"

   1. sbox does a series of checks to confirm that it has been called in correct context
      a. user ID is WEB_USER
      b. group ID is WEB_GROUP
      c. neither of these is root
    2. sbox fetches the target script named in PATH_TRANSLATED
      a. actually, it walks down the path until it finds the first executable file
    3. sbox performs checks on the target script
      a. script is not SUID or SGID
      b. script is executable
      c. script is not writable by WEB_USER or WEB_GROUP
      d. directory that script lives in is not writable by WEB_USER or WEB_GROUP
    4. sbox determines user and group of owner of the script file or its enclosing directory
    5. sbox changes its uid and gid to match the script's file or directory
    6. sbox checks that the script is within the owner's home directory
    7. sbox chroots to the new root directory
    8. sbox fixes PATH_TRANSLATED and SCRIPT_NAME for chroot change
    9. sbox sets resource limits
    10. sbox logs everything
    11. sbox execs script
 */

/* Copyright info:
 * Copyright 1997, Lincoln D. Stein
 *
 *  Parts of this code are derived from suexec.c, Copyright 1995-1997 The Apache Group
 */

#ifndef MAXPATHLEN
  #ifdef PATH_MAX
     #define MAXPATHLEN PATH_MAX
  #else
     #define MAXPATHLEN 8192
  #endif
#endif

#ifndef NAME_MAX
#define NAME_MAX 512
#endif

#define AP_ENVBUF 256
extern char **environ; 

/* needed to compile with -ansi */
#ifndef strdup
extern char *strdup (const char *);
#endif

#ifndef chroot
extern int chroot (const char *path);
#endif

static char **cleanenv = NULL;
static FILE *log;

static void open_log();
static void log_error(const char* fmt, ...);
static void fatal_error(const char* fmt, ...);
static void check_consistency();
static char* fetch_target(char *root,char** additional_info,
			  struct stat* targ,struct stat* dir);
static char* to_abs(char* directory);
static char* document_root ();
static void check_target(const char* newroot,
			 const char* target,
			 const struct stat *file_stats,
			 const struct stat *dir_stats);
static char* fetch_newroot(char* docroot);
static char* shave(char* newroot,
		   char* target);
static void clean_env();
static void tweak_environment(char* newroot,
			      char* root,
			      char* target,
			      char* additional_info);
static int set_env(const char *name, 
		   const char *value, 
		   int overwrite);
static char* escape(const char* str);
static void chdir_fix(char* newroot, char* target);

//#if SET_LIMITS
static void set_limits();
//#endif

static char *safe_env_lst[] =
{
    "AUTH_TYPE",
    "CONTENT_LENGTH",
    "CONTENT_TYPE",
    "DATE_GMT",
    "DATE_LOCAL",
    "DOCUMENT_NAME",
    "DOCUMENT_PATH_INFO",
    "DOCUMENT_URI",
    "FILEPATH_INFO",
    "GATEWAY_INTERFACE",
    "LAST_MODIFIED",
    "QUERY_STRING",
    "QUERY_STRING_UNESCAPED",
    "REMOTE_ADDR",
    "REMOTE_HOST",
    "REMOTE_IDENT",
    "REMOTE_PORT",
    "REMOTE_USER",
    "REDIRECT_QUERY_STRING",
    "REDIRECT_STATUS",
    "REDIRECT_URL",
    "REQUEST_METHOD",
    "REQUEST_URI",
    "SCRIPT_URI",
    "SCRIPT_URL",
    "SERVER_ADMIN",
    "SERVER_NAME",
    "SERVER_PORT",
    "SERVER_PROTOCOL",
    "SERVER_SOFTWARE",
    "USER_NAME",
    "TZ",
// #if !DO_CHROOT
//    "SCRIPT_NAME",
//    "PATH_INFO",
//    "PATH_TRANSLATED",
//    "DOCUMENT_ROOT",
//    "SCRIPT_FILENAME",
// #endif
    NULL
};

/***************** SBOX libdotconf config ***************/
typedef struct{
// UID and GID that runs sbox by default
	char* web_user;
	char* web_group;
	int do_suid;
	int do_sgid;

	int do_log_envvars;

	int allow_web_owned_scripts;

	int uid_min;
	int uid_max;
	int gid_min;
	int gid_max;
	int sid_mode_directory;

	int echo_failures;

	int do_chroot;
	char* safe_path;
	int use_safe_path;
	char* log_file;
	char* root;
	char* cgi_bin;

	int set_limits;
	int priority;
	long limit_cpu_hard;
	long limit_cpu_soft;
	long limit_fsize_hard;
	long limit_fsize_soft;
	long limit_data_hard;
	long limit_data_soft;
	long limit_stack_hard;
	long limit_stack_soft;
	long limit_core_hard;
	long limit_core_soft;
	long limit_rss_hard;
	long limit_rss_soft;
	int limit_nproc_hard;
	int limit_nproc_soft;
	int limit_nofile_hard;
	int limit_nofile_soft;

	char* php_path;
	char* python_path;
	char* perl_path;
	char* ruby_path;
}sbox_config_t;
sbox_config_t sbox_config;

DOTCONF_CB(cb_web_user);
DOTCONF_CB(cb_web_group);
DOTCONF_CB(cb_do_suid);
DOTCONF_CB(cb_do_sgid);
DOTCONF_CB(cb_do_log_envvars);
DOTCONF_CB(cb_allow_web_owned_scripts);
DOTCONF_CB(cb_uid_min);
DOTCONF_CB(cb_uid_max);
DOTCONF_CB(cb_gid_min);
DOTCONF_CB(cb_gid_max);
DOTCONF_CB(cb_sid_mode_directory);
DOTCONF_CB(cb_echo_failures);
DOTCONF_CB(cb_do_chroot);
DOTCONF_CB(cb_safe_path);
DOTCONF_CB(cb_use_safe_path);
DOTCONF_CB(cb_log_file);
DOTCONF_CB(cb_root);
DOTCONF_CB(cb_cgi_bin);
DOTCONF_CB(cb_set_limits);
DOTCONF_CB(cb_priority);
DOTCONF_CB(cb_limit_cpu_hard);
DOTCONF_CB(cb_limit_cpu_soft);
DOTCONF_CB(cb_limit_fsize_hard);
DOTCONF_CB(cb_limit_fsize_soft);
DOTCONF_CB(cb_limit_data_hard);
DOTCONF_CB(cb_limit_data_soft);
DOTCONF_CB(cb_limit_stack_hard);
DOTCONF_CB(cb_limit_stack_soft);
DOTCONF_CB(cb_limit_core_hard);
DOTCONF_CB(cb_limit_core_soft);
DOTCONF_CB(cb_limit_rss_hard);
DOTCONF_CB(cb_limit_rss_soft);
DOTCONF_CB(cb_limit_nproc_hard);
DOTCONF_CB(cb_limit_nproc_soft);
DOTCONF_CB(cb_limit_nofile_hard);
DOTCONF_CB(cb_limit_nofile_soft);
DOTCONF_CB(cb_php_path);
DOTCONF_CB(cb_python_path);
DOTCONF_CB(cb_perl_path);
DOTCONF_CB(cb_ruby_path);

static configoption_t options[] = {
	{"web_user",                ARG_STR,    cb_web_user, NULL, 0},
	{"web_group",               ARG_STR,    cb_web_group, NULL, 0},
	{"do_suid",                 ARG_TOGGLE, cb_do_suid, 0, 0},
	{"do_sgid",                 ARG_TOGGLE, cb_do_sgid, 0, 0},
	{"do_log_envvars",          ARG_TOGGLE, cb_do_log_envvars, 0, 0},
	{"allow_web_owned_scripts", ARG_TOGGLE, cb_allow_web_owned_scripts, 0, 0},
	{"uid_min",                 ARG_INT,    cb_uid_min, 0, 0},
	{"uid_max",                 ARG_INT,    cb_uid_max, 0, 0},
	{"gid_min",                 ARG_INT,    cb_gid_min, 0, 0},
	{"gid_max",                 ARG_INT,    cb_gid_max, 0, 0},
	{"sid_mode_directory",      ARG_TOGGLE, cb_sid_mode_directory, 0, 0},
	{"echo_failures",           ARG_TOGGLE, cb_echo_failures, 0, 0},
	{"do_chroot",               ARG_TOGGLE, cb_do_chroot, 0, 0},
	{"safe_path",               ARG_STR,    cb_safe_path, NULL, 0},
	{"use_safe_path",           ARG_TOGGLE, cb_use_safe_path, 0, 0},
	{"log_file",                ARG_STR,    cb_log_file, NULL, 0},
	{"root",                    ARG_STR,    cb_root, NULL, 0},
	{"cgi_bin",                 ARG_STR,    cb_cgi_bin, NULL, 0},
	{"set_limits",              ARG_TOGGLE, cb_set_limits, 0, 0},
	{"priority",                ARG_INT,    cb_priority, 0, 0},
	{"limit_cpu_hard",          ARG_INT,    cb_limit_cpu_hard, 0, 0},
	{"limit_cpu_soft",          ARG_INT,    cb_limit_cpu_soft, 0, 0},
	{"limit_fsize_hard",        ARG_INT,    cb_limit_fsize_hard, 0, 0},
	{"limit_fsize_soft",        ARG_INT,    cb_limit_fsize_soft, 0, 0},
	{"limit_data_hard",         ARG_INT,    cb_limit_data_hard, 0, 0},
	{"limit_data_soft",         ARG_INT,    cb_limit_data_soft, 0, 0},
	{"limit_stack_hard",        ARG_INT,    cb_limit_stack_hard, 0, 0},
	{"limit_stack_soft",        ARG_INT,    cb_limit_stack_soft, 0, 0},
	{"limit_core_hard",         ARG_INT,    cb_limit_core_hard, 0, 0},
	{"limit_core_soft",         ARG_INT,    cb_limit_core_soft, 0, 0},
	{"limit_rss_hard",          ARG_INT,    cb_limit_rss_hard, 0, 0},
	{"limit_rss_soft",          ARG_INT,    cb_limit_rss_soft, 0, 0},
	{"limit_nproc_hard",        ARG_INT,    cb_limit_nproc_hard, 0, 0},
	{"limit_nproc_soft",        ARG_INT,    cb_limit_nproc_soft, 0, 0},
	{"limit_nofile_hard",       ARG_INT,    cb_limit_nofile_hard, 0, 0},
	{"limit_nofile_soft",       ARG_INT,    cb_limit_nofile_soft, 0, 0},
	{"php_path",                ARG_STR,    cb_php_path, NULL, 0},
	{"python_path",             ARG_STR,    cb_python_path, NULL, 0},
	{"perl_path",               ARG_STR,    cb_perl_path, NULL, 0},
	{"ruby_path",               ARG_STR,    cb_ruby_path, NULL, 0},
	LAST_OPTION
};
DOTCONF_CB(cb_web_user){
	sbox_config.web_user = (char*)malloc(strlen(cmd->data.str)+1);
	strcpy(sbox_config.web_user,cmd->data.str);
	return NULL;
}
DOTCONF_CB(cb_web_group){
	sbox_config.web_group = (char*)malloc(strlen(cmd->data.str)+1);
	strcpy(sbox_config.web_group,cmd->data.str);
	return NULL;
}
DOTCONF_CB(cb_do_suid){
	sbox_config.do_suid = cmd->data.value;
	return NULL;
}
DOTCONF_CB(cb_do_sgid){
	sbox_config.do_sgid = cmd->data.value;
	return NULL;
}
DOTCONF_CB(cb_do_log_envvars){
	sbox_config.do_log_envvars = cmd->data.value;
	return NULL;
}
DOTCONF_CB(cb_allow_web_owned_scripts){
	sbox_config.allow_web_owned_scripts = cmd->data.value;
	return NULL;
}
DOTCONF_CB(cb_uid_min){
	sbox_config.uid_min = cmd->data.value;
	return NULL;
}
DOTCONF_CB(cb_uid_max){
	sbox_config.uid_max = cmd->data.value;
	return NULL;
}
DOTCONF_CB(cb_gid_min){
	sbox_config.gid_min = cmd->data.value;
	return NULL;
}
DOTCONF_CB(cb_gid_max){
	sbox_config.gid_max = cmd->data.value;
	return NULL;
}
DOTCONF_CB(cb_sid_mode_directory){
	sbox_config.sid_mode_directory = cmd->data.value;
	return NULL;
}
DOTCONF_CB(cb_echo_failures){
	sbox_config.echo_failures = cmd->data.value;
	return NULL;
}
DOTCONF_CB(cb_do_chroot){
	sbox_config.do_chroot = cmd->data.value;
	return NULL;
}
DOTCONF_CB(cb_safe_path){
	sbox_config.safe_path = (char*)malloc(strlen(cmd->data.str)+1);
	strcpy(sbox_config.safe_path,cmd->data.str);
	return NULL;
}
DOTCONF_CB(cb_use_safe_path){
	sbox_config.use_safe_path = cmd->data.value;
	return NULL;
}
DOTCONF_CB(cb_log_file){
	sbox_config.log_file = (char*)malloc(strlen(cmd->data.str)+1);
	strcpy(sbox_config.log_file,cmd->data.str);
	return NULL;
}
DOTCONF_CB(cb_root){
	sbox_config.root = (char*)malloc(strlen(cmd->data.str)+1);
	strcpy(sbox_config.root,cmd->data.str);
	return NULL;
}
DOTCONF_CB(cb_cgi_bin){
	sbox_config.cgi_bin = (char*)malloc(strlen(cmd->data.str)+1);
	strcpy(sbox_config.cgi_bin,cmd->data.str);
	return NULL;
}

DOTCONF_CB(cb_set_limits){
	sbox_config.set_limits = cmd->data.value;
	return NULL;
}
DOTCONF_CB(cb_priority){
	sbox_config.priority = cmd->data.value;
	return NULL;
}
DOTCONF_CB(cb_limit_cpu_hard){
	sbox_config.limit_cpu_hard = cmd->data.value;
	return NULL;
}
DOTCONF_CB(cb_limit_cpu_soft){
	sbox_config.limit_cpu_soft = cmd->data.value;
	return NULL;
}
DOTCONF_CB(cb_limit_fsize_hard){
	sbox_config.limit_fsize_hard = cmd->data.value * 1024;
	return NULL;
}
DOTCONF_CB(cb_limit_fsize_soft){
	sbox_config.limit_fsize_soft = cmd->data.value * 1024;
	return NULL;
}
DOTCONF_CB(cb_limit_data_hard){
	sbox_config.limit_data_hard = cmd->data.value * 1024;
	return NULL;
}
DOTCONF_CB(cb_limit_data_soft){
	sbox_config.limit_data_soft = cmd->data.value * 1024;
	return NULL;
}
DOTCONF_CB(cb_limit_stack_hard){
	sbox_config.limit_stack_hard = cmd->data.value * 1024;
	return NULL;
}
DOTCONF_CB(cb_limit_stack_soft){
	sbox_config.limit_stack_soft = cmd->data.value * 1024;
	return NULL;
}
DOTCONF_CB(cb_limit_core_hard){
	sbox_config.limit_core_hard = cmd->data.value * 1024;
	return NULL;
}
DOTCONF_CB(cb_limit_core_soft){
	sbox_config.limit_core_soft = cmd->data.value * 1024;
	return NULL;
}
DOTCONF_CB(cb_limit_rss_hard){
	sbox_config.limit_rss_hard = cmd->data.value * 1024;
	return NULL;
}
DOTCONF_CB(cb_limit_rss_soft){
	sbox_config.limit_rss_soft = cmd->data.value * 1024;
	return NULL;
}
DOTCONF_CB(cb_limit_nproc_hard){
	sbox_config.limit_nproc_hard = cmd->data.value;
	return NULL;
}
DOTCONF_CB(cb_limit_nproc_soft){
	sbox_config.limit_nproc_soft = cmd->data.value;
	return NULL;
}
DOTCONF_CB(cb_limit_nofile_hard){
	sbox_config.limit_nofile_hard = cmd->data.value;
	return NULL;
}
DOTCONF_CB(cb_limit_nofile_soft){
	sbox_config.limit_nofile_soft = cmd->data.value;
	return NULL;
}
DOTCONF_CB(cb_php_path){
	sbox_config.php_path = (char*)malloc(strlen(cmd->data.str)+1);
	strcpy(sbox_config.php_path,cmd->data.str);
	return NULL;
}
DOTCONF_CB(cb_python_path){
	sbox_config.python_path = (char*)malloc(strlen(cmd->data.str)+1);
	strcpy(sbox_config.python_path,cmd->data.str);
	return NULL;
}
DOTCONF_CB(cb_perl_path){
	sbox_config.perl_path = (char*)malloc(strlen(cmd->data.str)+1);
	strcpy(sbox_config.perl_path,cmd->data.str);
	return NULL;
}
DOTCONF_CB(cb_ruby_path){
	sbox_config.ruby_path = (char*)malloc(strlen(cmd->data.str)+1);
	strcpy(sbox_config.ruby_path,cmd->data.str);
	return NULL;
}

void read_config_file(char* sboxconf_path){
	configfile_t *configfile;
	configfile = dotconf_create(sboxconf_path, options, 0, CASE_INSENSITIVE);
	if (dotconf_command_loop(configfile) == 0){
		fprintf(stderr, "Error reading config file\n");
		exit(2);
	}
	dotconf_cleanup(configfile);
	return;
}

// Maxmimum string size for an environment name or value:
#define MAXENV 1024

// Get the HTTP_HOST environment variable value
// Returns NULL if not found
char* get_http_host(char** e){
	char *name,*delimiter;
	static char envvar_name[MAXENV+2];      // Stores the current env var name, make sure it's big enough by adding 2 safety chars
	while ((name = *e++)) {  
		delimiter = (char*) strchr(name,'=');
		if (delimiter == NULL) continue;        // If we don't find the "=" delimiter, then we didn't find anything...
		if (delimiter - name >= MAXENV) continue;       // If our envvar name is too big, then it's as if we didn't find anything
		if (strlen(delimiter) > MAXENV) continue;
		strncpy(envvar_name,name,delimiter-name);        // Copy the envvar name in a buffer, to check for it later
		envvar_name[delimiter-name]='\0';                // Make sure it terminates by a delimiting zero
		delimiter++;                            // Point just right after the = sign
		if( strcmp(envvar_name,"HTTP_HOST") == 0){       // Have we found the HTTP_HOST?
			// log_error("%s => %s\n",envvar_name,delimiter);   // Log the HTTP_HOST in our sbox.log
			return delimiter;
		}
	}
	return NULL;
}

// Debug function to print the environment values in the sbox.log
// Do not activate all the time, as its printing quite some stuff,
// and flooding a logfile is never a good idea.
void print_the_env(char** e){
	char *name,*delimiter;
	static char nm[MAXENV+2];
	while ((name = *e++)) {  
		delimiter = (char*) strchr(name,'=');
		if (delimiter == NULL) continue;
		if (delimiter - name >= MAXENV) continue;
		if (strlen(delimiter) > MAXENV) continue;
		strncpy(nm,name,delimiter-name);
		nm[delimiter-name]='\0';
		log_error("%s => %s\n",nm,++delimiter);
	}
}

int isToggleValueOn(char* t){
	if( strcmp(t,"On") == 0 || strcmp(t,"on") == 0 || strcmp(t,"1") == 0 || strcmp(t,"ON") == 0)
		return 1;
	else
		return 0;
}
// This function will read the environment variables of
// Apache, so that you can eventually set the configuration
// of SBOX in it in order to overwrite what is in /etc/sbox.conf
//
// This gives the additional functionality to be able to have
// specific values depending on which vhost you run.
//
// For example, in your apache config file, you can do:
// SetEnv SBOX_DTC_CONF_web_user 100
// in order to overwrite the "web_user" value.
// Of course, you will need the "mod_env" apache module to do that.
void readEnvSboxConfig(char** e){
	char *name,*delimiter;
	static char nm[MAXENV];
	while ((name = *e++)) {
		delimiter = (char*) strchr(name,'=');
		if (delimiter == 0) continue;
		if (delimiter - name >= MAXENV) continue;
		if (strlen(delimiter) > MAXENV) continue;
		strncpy(nm,name,delimiter-name);
		nm[delimiter-name]='\0';
		delimiter++;
		if( strcmp(nm,"SBOX_DTC_CONF_web_user") == 0)			sbox_config.web_user = delimiter;
		if( strcmp(nm,"SBOX_DTC_CONF_web_group") == 0)			sbox_config.web_group = delimiter;
		if( strcmp(nm,"SBOX_DTC_CONF_allow_web_owned_scripts") == 0)	sbox_config.allow_web_owned_scripts = isToggleValueOn(delimiter);
		if( strcmp(nm,"SBOX_DTC_CONF_uid_min") == 0)			sbox_config.uid_min = atoi(delimiter);
		if( strcmp(nm,"SBOX_DTC_CONF_uid_max") == 0)			sbox_config.uid_max = atoi(delimiter);
		if( strcmp(nm,"SBOX_DTC_CONF_gid_min") == 0)			sbox_config.gid_min = atoi(delimiter);
		if( strcmp(nm,"SBOX_DTC_CONF_gid_max") == 0)			sbox_config.gid_max = atoi(delimiter);
		if( strcmp(nm,"SBOX_DTC_CONF_sid_mode_directory") == 0)		sbox_config.sid_mode_directory = isToggleValueOn(delimiter);
		if( strcmp(nm,"SBOX_DTC_CONF_use_safe_path") == 0)		sbox_config.use_safe_path = isToggleValueOn(delimiter);
		if( strcmp(nm,"SBOX_DTC_CONF_safe_path") == 0)			sbox_config.safe_path = delimiter;
		if( strcmp(nm,"SBOX_DTC_CONF_log_file") == 0)			sbox_config.log_file = delimiter;
		if( strcmp(nm,"SBOX_DTC_CONF_do_log_envvars") == 0)		sbox_config.do_log_envvars = isToggleValueOn(delimiter);
		if( strcmp(nm,"SBOX_DTC_CONF_echo_failures") == 0)		sbox_config.echo_failures = isToggleValueOn(delimiter);
		if( strcmp(nm,"SBOX_DTC_CONF_do_chroot") == 0)			sbox_config.do_chroot = isToggleValueOn(delimiter);
		if( strcmp(nm,"SBOX_DTC_CONF_root") == 0)			sbox_config.root = delimiter;
		if( strcmp(nm,"SBOX_DTC_CONF_cgi_bin") == 0)			sbox_config.cgi_bin = delimiter;
		if( strcmp(nm,"SBOX_DTC_CONF_do_suid") == 0)			sbox_config.do_suid = isToggleValueOn(delimiter);
		if( strcmp(nm,"SBOX_DTC_CONF_do_sgid") == 0)			sbox_config.do_sgid = isToggleValueOn(delimiter);
		if( strcmp(nm,"SBOX_DTC_CONF_set_limits") == 0)			sbox_config.set_limits = isToggleValueOn(delimiter);
		if( strcmp(nm,"SBOX_DTC_CONF_priority") == 0)			sbox_config.priority = atoi(delimiter);
		if( strcmp(nm,"SBOX_DTC_CONF_limit_cpu_hard") == 0)		sbox_config.limit_cpu_hard = atol(delimiter);
		if( strcmp(nm,"SBOX_DTC_CONF_limit_cpu_soft") == 0)		sbox_config.limit_cpu_soft = atol(delimiter);
		if( strcmp(nm,"SBOX_DTC_CONF_limit_fsize_hard") == 0)		sbox_config.limit_fsize_hard = 1024*atol(delimiter);
		if( strcmp(nm,"SBOX_DTC_CONF_limit_fsize_soft") == 0)		sbox_config.limit_fsize_soft = 1024*atol(delimiter);
		if( strcmp(nm,"SBOX_DTC_CONF_limit_data_hard") == 0)		sbox_config.limit_data_hard = 1024*atol(delimiter);
		if( strcmp(nm,"SBOX_DTC_CONF_limit_data_soft") == 0)		sbox_config.limit_data_soft = 1024*atol(delimiter);
		if( strcmp(nm,"SBOX_DTC_CONF_stack_hard") == 0)			sbox_config.limit_stack_hard = 1024*atol(delimiter);
		if( strcmp(nm,"SBOX_DTC_CONF_limit_stack_soft") == 0)		sbox_config.limit_stack_soft = 1024*atol(delimiter);
		if( strcmp(nm,"SBOX_DTC_CONF_limit_core_hard") == 0)		sbox_config.limit_core_hard = 1024*atol(delimiter);
		if( strcmp(nm,"SBOX_DTC_CONF_limit_core_soft") == 0)		sbox_config.limit_core_soft = 1024*atol(delimiter);
		if( strcmp(nm,"SBOX_DTC_CONF_limit_rss_hard") == 0)		sbox_config.limit_rss_hard = 1024*atol(delimiter);
		if( strcmp(nm,"SBOX_DTC_CONF_limit_rss_soft") == 0)		sbox_config.limit_rss_soft = 1024*atol(delimiter);
		if( strcmp(nm,"SBOX_DTC_CONF_limit_nproc_hard") == 0)		sbox_config.limit_nproc_hard = atol(delimiter);
		if( strcmp(nm,"SBOX_DTC_CONF_limit_nproc_soft") == 0)		sbox_config.limit_nproc_soft = atol(delimiter);
		if( strcmp(nm,"SBOX_DTC_CONF_limit_nofile_hard") == 0)		sbox_config.limit_nofile_hard = atol(delimiter);
		if( strcmp(nm,"SBOX_DTC_CONF_limit_nofile_soft") == 0)		sbox_config.limit_nofile_soft = atol(delimiter);
	}
}

/*****************  START OF CODE ****************/

char* getFileExtension(char* file){
	int len,i;

	len = strlen(file);
	for(i=len-1 ; i>0 ; --i){
		if( file[i] == '.'){
			return &file[i];
		}
	}
	return 0;
}

#define HOST_CONF_FILE_FOLDER "/etc/sbox/vhosts.d/"
int main (int argc, char* argv[], char** e) {
	struct stat target_stat,dir_stat;
	char *target,*newroot,*root,*additional_info,*cmd,*new_cmd_interp;
	int gid,uid,i,return_int;
	char* my_http_host;
	char* ext;
	struct stat stat_buffer;
	char* http_host_config_file_path;
	int conf_file_path_string_size;
	char realpath_path[MAXPATHLEN+2];
	char* dirname_path;
	char* dirname_path2;
	FILE* fp;

	////////////////////////// GET THE PATH OF THE SBOX CONFIG DEPENDING ON THE HTTP_HOST ENV VAR //////////////////////////
	//sbox_config.log_file = "/var/log/sbox.log";
	//open_log();
	//log_error("Testing log\n");
	my_http_host = get_http_host(e);	// Get the current vhost name
	if(my_http_host == NULL){
		sbox_config.log_file = "/var/log/sbox.log";
		open_log();
		log_error("HTTP_HOST environment variable not found: exiting.\n");
		exit(1);
	}
	if(strlen(my_http_host) > 1024){
		sbox_config.log_file = "/var/log/sbox.log";
		open_log();
		log_error("HTTP_HOST environment variable too big: exiting.\n");
		exit(1);
	}
	conf_file_path_string_size = strlen(HOST_CONF_FILE_FOLDER) + strlen(my_http_host) + 2;
	http_host_config_file_path = malloc(conf_file_path_string_size);
	if(http_host_config_file_path == NULL){
		sbox_config.log_file = "/var/log/sbox.log";
		open_log();
		log_error("Could not alloc space for storing HTTP_HOST: exiting.\n");
		exit(1);
	}
	strcpy(http_host_config_file_path,HOST_CONF_FILE_FOLDER);
	strcat(http_host_config_file_path,my_http_host);
	// log_error("Concat file is: \"%s\"\n",http_host_config_file_path);
	if(!realpath(http_host_config_file_path,realpath_path)){
		// If not resolved, open the default config file
		//log_error("realpath returned NULL: opening default /etc/sbox/sbox.conf\n");
		read_config_file("/etc/sbox/sbox.conf");
	}else{
		// If resolved, then there may be a vhost specific file that can be opened!
		log_error("Realpath is: %s\n",realpath_path);
		dirname_path = strdup(realpath_path);
		dirname_path2 = dirname(dirname_path);
		//log_error("dirname_path2 is: %s\n",dirname_path2);
		strcat(dirname_path2,"/");
		if( strcmp(dirname_path,HOST_CONF_FILE_FOLDER) != 0 ){
			sbox_config.log_file = "/var/log/sbox.log";
			open_log();
			log_error("Directory traversal attempt: exiting.\n");
			exit(1);
		}

		// Get to know if the file exists, if it does use it as config file, if not use /etc/sbox/sbox.conf
		fp = fopen(realpath_path,"r");
		if(fp == NULL){
			//log_error("File %s doesn't exist or can't be read, using /etc/sbox/sbox.conf",realpath_path);
			read_config_file("/etc/sbox/sbox.conf");
		}else{
			//log_error("File exist: using %s\n",realpath_path);
			fclose(fp);
			read_config_file(realpath_path);
		}
	}
	// Used for debug purpose: do ont use in production, as this is very easy
	// to hack a change in the environment of Apache
	// readEnvSboxConfig(e);
#if defined(DEBUG)
	printf("Web user: %s\n",sbox_config.web_user);
	printf("Web group: %s\n",sbox_config.web_group);
	printf("do_suid: %d\n",sbox_config.do_suid);
	printf("do_guid: %d\n",sbox_config.do_sgid);
	printf("uid_min: %d\n",sbox_config.uid_min);
	printf("uid_max: %d\n",sbox_config.uid_max);
	printf("gid_min: %d\n",sbox_config.gid_min);
	printf("gid_max: %d\n",sbox_config.gid_max);
	printf("sid_mode_directory: %d\n",sbox_config.sid_mode_directory);
	printf("echo_failures: %d\n",sbox_config.echo_failures);
	printf("do_chroot: %d\n",sbox_config.do_chroot);
	printf("safe_path: %s\n",sbox_config.safe_path);
	printf("safe_path_switch: %d\n",sbox_config.safe_path_switch);
	printf("log_file: %s\n",sbox_config.log_file);
	printf("root: %s\n",sbox_config.root);
	printf("cgi_bin: %s\n",sbox_config.cgi_bin);
	printf("set_limits: %d\n",sbox_config.set_limits);
	printf("priority: %d\n",sbox_config.priority);
	printf("limit_cpu_hard: %ld\n",sbox_config.limit_cpu_hard);
	printf("limit_cpu_soft: %ld\n",sbox_config.limit_cpu_soft);
	printf("limit_fsize_hard: %ld\n",sbox_config.limit_fsize_hard);
	printf("limit_fsize_soft: %ld\n",sbox_config.limit_fsize_soft);
	printf("limit_data_hard: %ld\n",sbox_config.limit_data_hard);
	printf("limit_data_soft: %ld\n",sbox_config.limit_data_soft);
	printf("limit_stack_hard: %ld\n",sbox_config.limit_stack_hard);
	printf("limit_stack_soft: %ld\n",sbox_config.limit_stack_soft);
	printf("limit_core_hard: %ld\n",sbox_config.limit_core_hard);
	printf("limit_core_soft: %ld\n",sbox_config.limit_core_soft);
	printf("limit_rss_hard: %ld\n",sbox_config.limit_rss_hard);
	printf("limit_rss_soft: %ld\n",sbox_config.limit_rss_soft);
	printf("limit_nproc_hard: %d\n",sbox_config.limit_nproc_hard);
	printf("limit_nproc_soft: %d\n",sbox_config.limit_nproc_soft);
	printf("limit_nofile_hard: %d\n",sbox_config.limit_nofile_hard);
	printf("limit_nofile_soft: %d\n",sbox_config.limit_nofile_soft);
#endif

	open_log();

	if(sbox_config.do_log_envvars){
		print_the_env(e);
	}

	check_consistency();

	/* figure out the base of the user's HTML document tree */
	root = document_root();


	/* resolve the additional path information correctly */
	target = fetch_target(root,&additional_info,&target_stat,&dir_stat);

	if(sbox_config.do_chroot){
		/* find the absolute path name of the root */
		to_abs(root);

		/* calculate the new root for chroot*/
		newroot = fetch_newroot(root);
	}

	/* check that the target is OK */
	check_target(newroot,target,&target_stat,&dir_stat);

	if(sbox_config.do_chroot){
		/* fix the environment */
		tweak_environment(newroot,root,target,additional_info);

#if !defined(DEBUG)
		/* change to the owner's root */
		if (chroot(newroot) < 0)
			fatal_error("couldn't chroot to %s (%s)\n",escape(newroot),strerror(errno));
#endif
	}

#if defined(DEBUG)
	cmd = target;
#else
	if(sbox_config.do_chroot){
		cmd = shave(newroot,target);
	}else{
		cmd = target;
	}
#endif

	clean_env();

	/* set hard and soft limits on resource usage */
	/* important to do this after log is closed because otherwise the log file 
	  size will be restricted by the LIMIT_FSIZE_SOFT value */
	if(sbox_config.set_limits)
		set_limits();


	/* set to the owner's uid and gid */
	if(sbox_config.do_suid || sbox_config.do_sgid){
		gid = sbox_config.sid_mode_directory == 1 ? dir_stat.st_gid : target_stat.st_gid;
		uid = sbox_config.sid_mode_directory == 1 ? dir_stat.st_uid : target_stat.st_uid;
#if defined(DEBUG)
		if (setgid(getgid()) < 0) {
			fatal_error("couldn't setgid() to %d (%s)\n",getgid(),strerror(errno));
		}
#else
		if(sbox_config.do_sgid){
			if (setgid(gid) < 0) {
				fatal_error("couldn't setgid() to %d (%s)\n",dir_stat.st_gid,strerror(errno));
			}
		}else{
			/* give up our sgid privileges if any*/
			if (setgid(getgid()) < 0) {
				fatal_error("couldn't setgid() to %d (%s)\n",getgid(),strerror(errno));
			}
		}
#endif

#if !defined(DEBUG)
		if(sbox_config.do_suid){
			if (setuid(uid) < 0) {
				fatal_error("couldn't setuid() to %d (%s)\n",dir_stat.st_uid,strerror(errno));
			}
		}
#endif
	}

	/* give up our root privileges now */
	if (setuid(getuid()) < 0) {
		fatal_error("couldn't setuid() to %d (%s)\n",getuid(),strerror(errno));
	}
  


	/* fix up argv[] array and command depending on the extension */
	ext = getFileExtension(cmd);
	if(ext == 0){
		new_cmd_interp = cmd;
		argv[0] = cmd;
		if(strlen(sbox_config.log_file) > 0){
			log_error("No extension found: starting as CGI: executing %s for uid %d, gid %d\n",target,getuid(),getgid());
		}
	}else{
		if( strcmp(ext,".php") == 0){
			new_cmd_interp = sbox_config.php_path;
		}else if(strcmp(ext,".py") == 0){
			new_cmd_interp = sbox_config.python_path;
		}else if(strcmp(ext,".pl") == 0){
			new_cmd_interp = sbox_config.perl_path;
		}else if(strcmp(ext,".rb") == 0){
			new_cmd_interp = sbox_config.ruby_path;
		}else{
			log_error("Extension not recognised: will exit here!\n");
			return -1;
		}
		argv[0] = new_cmd_interp;
		argv[1] = cmd;
		log_error("Found %s for %s: %s %s (%s for uid %d and gid %d)\n",ext,target,new_cmd_interp,argv[1],cleanenv[0],getuid(),getgid());
	}

	/* chdir() to new directory */
	chdir_fix(newroot,target);
	if(strlen(sbox_config.log_file) > 0 && ext == 0){
		log_error("Going to try this: %s , %s, %s\n", new_cmd_interp, argv[1], cleanenv[0]);
	}

	/* close log file so we don't leak file descriptor */
	if (log && log != stderr) {
		fp = log; log = NULL;
		fclose(fp);
	}

	/* execute the target */
	return_int = execve(new_cmd_interp,argv,cleanenv);

	/* if we get here, then something went wrong -- we won't be able to
	   reopen the log file because we've given up privileges, logging
	   to stderr causes an Apache "Premature end of script" error because
	   it's expecting a Content-Type header, so disable logging via
	   write_log entirely by setting log to NULL. */
	log = NULL;
	fatal_error("exec of %s failed (%s)\n",escape(new_cmd_interp),strerror(errno));

	return -1;
}

/* Will error out if one of the consistency checks fails. */
void check_consistency() {
	struct passwd *pass;
	struct group *grp;
	int uid,gid;

#if !defined(DEBUG)
	/* get our group and user ids */
	uid = getuid();
	if ((pass = getpwuid(uid)) == NULL)
		fatal_error("invalid uid: (%ld)\n", uid);

	gid = getgid();
	if ((grp = getgrgid(gid)) == NULL)
		fatal_error("invalid gid: (%ld)\n", gid);
  
	/* exit if either the uid or gid are zero */
	if (uid == 0)
		fatal_error("cannot be run as root\n");

	if (gid == 0)
		fatal_error("cannot be run as the root group\n");

	/* Make sure that we were invoked by the Web user and group */
	if (strcmp(sbox_config.web_user,pass->pw_name))
		fatal_error("invoked by %s, but must be run by %s\n",escape(pass->pw_name),escape(sbox_config.web_user));

	if (strcmp(sbox_config.web_group,grp->gr_name))
		fatal_error("invoked by group %s, but must be run by group %s\n",escape(grp->gr_name),escape(sbox_config.web_group));
#endif
}

void open_log () {
	if (strlen(sbox_config.log_file) > 0) {
		if ((log = fopen(sbox_config.log_file, "a")) == NULL) {
			fprintf(stderr, "sbox failed to open log file.  Falling back to stderr.\n");
			log = stderr;
		}
	} else {
		log = stderr;
	}
//  log = NULL;
}

static void write_log(const char* fmt, va_list ap) {
	time_t    timevar;
	char*     timestr;
  
	if (log == NULL) return;

	timevar = time(NULL);
	timestr = ctime(&timevar);
	timestr[strlen(timestr)-1]='\0';
  
	fprintf(log,"[%s] sbox[%d]: ",timestr,getpid());
	vfprintf(log, fmt, ap);
	fflush(log);

	return;
}

void log_error(const char* fmt, ...) {
	va_list ap;

	va_start(ap, fmt);
	write_log(fmt,ap);
	va_end(ap);
}

void fatal_error(const char* fmt, ...) {
	va_list ap;
	char* webmaster;

	va_start(ap, fmt);
	write_log(fmt,ap);

	if(sbox_config.echo_failures){
		webmaster = (char*)getenv("SERVER_ADMIN");

		fprintf(stdout,"Content-type: text/html\n\n");
		fprintf(stdout,webmaster ? "%s (<a href=\"mailto:%s\">%s</a>).": "%s",
			CANNED_ERROR_TOP,webmaster,webmaster);
		fprintf(stdout,"<BLOCKQUOTE><STRONG>");
		vprintf(fmt, ap);
		fprintf(stdout,"</STRONG></BLOCKQUOTE>%s",CANNED_ERROR_BOTTOM);
		fprintf(stdout,"<P><I>sbox version %3.2f</I><BR><I>%s</I></P><HR></BODY></HTML>",VERSION,"$Id: sbox.c,v 1.8 2007/06/18 14:40:03 thomas Exp $");
	}else{
		fprintf(stdout,"Content-type: text/html\n\n%s",CANNED_ERROR);
	}
	fflush(stdout);
	va_end(ap);
	exit(-1);
}

/* Find the physical path of a directory, following symbolic and 
   hard links. This transforms the argument in place, so it must
   be at least MAXPATHLEN in size! */
static char* to_abs(char* directory) {
	if (chdir(directory) < 0)
		fatal_error("Can't chdir() to %s: %s\n",escape(directory),strerror(errno));
	if (!getcwd(directory,MAXPATHLEN))
		fatal_error("Error during getcwd(): %s\n",strerror(errno));
	return directory;
}
#ifdef USE_ABSOLUTE_ROOT
char* document_root () {
	char *document_root;
	int pathlen;
	if (!(document_root = (char*) calloc(sizeof(char),MAXPATHLEN+1)))
		fatal_error("out of memory while allocating space for document root string\n");
	pathlen = strlen(USE_ABSOLUTE_ROOT);
	strncpy(document_root,USE_ABSOLUTE_ROOT, pathlen+1);
	document_root[pathlen+1] = '\0';
	return document_root;
}
#else
/* Find the document root by subtracting PATH_INFO from PATH_TRANSLATED */
char* document_root () {
	char *path_info,*path_translated,*document_root;
	int p,v,common;
	int pathlen;
    
	/* fetch the PATH_TRANSLATED environment variable */
	/* should print out usage information, actually */
	path_translated = (char*) getenv("PATH_TRANSLATED");
	if (path_translated == NULL)
	fatal_error("Please specify the script to run with the format: \"%s/script/to/run\".\n",
		escape((char*)getenv("SCRIPT_NAME")));

	/* fetch the PATH_TRANSLATED environment variable */
	/* should print out usage information, actually */
	path_info = (char*) getenv("PATH_INFO");
	if (path_info == NULL)
		fatal_error("please specify the script to run \"%s/script/to/run\"\n",
			escape((char*)getenv("SCRIPT_NAME")));
  
	/* find the document root by proceeding from right to left */
	for (common=p=strlen(path_translated),v=strlen(path_info);
		p>=0 && v>=0;
		p--,v--) {
		if (path_translated[p] != path_info[v])
			break;
		if (path_translated[p] == '/') 
			common = p;
	}
	if (path_translated[common] == '/')
		common--;

	/* now common points to the end of the document root */
	if (common+2 > MAXPATHLEN)
		fatal_error("path translated is larger than MAXPATHLEN: \"%s\"",path_translated);

	/* at this point, common points to the end of the document root */
  
	if (!(document_root = (char*) calloc(sizeof(char),MAXPATHLEN+1)))
		fatal_error("out of memory while allocating space for document root string\n");

	strncpy(document_root,path_translated,common+1);
	document_root[common+1] = '\0';
	return document_root;
}
#endif

/* Find the path to the target script and return it, along
 * with the additional path info, if any.  Also returns stat
 * structures for the target and its directory.
 * A side-effect is that the target's directory is made the current
 * working directory.
 */
char* fetch_target(char* root,char** additional,struct stat* starg,struct stat* sdir) {

	char *path_info,*path_translated,*dir=NULL,*path,*p;
	char *raw,*shaved,target[MAXPATHLEN+1],directory[MAXPATHLEN+1];
	int valid = 0;
	int additional_length,max;

	/* fetch the PATH_{TRANSLATED,INFO} environment variables */
	/* we will have errored out before this if these are undefined 
	   or zero length */
	path_translated = (char*) getenv("PATH_TRANSLATED");
	path_info = (char*) getenv("PATH_INFO");
	// log_error("path_info %s , path_translated %s\n", path_info, path_translated );

	if (path_info[0] != '/')
		fatal_error("PATH_INFO does not begin with a '/'\n");

	/* if this is the /~user type of path info, then the translated path is
	   the root, appended to CGI_BIN, appended to the shaved path */
	if (path_info[1] == '~')
		shaved = shave(root,path_translated);
	else
		shaved = path_info;
	
	//log_error("shaved %s\n", shaved);
	//log_error("root %s\n", root);
	//log_error("sbox_config.cgi_bin %s\n", sbox_config.cgi_bin);

	if (strlen(root)+1+strlen(sbox_config.cgi_bin) > MAXPATHLEN)
		fatal_error("Script directory path larger than MAXPATHLEN\n");
	strncpy(directory,root,MAXPATHLEN);
	directory[MAXPATHLEN] = '\0';
	strncat(directory,"/",1);
	strncat(directory,sbox_config.cgi_bin,strlen(sbox_config.cgi_bin));

	/* resolve symbolic links and relative paths */
	to_abs(directory);

	max = strlen(directory) + strlen(shaved) + 1;
	if (!(raw = (char*)calloc(sizeof(char),max)))
		fatal_error("Unable to allocate memory for path to CGI script: %s\n",strerror(errno));
	strncpy(raw,directory,max);
	strncat(raw,shaved,strlen(shaved));
	raw[max-1] = '\0';

	/* step down the path until we find the directory and the executable */
	p = raw+1;
	while ((p = strchr(p,'/'))) {
		if ( (p-raw) >  MAXPATHLEN)
			fatal_error("path_info too long\n");

		strncpy(target,raw,p-raw);
		target[p-raw] = '\0';

		/* make sure there are no ".." path components!!!! */
		if (strncmp(p,"/..",3) == 0)
			fatal_error("path to CGI script (%s) must not contain relative path components\n",escape(raw));

		if (stat(target,starg) < 0)
			fatal_error("Stat failed. %s: %s\n",escape(target),strerror(errno));

		/* if it's a directory, then copy it into dir for safe keeping */
		if (S_ISDIR(starg->st_mode))
			memcpy((void*)sdir,(void*)starg,sizeof(struct stat));
		else 
			if ((valid = S_ISREG(starg->st_mode)) == TRUE )
				break;
		dir = p;
		p++;
	}
	/* If the executable is the last item on the path, then we will not
	   have found a valid partial path.  Stat the whole thing. */
	if (!valid) {
		if (stat(raw,starg) < 0)
			fatal_error("Stat failed. %s: %s\n",escape(raw),strerror(errno));

		if (!S_ISREG(starg->st_mode))
			fatal_error("Couldn't find a valid script to execute in %s\n",escape(raw));

		p = raw + strlen(raw);
		strncpy(target,raw,MAXPATHLEN);
		target[MAXPATHLEN] = '\0';
	}

	/* Everything to the right of the end of target is additional path info */
	additional_length = strlen(raw) - strlen(target);
	if (!(*additional = (char*) calloc(sizeof(char),additional_length+1)))
		fatal_error("Unable to allocate memory for additional path info.\n");

	strncpy(*additional,raw+strlen(target),additional_length);
	(*additional)[additional_length] = '\0';

	/* turn the directory part of the target into a real directory, resolving
	 symbolic paths */
	strncpy(directory,target,dir-raw);
	directory[dir-raw]='\0';

	to_abs(directory);

	max = strlen(directory)+(p-dir)+1;
	if (!(path = (char*)calloc(sizeof(char),max)))
		fatal_error("unable to allocate memory during calloc() of physical path: %s\n",strerror(errno));

	strncpy(path,directory,max);
	strncat(path,dir,p-dir);
	path[max-1] = '\0';
	if (raw != NULL)
		free((void*)raw);
	return path;
}

/* implement a variety of checks on the script before executing it */
void check_target(const char* newroot,
		  const char* target,
		  const struct stat *file_stats,
		  const struct stat *dir_stats) {
	struct passwd *pass;
	struct group *grp;

#if !defined(DEBUG)
	/* 1) script must not be SUID or SGID*/
	if (file_stats->st_mode & S_ISUID)
		fatal_error("cannot run suid scripts (%s)\n",escape(target));

	if (file_stats->st_mode & S_ISGID)
		fatal_error("cannot run sgid scripts (%s)\n",escape(target));

	/* 2) script must be executable by other */
	if (!( (file_stats->st_mode & S_IXOTH)))
		fatal_error("%s not world executable. Make sure your script is chmod +x!\n",escape(target));

	/* 3) script is not owned by WEB_USER or WEB_GROUP */
	if ((pass = getpwuid(file_stats->st_uid)) == NULL)
		fatal_error("%s is owned by an unknown user (%ld)\n",escape(target),file_stats->st_uid);

	if(sbox_config.allow_web_owned_scripts){
		if (!(strcmp(pass->pw_name,sbox_config.web_user)))
			fatal_error("%s is owned by the Web user (%s)\n",escape(target),sbox_config.web_user);
	}


	if ((grp = getgrgid(file_stats->st_gid)) == NULL) 
		fatal_error("%s is owned by an unknown group (%ld)\n",escape(target),file_stats->st_gid);

	if(sbox_config.allow_web_owned_scripts){
		if (!(strcmp(grp->gr_name,sbox_config.web_group)))
			fatal_error("%s is owned by the Web group (%s)\n",escape(target),sbox_config.web_group);
	}
  
	/* 4) directory is not owned by WEB_USER or WEB_GROUP */
	if ((pass = getpwuid(dir_stats->st_uid)) == NULL)
		fatal_error("the directory containing %s is owned by an unknown user (%ld)\n",
			escape(target),dir_stats->st_uid);

	if(sbox_config.allow_web_owned_scripts){
		if (!(strcmp(pass->pw_name,sbox_config.web_user)))
			fatal_error("the directory containing %s is owned by the Web user (%s)\n",escape(target),sbox_config.web_user);
	}

	if ((grp = getgrgid(dir_stats->st_gid)) == NULL) 
		fatal_error("the directory containing %s is owned by an unknown group (%ld)\n",
			escape(target),dir_stats->st_gid);

	if(sbox_config.allow_web_owned_scripts){
		if (!(strcmp(grp->gr_name,sbox_config.web_group)))
			fatal_error("the directory containing %s is owned by the Web group (%s)\n",escape(target),sbox_config.web_group);
	}

	/* 5) Neither file nor the directory are writable by other */
	if (file_stats->st_mode & S_IWOTH)
		fatal_error("%s is world writable\n",escape(target));

	if (dir_stats->st_mode & S_IWOTH)
		fatal_error("the directory containing %s is world writable\n",escape(target));
  
	if(sbox_config.do_chroot){
		/* 6) target must be located within the new root */
		if (strstr(target,newroot) != target)
			fatal_error("%s is not contained within the chroot directory %s\n",escape(target),newroot);
	}

	/* 7) owner and group must not be less than UID_MIN, GID_MIN */
	if(sbox_config.do_suid){
		if(sbox_config.sid_mode_directory){
			if (dir_stats->st_uid < sbox_config.uid_min)
				fatal_error("the directory containing %s must not be owned by a UID less than %d\n",escape(target),sbox_config.uid_min);
		}else{
			if (file_stats->st_uid < sbox_config.uid_min)
				fatal_error("the file containing %s must not be owned by a UID less than %d\n",escape(target),sbox_config.uid_min);
		}
	}

	if(sbox_config.do_sgid){
		if(sbox_config.sid_mode_directory){
			if (dir_stats->st_gid < sbox_config.gid_min)
				fatal_error("the directory containing %s must not be owned by a GID less than %d\n",escape(target),sbox_config.gid_min);
		}else{
			if (file_stats->st_gid < sbox_config.gid_min)
				fatal_error("the file containing %s must not be owned by a GID less than %d\n",escape(target),sbox_config.gid_min);
		}
	}

	/* 8) owner and group must not be greater than UID_MAX, GID_MAX */
	if(sbox_config.do_suid){
		if(sbox_config.sid_mode_directory){
			if (dir_stats->st_uid > sbox_config.uid_max)
				fatal_error("the directory containing %s must not be owned by a UID greater than %d\n",escape(target),sbox_config.uid_max);
		}else{
			if (file_stats->st_uid > sbox_config.uid_max)
				fatal_error("the file containing %s must not be owned by a UID greater than %d\n",escape(target),sbox_config.uid_max);
		}
	}

	if(sbox_config.do_sgid){
		if(sbox_config.sid_mode_directory){
			if (dir_stats->st_gid > sbox_config.gid_max)
				fatal_error("the directory containing %s must not be owned by a GID greater than %d\n",escape(target),sbox_config.gid_max);
		}else{
			if (file_stats->st_gid > sbox_config.gid_max)
				fatal_error("the file containing %s must not be owned by a GID greater than %d\n",escape(target),sbox_config.gid_max);
		}
	}
#endif

}

char* fetch_newroot(char* docroot) {
	char newd[MAXPATHLEN+1],*newroot;
	int max;

	max = strlen(docroot) + 1 + strlen(sbox_config.root);
	if ( max > MAXPATHLEN)
		fatal_error("document root is too large: \"%s\"",docroot);

	strncpy(newd,docroot,max);
	strncat(newd,"/",1);
	strncat(newd,sbox_config.root,strlen(sbox_config.root)); /* tack on the new root component */
	newd[MAXPATHLEN] = '\0';
	if ((newroot = strdup(to_abs(newd))) == NULL)
		fatal_error("unable to allocate memory while making copy of new root directory path: %s\n",
			strerror(errno));
	return newroot;
}

char* shave(char* newroot,
	    char* target) {

	char* shaved = target;
	char* h = newroot;

	if (!newroot) return target;
	if (!target) return "";

	while (*shaved && *h) {
		if (*shaved++ != *h++)
			break;
	}
	if (*h) return "/";
	return shaved;
}

/* modify the environment in the following ways: 
 * DOCUMENT_ROOT => shave(newroot,root)
 * SCRIPT_NAME => shave(root,target)
 * SCRIPT_FILENAME => shave(newroot,target)
 * PATH_INFO => shave(SCRIPT_NAME,env(path_info))
 * PATH_TRANSLATED => SCRIPT_FILENAME,env(path_info)
 */
static void tweak_environment(char* newroot,
			      char* root,
			      char* target,
			      char* additional_info) {
	char *s,*t,*path_info,*path_translated,*script_name;
	int r,max;

	/* per rfc3875:  The SCRIPT_NAME variable MUST be set to a URI path
	   (not URL-encoded) which could identify the CGI script ...
	   No PATH_INFO segment is included in the SCRIPT_NAME value. */
	script_name = shave(root,target);
	r = set_env("SCRIPT_NAME",script_name,1);
	if (r < 0) 
		fatal_error("no room for SCRIPT_NAME environment variable");

	/* Shave the chroot directory off the target.  Will cause an error
	   if the target is not contained within the new root. */
	s = shave(newroot,target);
	r = set_env("SCRIPT_FILENAME",s,1);
	if (r < 0) 
		fatal_error("no room for SCRIPT_FILENAME environment variable");

	/* PATH_INFO Contains any client-provided pathname information trailing
	   the actual script filename but preceding the query string, if available.
	   It does not include the script name itsself (SCRIPT_NAME). */
	s = (char*) getenv("PATH_INFO");
	path_info = shave(script_name,s);
//	r = set_env("PATH_INFO",(strlen(path_info) ? path_info : "/"),1);
//	if (r < 0)
//		fatal_error("no room for PATH_INFO environment variable");

	/* PATH_TRANSLATED "is derived by taking the PATH_INFO value, parsing it
	   as a local URI in its own right, and performing any virtual-to-physical
	   translation appropriate to map it onto the server's document repository
	   structure."  So says rfc3875.  That would make it roughly
	   DOCUMENT_ROOT/uri_encode(PATH_INFO) .. which seems fairly useless.
	   Additionally, "If PATH_INFO is NULL, then the PATH_TRANSLATED variable
	   MUST be set to NULL (or unset)."
	   */
	if (strlen(path_info)) {
		/* this is DOCUMENT_ROOT */
		s = shave(newroot,root);

		/* PATH_TRANSLATED should already be properly URI-encoded */
		path_translated = (char*) getenv("PATH_TRANSLATED");
		t = shave(target,path_translated);

		//max = strlen(s)+((t[0] != '/')?1:0)+ strlen(t)+1 +strlen(script_name);
		max = strlen( shave(newroot,target) ) + strlen(path_info) + 1;
		if (!(path_translated = (char*) calloc(sizeof(char),max)))
			fatal_error("unable to allocate string for path translated: %s\n",strerror(errno));

		sprintf(path_translated,"%s%s",shave(newroot,target),path_info);

		r = set_env("PATH_TRANSLATED",path_translated,1);
		if (r < 0)
			fatal_error("no room for PATH_TRANSLATED environment variable");

		//script_name = shave(root,target);
		max = strlen( shave(root,target) ) + strlen(path_info) + 1;
		if (!(s = (char*) calloc(sizeof(char),max)))
			fatal_error("unable to allocate string for path_info: %s\n",strerror(errno));
		sprintf(s,"%s%s", shave(root,target),path_info);
		r = set_env("PATH_INFO",s,1);
		free((void*)s);
	}

	s = shave(newroot,root);
	r = set_env("DOCUMENT_ROOT",s,1);
	if (r < 0) 
		fatal_error("no room for DOCUMENT_ROOT environment variable");
}

/* set_env() is a replacement for the BSD setenv() function. */
static int set_env(const char *name, const char *value, int overwrite) {
	char **ep,**var,*d;

	/* initialize cleanenv global if necessary */
	if (cleanenv == NULL) {
		if ((cleanenv = (char **)calloc(AP_ENVBUF, sizeof(char *))) == NULL)
			return -1;
	}

	/* search for the string in the existing environment */
	ep = cleanenv;
	while (((var = ep++) != NULL) && *var) {
		d = (char*) strchr(*var,'=');  /* look for the "=" sign */
		if (!d) continue;             /* malformed entry */
		if ((int)strlen(name) != abs(d-*var)) continue;
		if (0 != strncmp(*var,name,d-*var)) /* compare to target string */
			continue;

		/* if we get here, we found the environment variable */
		if (!overwrite) return 0; /* not allowed to overwrite the variable */

		/* clear out the previous value */
		free((void*) *var);
		*var = NULL;
	}
	/* when we get here var points to the place in the environment string
	   for the new value */
	/* First make sure we haven't run off the end of the buffer.  Must be a terminal
	   NULL in the array */
	if (var - cleanenv >= AP_ENVBUF - 1)
		return -1;

	if ( (*var = (char*)calloc(strlen(name)+1+strlen(value)+1,sizeof(char))) == NULL)
		return -1; /* out of space */
  
	/* copy */
	if (sprintf(*var,"%s=%s",name,value) <= 0)
		return -1; /* don't know when this would happen */

	return 0;
}

/* clean_env() is derived from similar routine in suexec.c, 
   part of the Apache distribution */
void clean_env(){
	char pathbuf[NAME_MAX];
	char *name,*delimiter;
	char **ep;
	int cidx = 0;
	int idx;
  
	/* initialize cleanenv global if necessary */
	if (cleanenv == NULL) {
		if ((cleanenv = (char **)calloc(AP_ENVBUF, sizeof(char *))) == NULL)
			fatal_error("failed to malloc env mem\n");
	}

	/* check cleanenv name and value lengths, and position to first NULL entry */
	for (cidx = 0; cleanenv[cidx] && cidx < AP_ENVBUF; cidx++) {
		name = cleanenv[cidx];
		delimiter = (char*) strchr(name,'=');
		if (delimiter == 0)
			fatal_error("malformed cleanenv entry %d, not in name=value format\n",cidx);
		if (delimiter - name >= MAXENV) {
			name[MAXENV] = '\0';
			fatal_error("env name too long: %s\n",name);
		}
		if (strlen(delimiter) > MAXENV) {
			delimiter[MAXENV] = '\0';
			fatal_error("env value too long: %s = %s\n",name,++delimiter);
		}
	}

	/* copy the environment */
	for (ep = environ; *ep && cidx < AP_ENVBUF; ep++) {
		if (!strncmp(*ep, "HTTP_", 5)) {
			cleanenv[cidx] = *ep;
			cidx++;
		}else{
			for (idx = 0; safe_env_lst[idx]; idx++){
				if (!strncmp(*ep, safe_env_lst[idx], strlen(safe_env_lst[idx]))) {
					cleanenv[cidx] = *ep;
					cidx++;
					break;
				}
			}
		}
	}

	if (strlen(sbox_config.safe_path)+strlen("PATH=")+1 > NAME_MAX)
		fatal_error("value of SAFE_PATH (%s) is too large (max %d bytes)\n",escape(sbox_config.safe_path),NAME_MAX);

	sprintf(pathbuf, "PATH=%s", sbox_config.safe_path);
	cleanenv[cidx] = strdup(pathbuf);
	cleanenv[++cidx] = NULL;
}

char* escape (const char* str) {
	char *escaped,*s,c;
	int count = 0;

	if (str == NULL)
		return NULL;

	if(sbox_config.echo_failures){
		s = (char*) str;
		count = strlen(str);

		while (c = *s++) {
			if (c == '<' || c == '>') {
				count += 4;
			}else if (c == '&'){
				count += 5;
			}
		}

		escaped = (char*) calloc(sizeof(char),count+1);
		s = escaped;
		while (c = *str++) {
			if (c == '<') {
				strcat(s,"&lt;");
				s+=4;
			}else if (c == '>') {
				strcat(s,"&gt;");
				s+=4;
			}else if (c== '&') {
				strcat(s,"&amp;");
				s+=5;
			}else {
				*s++ = c;
			}
		}
		return escaped;
	}else{
		return (char*) str;
	}
}

/* chdir() to the directory where CGI script is located so that
   most e.g. Perl scripts that use relative paths work. the function
   gets the the full path to the chroot() directory (newroot) and full
   path (target) to the CGI script and extracts the correct subdirectory
   where the script resides on and does chdir() there. */
static void chdir_fix(char* newroot, char* target) {
	char *chdir_path;
	int i,j;
	int start=0;
	int end=0;

	chdir_path = (char*) calloc(sizeof(char),MAXPATHLEN);
	if (chdir_path == NULL)
		fatal_error("failed to allocate memory for chdir path: %s\n",strerror(errno));

	for (i=0; target[i]!='\0' && newroot[i]!='\0'; i++) {
		if (target[i] == newroot[i])
			start++;
		else
			continue;
	}

	for (i=0; target[i]!='\0'; i++)
		if (target[i] == '/')
			end=i;

	j = 0;
	if (start>0 && end>0 && start<end) {
		for (i=start; i<end; i++) {
			chdir_path[j] = target[i];
			j++;
		}

	if (chdir(chdir_path) < 0)
		fatal_error("Can't chdir() to %s: %s\n",chdir_path,strerror(errno));
	}
}

//#if SET_LIMITS
void set_limits() {
	struct rlimit limit;

	if(sbox_config.set_limits){
#ifdef RLIMIT_CPU
		limit.rlim_cur = sbox_config.limit_cpu_soft;
		limit.rlim_max = sbox_config.limit_cpu_hard;
		if (setrlimit(RLIMIT_CPU,&limit)<0)
			fatal_error("Couldn't set limit: %s",strerror(errno));
#endif

#ifdef RLIMIT_FSIZE
		limit.rlim_cur = sbox_config.limit_fsize_soft;
		limit.rlim_max = sbox_config.limit_fsize_hard;
		if (setrlimit(RLIMIT_FSIZE,&limit)<0)
			fatal_error("Couldn't set limit: %s",strerror(errno));
#endif

#ifdef RLIMIT_DATA
		limit.rlim_cur = sbox_config.limit_data_soft;
		limit.rlim_max = sbox_config.limit_data_hard;
		if (setrlimit(RLIMIT_DATA,&limit)<0)
			fatal_error("Couldn't set limit: %s",strerror(errno));
#endif

#ifdef RLIMIT_STACK
		limit.rlim_cur = sbox_config.limit_stack_soft;
		limit.rlim_max = sbox_config.limit_stack_hard;
		if (setrlimit(RLIMIT_STACK,&limit)<0)
			fatal_error("Couldn't set limit: %s",strerror(errno));
#endif

#ifdef RLIMIT_CORE
		limit.rlim_cur = sbox_config.limit_core_soft;
		limit.rlim_max = sbox_config.limit_core_hard;
		if (setrlimit(RLIMIT_CORE,&limit)<0)
			fatal_error("Couldn't set limit: %s",strerror(errno));
#endif

#ifdef RLIMIT_NOFILE
		limit.rlim_cur = sbox_config.limit_nofile_soft;
		limit.rlim_max = sbox_config.limit_nofile_hard;
		if (setrlimit(RLIMIT_NOFILE,&limit)<0)
			fatal_error("Couldn't set limit: %s",strerror(errno));
#endif

#ifdef RLIMIT_RSS
		limit.rlim_cur = sbox_config.limit_rss_soft;
		limit.rlim_max = sbox_config.limit_rss_hard;
		if (setrlimit(RLIMIT_RSS,&limit)<0)
			fatal_error("Couldn't set limit: %s",strerror(errno));
#endif

#ifdef RLIMIT_NPROC
		limit.rlim_cur = sbox_config.limit_nproc_soft;
		limit.rlim_max = sbox_config.limit_nproc_hard;
		if (setrlimit(RLIMIT_NPROC,&limit)<0)
			fatal_error("Couldn't set limit: %s",strerror(errno));
#endif
		setpriority(PRIO_PROCESS,0,sbox_config.priority);
	}
}
//#endif
