http://www.perlmonks.org?node_id=340794


in reply to Re: Problems with opendir in CGI
in thread Problems with opendir in CGI

Well, I've narrowed it down to a problem with the whitespace in the directory name. I renamed one of the directories that I'm trying to open with no whitespace and the CGI works fine. The "not found" error only happens on directories with whitespace in the path, which says to me that s/(\s)/\\$1/g isn't cutting it. Any suggestions?

Replies are listed 'Best First'.
Re: Re: Re: Problems with opendir in CGI
by tachyon (Chancellor) on Mar 29, 2004 at 23:58 UTC

    Don't use whitespace in dir names? Seriously. Although in theory you can escape it with \\ each time you interpolate you 'lose' one level of escape. Why not make your life easy?.

    BTW you need some decent error checking on the supplied path. ..\..\WINNT\cmd.exe or ..\..\etc\passwd anyone? There are all manner of variations on this theme. Have a look at the Webserver error logs for the 404 not found with .. %5d and friends. I suggest:

    my $full_path = '/some/path' my $cgi_path = s/\W//g; my $safe_path = "$full_path/$cgi_path";

    ie only allow the final part of the path to be passed so you can remove anything non alphanumeric. If you need more path to be passed pass it as alphanumeric fragments and build the path safely. You ARE NOT SAFE trying to remove ../ as there are 101 ways to express this ie the %5D hacks that even complex regexes will miss. You need to know exactly how the shell deals with escape chars in the path to know what will happen.

    cheers

    tachyon

      Interesting ... when I took out the code that added escape sequences to whitespace, everything started working!

      /me shrugs. Oh well.

      alex g.
Re: Re: Re: Problems with opendir in CGI
by Fletch (Bishop) on Mar 30, 2004 at 02:06 UTC

    So long as you're only passing things directly to perl builtins (i.e. you're not calling something externally using system()) spaces shouldn't need to be escaped and if you try and do so you'll cause yourself problems (as you've found out).