Skip to content

Instantly share code, notes, and snippets.

@neevek
Last active August 29, 2020 15:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save neevek/b3f2fc7737aff40d8296335b914ee283 to your computer and use it in GitHub Desktop.
Save neevek/b3f2fc7737aff40d8296335b914ee283 to your computer and use it in GitHub Desktop.
A file server with nc
#!/bin/bash
port=$1
if [[ $# -ne 1 ]]; then
echo "usage: $0 <port>"
exit 1
fi
echo "will listen on $port, serve current directory"
mkfifo pipe 2> /dev/null
while true; do
#nc -l $port < pipe | tee /dev/tty | head -1 | \
nc -l 0.0.0.0 $port < pipe | tee /dev/tty | head -1 | \
perl -ne '
use URI::Split qw(uri_split);
use Cwd qw();
my $dstfile = "";
if ($_ =~ /GET (.*) HTTP\/1.[01]/) {
$dstfile = $1;
} else {
print "HTTP/1.1 400 Bad Request\r\n\r\nBad Request, only GET method is supported.";
exit;
}
if ($dstfile =~ /^https?:\/\//) {
my ($scheme, $auth, $path, $query, $frag) = uri_split($dstfile);
$dstfile = $path;
}
$dstfile = Cwd::cwd() . $dstfile;
if(-f "$dstfile") {
my $mimeType = `file -b -I "$dstfile"`;
chomp($mimeType);
open f, "$dstfile" or die "failed to open file: $dstfile";
print("HTTP/1.1 200 OK\r\n",
"Content-Type: $mimeType\r\n",
"Content-Length: ", -s "$dstfile", "\r\n\r\n",
<f>);
} else {
my $content = "FILE NOT FOUND: $dstfile\n";
print("HTTP/1.1 404 Not Found\r\n",
"Content-Type: text/plain\r\n",
"Content-Length: ", length($content), "\r\n\r\n",
$content);
}
' > pipe;
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment