flappix flappix - 5 months ago 47
HTTP Question

Serve an HTTP response including an image, with netcat

I'm trying to write a little HTTP server using netcat. For plain text files this works fine but when I try to send a picture, the browser displays only the icon for broken images.
What I do is extracting the mime-type and size of a requested file and cat it to the client.
The header of a request of my example picture looks like this:

HTTP/1.0 200 OK
Content-Length: 197677
Content-Type: image/jpeg

This is my bash script which I launch with -e option of the netcat tool:



# -- CODE

# read request
read -s input
resource=$(echo $input | grep -P -o '(?<=GET \/).*(?=\ )') # extract requested file
[ ! -n "$resource" ] && resource=$index_page # if no file requested, set to default
[ ! -f "$resource" ] && resource=$error_page # if requested file not exists, show error pag

# generate output
http_content_type=$(file -b --mime-type $resource) # extract mime type
case "$(echo $http_content_type | cut -d '/' -f2)" in
output=$(cat $resource)

# fix mime type for plain text documents
echo $resource | grep -q '.css$' && http_content_type=${http_content_type//plain/css}
echo $resource | grep -q '.js$' && http_content_type=${http_content_type//plain/javascript}

output=$(php $resource)
http_content_type=${http_content_type//x-php/html} # fix mime type

output=$(cat $resource)

output=$(cat $resource)

echo 'Unknown type'

http_content_length="$(echo $output | wc -c | cut -d ' ' -f1)"

# sending reply
echo "HTTP/1.0 200 OK"
echo "Content-Length: $http_content_length"
echo -e "Content-Type: $http_content_type\n"
echo $output

Would be very happy if someone is able to help me :-)


I'd expect that special characters in the binary data are active in your shell script.

I'd recommend that you get the file size with:

http_content_length=`stat -c '%s' $resource`

And you "send" it with:

echo -e "Content-Type: $http_content_type\n"
cat $resource