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.

if (spc_environ) free(environ);<br />

environ = new_environ;<br />

spc_environ = 1;<br />

return 1;<br />

}<br />

See Also<br />

Recipe 1.1<br />

3.7 Validating Filenames and Paths<br />

<strong>Problem</strong><br />

You need to resolve the path of a file provided by a user to determine the actual file<br />

that it refers to on the filesystem.<br />

Solution<br />

On Unix systems, use the function realpath( ) to resolve the canonical name of a file<br />

or path. On Windows, use the function GetFullPathName( ) to resolve the canonical<br />

name of a file or path.<br />

Discussion<br />

You must be careful when making access decisions for a file. Taking relative pathnames<br />

and links into account, it is possible for multiple filenames to refer to the<br />

same file. Failure to take this into account when attempting to perform access checks<br />

based on filename can have severe consequences.<br />

On the surface, resolving the canonical name of a file or path may appear to be a reasonably<br />

simple task to undertake. However, many programmers fail to consider symbolic<br />

and hard links. On Windows, links are possible, but they are not as serious an<br />

issue as they are on Unix because they are much less frequently used.<br />

Fortunately, most modern Unix systems provide, as part of the standard C runtime,<br />

a function called realpath( ) that will properly resolve the canonical name of a file or<br />

path, taking relative paths and links into account. Be careful when using realpath( )<br />

because the function is not thread-safe, and the resolved path is stored in a fixed-size<br />

buffer that must be at least MAXPATHLEN bytes in size.<br />

The function realpath( ) is not thread-safe because it changes the current<br />

directory as it resolves the path. On Unix, a process has a single<br />

current directory, regardless of how many threads it has, so changing<br />

the current directory in one thread will affect all other threads within<br />

the process.<br />

Validating Filenames and Paths | 97<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!