Serve HTTP response, including image, with netcat

I am trying to write a small HTTP server using netcat. For text files, this works great, but when I try to send an image, only the icon for the broken images is displayed in the browser. What I am doing is extracting the type and size of the mime of the requested file and the cat to its client. The request header of my example is as follows:

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

This is my bash script that I run with the -e parameter of the netcat tool:

 #!/bin/bash # -- OPTIONS index_page=index.htm error_page=notfound.htm # -- 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 html|plain) 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} ;; x-php) output=$(php $resource) http_content_type=${http_content_type//x-php/html} # fix mime type ;; jpeg) output=$(cat $resource) ;; png) output=$(cat $resource) ;; *) echo 'Unknown type' esac 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 

I would be very happy if someone can help me :-)

+4
source share
1 answer

I expect special characters in binary data to be active in your shell script.

I would recommend 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 
0
source

All Articles