Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Added an example clearenv() function

...

The clearenv() function (which is not defined by either C99 or POSIX) may be used to clear out the environment where available, otherwise it can be cleared by obtaining a list of the environment variable names from environ and removing each one using unsetenv().

...

In this compliant solution, the environment is cleared by clearenv() and then the PATH and IFS variables are set to safe values before invoking system(). Sanitizing a shell command can be difficult and doing so can adversely affect the power and flexibility associated with them.

Code Block
bgColor#ccccff
char *pathbuf;
size_t n;

if (clearenv() != 0) {
  /* Handle Error */
}


n = confstr(_CS_PATH, NULL, 0);
if (n == 0) {
  /* Handle Error */
}

if ((pathbuf = malloc(n)) == NULL) {
  /* Handle Error */
}

if (confstr(_CS_PATH, pathbuf, n) == 0) {
  /* Handle Error */
}

if (setenv("PATH", pathbuf, 1) == -1) {
  /* Handle Error */
}
if (setenv("IFS", " \t\n", 1) == -1) {
  /* Handle Error */
}

if (system("/bin/ls dir.`date +%Y%m%d`") == -1) {
  /* Handle Error */
}

...

On systems which have no clearenv() function, the following implementation can be used.

Code Block
bgColor#ccccff

extern char **environ;

int clearenv(void)
{
  static char *namebuf = NULL;
  static size_t lastlen = 0;

  while (environ != NULL && environ[0] != NULL) {
    size_t len = strcspn(environ[0], "=");
    if (len == 0) {
      /* Handle empty variable name (corrupted environ[]) */
    }
    if (len > lastlen) {
      namebuf = realloc(namebuf, len+1);
      if (namebuf == NULL) {
        /* Handle Error */
      }
      lastlen = len;
    }
    memcpy(namebuf, environ[0], len);
    namebuf[len] = '\0';
    if (unsetenv(namebuf) == -1) {
      /* Handle Error */
    }
  }
  return 0;
}

Compliant Solution (Windows)

...