21.03.2013 Views

Problem - Kevin Tafuro

Problem - Kevin Tafuro

Problem - Kevin Tafuro

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Especially if you use the code from Recipe 1.1 to sanitize the environment, or if you<br />

use the code from the previous subsection, you should use spc_delenv( ) to delete an<br />

environment variable. The following code for spc_delenv( ) depends on the static<br />

variable spc_environ declared at global scope in the spc_putenv( ) code from the previous<br />

subsection; the two functions should share the same instance of that variable.<br />

Note that the following code is not thread-safe. You need to explicitly avoid the possibility<br />

of manipulating the environment from two separate threads at the same time.<br />

#include <br />

#include <br />

int spc_delenv(const char *name) {<br />

int del = 0, envc, i, idx = -1;<br />

size_t delsz = 0, envsz = 0, namelen;<br />

char *envptr, **new_environ;<br />

extern int spc_environ;<br />

extern char **environ;<br />

/* first compute the size of the new environment */<br />

namelen = strlen(name);<br />

for (envc = 0; environ[envc]; envc++) {<br />

if (!strncmp(environ[envc], name, namelen) && environ[envc][namelen] = = '=') {<br />

if (idx = = -1) idx = envc;<br />

else {<br />

del++;<br />

delsz += strlen(environ[envc]) + 1;<br />

}<br />

}<br />

envsz += strlen(environ[envc]) + 1;<br />

}<br />

if (idx = = -1) return 1;<br />

envc -= del; /* account for duplicate entries of the same name */<br />

envsz -= delsz;<br />

/* allocate memory for the new environment */<br />

envsz += (sizeof(char *) * (envc + 1));<br />

if (!(new_environ = (char **)malloc(envsz))) return 0;<br />

envptr = (char *)new_environ + (sizeof(char *) * (envc + 1));<br />

/* copy the old environment into the new environment, ignoring any<br />

* occurrences of the environment variable that we want to delete.<br />

*/<br />

for (envc = i = 0; environ[envc]; envc++) {<br />

if (envc = = idx || (del && !strncmp(environ[envc], name, namelen) &&<br />

environ[envc][namelen] = = '=')) continue;<br />

new_environ[i++] = envptr;<br />

envsz = strlen(environ[envc]);<br />

memcpy(envptr, environ[envc], envsz + 1);<br />

envptr += (envsz + 1);<br />

}<br />

/* possibly free the old environment, then replace it with the new one */<br />

96 | Chapter 3: Input Validation<br />

This is the Title of the Book, eMatter Edition<br />

Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!