G'day htmanning,
Here's a possible solution.
It's basically just a technique; adapt to your needs.
"I feed it the directory via the URL ..."
That sounds like the the URL could be manipulated to inject malicious code.
The following thwarts such attempts
(in the example runs below I just used `pwd` to demonstrate this; that could, of course, be `rm ...`).
Regardless of whether you use this, or another, solution, you should bear this possibility in mind:
never trust user input as even innocent, accidental typos can cause disasters.
#!/usr/bin/env perl
use strict;
use warnings;
use constant {
BASE_URL => 'https://www.example.com/reg/',
LS => '/usr/bin/ls',
LS_OPTS => [qw{-l -h}],
};
use IPC::System::Simple 'capturex';
die "Usage: $0 dir\n" unless @ARGV;
my $dir = $ARGV[0];
my $base_dir = '/home/ken/tmp/pm_11147164_web_dir_listing/';
my $dir_path = $base_dir . $dir;
die "ERROR: User '$dir' does not exist.\n" unless -e $dir_path && -d _
+;
chdir $base_dir;
my @listing;
for (capturex(LS, @{+LS_OPTS}, $dir_path)) {
next if 0 == index $_, 'total';
/^(.*?\s)(\S+)$/;
push @listing,
qq{<li>$1<a href="} . BASE_URL . qq{$dir/$2">$2</a></li>\n};
}
print "<p>User: <strong>$dir</strong></p>\n";
if (@listing) {
print "<ul>\n";
print for @listing;
print "</ul>\n";
}
else {
print "<p>User '$dir' has no files.</p>\n";
}
Sample runs using the directory structure shown:
$ ls -lR
.:
total 4
drwxr-xr-x 1 ken None 0 Oct 1 05:18 u1
drwxr-xr-x 1 ken None 0 Oct 1 04:00 u2
drwxr-xr-x 1 ken None 0 Oct 1 04:33 u3
-rwxr-xr-x 1 ken None 839 Oct 1 06:07 web_dir_listing.pl
./u1:
total 5
-rw-r--r-- 1 ken None 2002 Oct 1 05:11 u1_a
-rw-r--r-- 1 ken None 501 Oct 1 05:18 u1_b
./u2:
total 4
-rw-r--r-- 1 ken None 4004 Oct 1 05:18 u2_c
-rw-r--r-- 1 ken None 0 Oct 1 04:00 u2_d
./u3:
total 0
$ ./web_dir_listing.pl u1
<p>User: <strong>u1</strong></p>
<ul>
<li>-rw-r--r-- 1 ken None 2.0K Oct 1 05:11 <a href="https://www.examp
+le.com/reg/u1/u1_a">u1_a</a></li>
<li>-rw-r--r-- 1 ken None 501 Oct 1 05:18 <a href="https://www.examp
+le.com/reg/u1/u1_b">u1_b</a></li>
</ul>
$ ./web_dir_listing.pl u2
<p>User: <strong>u2</strong></p>
<ul>
<li>-rw-r--r-- 1 ken None 4.0K Oct 1 05:18 <a href="https://www.examp
+le.com/reg/u2/u2_c">u2_c</a></li>
<li>-rw-r--r-- 1 ken None 0 Oct 1 04:00 <a href="https://www.examp
+le.com/reg/u2/u2_d">u2_d</a></li>
</ul>
$ ./web_dir_listing.pl u3
<p>User: <strong>u3</strong></p>
<p>User 'u3' has no files.</p>
$ ./web_dir_listing.pl u4
ERROR: User 'u4' does not exist.
$ ./web_dir_listing.pl 'u1;pwd'
ERROR: User 'u1;pwd' does not exist.
$ ./web_dir_listing.pl
Usage: ./web_dir_listing.pl dir
See also: IPC::System::Simple
(noting that capturex() does not invoke the shell).
|