#include "sbox.h"

#include <stdio.h>
#include <stdlib.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

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

   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,*tzname[2];
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);
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);
int set_env(const char *name, 
	    const char *value, 
	    int overwrite);
#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
};

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

int main (int argc, char* argv[]) {
  struct stat target_stat,dir_stat;
  char *target,*newroot,*root,*additional_info,*cmd;
  int gid,uid;

  /* necessary in order to avoid clobbering time zone */
#if 0
  /* was causing more problems than it was worth */
  tzset(); 
  set_env("TZ",tzname[0],0);
#endif

  open_log();
  
  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);

  /* 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 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",newroot,strerror(errno));
  #endif

  cmd = shave(newroot,target); 
#else
  cmd = target;
#endif

clean_env();

  /* set to the owner's uid and gid */
#if DO_SGID || DO_SUID
  gid = SID_MODE == DIRECTORY ? dir_stat.st_gid : target_stat.st_gid;
  uid = SID_MODE == DIRECTORY ? dir_stat.st_uid : target_stat.st_uid;
#if DO_SGID && !defined(DEBUG)
  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 DO_SUID && !defined(DEBUG)
  if (setuid(uid) < 0) {
    fatal_error("couldn't setuid() to %d (%s)\n",dir_stat.st_uid,strerror(errno));
  }
#endif
#endif

  /* give up our root privileges now */
  if (setuid(getuid()) < 0) {
    fatal_error("couldn't setuid() to %d (%s)\n",getuid(),strerror(errno));
  }
  
  /* set hard and soft limits on resource usage */
#if SET_LIMITS
  set_limits();
#endif

#ifdef LOG_FILE
  log_error("executing %s for uid %d, gid %d\n",target,getuid(),getgid());
#endif

  if (log != stderr)
    fclose(log);

  /* execute the target */
  argv[0]=cmd;
  /*  execl(cmd,cmd,(char*)0x0); */
  execve(cmd,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, so log to stderr */
  log = stderr;
  fatal_error("exec of %s failed (%s)\n",cmd,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", uid);
  
  /* 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(WEB_USER,pass->pw_name))
    fatal_error("invoked by %s, but must be run by %s\n",pass->pw_name,WEB_USER);

  if (strcmp(WEB_GROUP,grp->gr_name))
    fatal_error("invoked by group %s, but must be run by group %s\n",grp->gr_name,WEB_GROUP);

#endif
}

void open_log () {
#ifdef LOG_FILE
  if (strlen(LOG_FILE) > 0) {
   if ((log = fopen(LOG_FILE, "a")) == NULL) {
      fprintf(stderr, "sbox failed to open log file\n");
      perror("sbox fopen()");
      exit(1);
    }
  } else {
    log = stderr;
  }
#else
  log = NULL;
#endif
}

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: ",timestr);
  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;

  webmaster = (char*)getenv("SERVER_ADMIN");
  
  va_start(ap, fmt);
  write_log(fmt,ap);
  va_end(ap);

#if ECHO_FAILURES
  fprintf(stdout,
"Content-type: text/html\n\n
<HTML><HEAD>
<TITLE>Sbox Error</TITLE>
</HEAD>
<BODY>
<H1>Sbox Execution Error</H1>
The <A HREF=\"http://stein.cshl.org/~lstein/sbox/\">sbox</A> program
encountered an error while processing this request: <BLOCKQUOTE><STRONG>");

  vprintf(fmt, ap);

  fprintf(stdout,"</STRONG></BLOCKQUOTE>
Please note \
the time of the error, anything you might have been doing at the time \
to trigger the problem, and forward the information to this site's \
Webmaster");
  fprintf(stdout,
	  (webmaster ? " (<a href=\"mailto:%s\">%s</a>).": "."),
	  webmaster,webmaster);
fprintf(stdout,"<P><I>sbox version %3.2f</I><BR><I>%s</I></P><HR></BODY></HTML>",VERSION,"$Id: sbox.c,v 1.4 1998/10/19 20:50:31 lstein Exp $");
#else
  printf(stdout,"Content-type: text/html\n\n%s",CANNED_ERROR);
#endif
  fflush(stdout);
  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! */
char* to_abs(char* directory) {
  if (chdir(directory) < 0)
    fatal_error("error during chdir() to %s: %s\n",directory,strerror(errno));
  if (!getcwd(directory,MAXPATHLEN))
    fatal_error("error during getcwd(): %s\n",strerror(errno));
  return directory;
}

/* 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;
    
  /* 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 \"%s/script/to/run\"\n",
		(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",
		(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;
}

/* 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;

  /* 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");

  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 0
  if (path_info[1] == '~')
    shaved = shave(root,path_translated);
  else
    shaved = path_info;
#else
  /* Actually, that's dead code that doesn't work properly with Alias.  We always want to shave
     the document root off the translated path! */
    shaved = shave(root,path_translated);
#endif

  if (strlen(root)+1+strlen(CGI_BIN) > MAXPATHLEN)
    fatal_error("Unable to allocate memory to hold script directory\n");
  strcpy(directory,root);
  strcat(directory,"/");
  strcat(directory,CGI_BIN);

  /* resolve symbolic links and relative paths */
  to_abs(directory);
  
  if (!(raw = (char*)calloc(sizeof(char),strlen(directory) + strlen(shaved) + 1)))
    fatal_error("Unable to allocate memory for path to CGI script: %s\n",strerror(errno));
  strcpy(raw,directory);
  strcat(raw,shaved);

  /* step down the path until we find the directory and the executable */
  p = raw+1;
  while ((p = index(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",raw);

    if (stat(target,starg) < 0)
      fatal_error("Stat failed. %s: %s\n",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)))
	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",raw,strerror(errno));

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

    p = raw + strlen(raw);
    strncpy(target,raw,MAXPATHLEN);
  }

  /* 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);

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

  strcpy(path,directory);
  strncat(path,dir,p-dir);
  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) {
#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",target);

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

  /* 2) script must be executable by other */
  if (!( (file_stats->st_mode & S_IXOTH)))
    fatal_error("%s not world executable\n",target);

  /* 3) script is not owned by WEB_USER or WEB_GROUP */
  if (!(strcmp(getpwuid(file_stats->st_uid)->pw_name,WEB_USER)))
    fatal_error("%s is owned by the Web user (%s)\n",target,WEB_USER);

  if (!(strcmp(getgrgid(file_stats->st_gid)->gr_name,WEB_GROUP)))
    fatal_error("%s is owned by the Web group (%s)\n",target,WEB_GROUP);
  
  /* 4) directory is not owned by WEB_USER or WEB_GROUP */
  if (!(strcmp(getpwuid(dir_stats->st_uid)->pw_name,WEB_USER)))
    fatal_error("the directory containing %s is owned by the Web user (%s)\n",target,WEB_USER);

  if (!(strcmp(getgrgid(dir_stats->st_gid)->gr_name,WEB_GROUP)))
    fatal_error("the directory containing %s is owned by the Web group (%s)\n",target,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",target);

  if (dir_stats->st_mode & S_IWOTH)
    fatal_error("the directory containing %s is world writable\n",target);
  
#if 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",target,newroot);
#endif

  /* 7) owner and group must not be less than UID_MIN, GID_MIN */
#if DO_SUID
#if SID_MODE == DIRECTORY
  if (dir_stats->st_uid < UID_MIN)
    fatal_error("the directory containing %s must not be owned by a UID less than %d\n",target,UID_MIN);
#else
  if (file_stats->st_uid < UID_MIN)
    fatal_error("the file containing %s must not be owned by a UID less than %d\n",target,UID_MIN);
#endif
#endif

#if DO_SGID
#if SID_MODE == DIRECTORY
  if (dir_stats->st_gid < GID_MIN)
    fatal_error("the directory containing %s must not be owned by a GID less than %d\n",target,GID_MIN);
#else
  if (file_stats->st_gid < GID_MIN)
    fatal_error("the file containing %s must not be owned by a GID less than %d\n",target,GID_MIN);
#endif
#endif

#endif

}

struct stat* stat_dir(const char* target) {
  char target_dir[MAXPATHLEN+1],*d;
  struct stat* stats;

  if ((d = rindex(target,'/'))) {
    strncpy(target_dir,target,d-target);
    target_dir[d-target]='\0';
  } else {
    strcpy(target_dir,".");
  }

  stats = (struct stat*) calloc(1,sizeof(struct stat));
  if (stats == NULL)
    fatal_error("stat_target() failed to allocate room for stat structure: %s\n",strerror(errno));

  if (stat(target_dir,stats) < 0)
    fatal_error("stat() failed: %s\n",strerror(errno));

  return stats;
}

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

  if ( (strlen(docroot) + 1 + strlen(ROOT)) > MAXPATHLEN)
    fatal_error("document root is too large: \"%s\"",docroot);
  
  strcpy(newd,docroot);
  strcat(newd,"/");
  strcat(newd,ROOT); /* tack on the new root component */
  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(DOCUMENT_ROOT)
 * PATH_INFO => path_info
 * PATH_TRANSLATED => "DOCUMENT_ROOT/path_info"
 * SCRIPT_FILENAME => shave(target)
 * SCRIPT_NAME => "$SCRIPT_NAME/shave(target)"
 */
static void tweak_environment(char* newroot,
			      char* root,
			      char* target,
			      char* additional_info) {
  char *s,*t,*path_info,*script_name;
  int r;

  /* the SCRIPT_NAME needs to be the URL that we invoke to get at the
   script again.  */
  path_info = (char*) getenv("PATH_INFO");
  script_name = (char*) getenv("SCRIPT_NAME");
  if (script_name == NULL)
    fatal_error("expect SCRIPT_NAME environment variable to be set, but null found\n");

  /* set the script name -- it should be existing SCRIPT_NAME concatenated
     to the path info, less the additional info.  SCRIPT_NAME can be used to
     reinvoke the script in virtual name space*/
    s = (char*) calloc(sizeof(char),strlen(script_name) + 
		       strlen(path_info) - 
		       strlen(additional_info) +
		       1);
    if (s == NULL)
      fatal_error("failed to allocate memory for SCRIPT_NAME: %s\n",strerror(errno));

    strcpy(s,script_name);
    strncat(s,path_info,strlen(path_info)-strlen(additional_info));
    r = set_env("SCRIPT_NAME",s,1);
    free((void*)s);

    if (*additional_info) {
      /* set the path info */
      r = set_env("PATH_INFO",strdup(additional_info),1);

      t = shave(newroot,root);

      if (!(s = (char*) calloc(sizeof(char),strlen(t)+strlen(additional_info)+1)))
	fatal_error("unable to allocate string for path translated: %s\n",strerror(errno));

      /* set the path translated */
      strcpy(s,t);
      if (t[strlen(t)-1] == '/')
	strcat(s,additional_info+1);
      else
	strcat(s,additional_info);
      r = set_env("PATH_TRANSLATED",s,1);
      free((void*)s);
    }

  /* Shave the chroot directory off the target.  Will error out
     if the target is not contained within the new root. */
  s = shave(newroot,target);
  r = set_env("SCRIPT_FILENAME",s,1);

  s = shave(newroot,root);
  r = set_env("DOCUMENT_ROOT",s,1);
}

/* set_env() is a replacement for the BSD setenv() function. */
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++) && *var) {
    d = (char*) index(*var,'=');  /* look for the "=" sign */
    if (!d) continue;             /* malformed entry */
    if (strlen(name) != 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 **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");
  }

  /* position to first NULL entry in cleanenv */
  for (cidx = 0; cleanenv[cidx] && cidx < AP_ENVBUF; cidx++)
    ;

  /* 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(SAFE_PATH)+strlen("PATH=")+1 > NAME_MAX)
    fatal_error("value of SAFE_PATH (%s) is too large (max %d bytes)\n",SAFE_PATH,NAME_MAX);

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

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

#ifdef RLIMIT_CPU
  SETLIMIT(CPU);
#endif
#ifdef RLIMIT_FSIZE
  SETLIMIT(FSIZE);
#endif
#ifdef RLIMIT_DATA
  SETLIMIT(DATA);
#endif
#ifdef RLIMIT_STACK
  SETLIMIT(STACK);
#endif
#ifdef RLIMIT_CORE
  SETLIMIT(CORE);
#endif
#ifdef RLIMIT_NOFILE
  SETLIMIT(NOFILE);
#endif
#ifdef RLIMIT_RSS
  SETLIMIT(RSS);
#endif
#ifdef RLIMIT_NPROC
  SETLIMIT(NPROC);
#endif
  setpriority(PRIO_PROCESS,0,PRIORITY);
}
#endif
