hello.

I'm using the method below - a bit simplified here but functionally the same - to create the path to a file I'm about to save, if it isn't there already. It works well enough, but I'm concerned that it should be as safe as possible and I'm sure there will be dangers I haven't considered. All suggestions and criticisms most gratefully received, especially if they take the form 'use File::Something, as any fule kno'.

Package My::Page; use File::Basename; #... sub _create_path { my $self = shift; my (undef, $directories, undef) = fileparse( $self->url, '\.\w+' ) +; my $path = $self->config->get('base_path'); chdir $path; for (split('/', $directories)) { next unless $_; $path .= "/$_"; if (-e && ! -d) { $self->log_error("$path already exists and is not a direct +ory."); return; } if (-l) { $self->log_error("$path already exists and is a symlink.") +; return; } unless (-e && -d || mkdir $path) { $self->log_error("failed to mkdir $path: $!"); return; } unless (chdir $path) { $self->log_error("failed to chdir to $path: $!"); return; } } return 1; }

nb. the path to the file has been untainted (but only on input), and it all runs under an suexec'd apache, so the normal umask for mkdir is fine. It's generally called as $page->_create_path || grumble(), hence the return values. And I'm a bit torn between using relative and absolute paths, as you can see. One is better for error messages, the other for tests. Oh well.

thanks. hope this isn't another question that was answered two days ago.


In reply to rfc: safely creating path/to/file by thpfft

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.