Question

I am trying to write a webserver in bash using socat. I am having trouble serving image requests. I'm opening the socat listening connection like so:

socat -T 30 -d -d TCP-L:$LISTENIP,reuseaddr,fork,crlf SYSTEM:"$0 \"docroot=$DOCROOT\""

I'm serving the image with the following, where $1 is the docroot and $2 is the image file name.

function serve_png {
  if [ -e $1$2 ]
  then
    SIZE=`stat -c '%s' $1$2`
    echo -ne "HTTP/1.1 200 OK\nContent-type: image/png\nContent-length: $SIZE\n\n"
    cat $1$2
  else
    echo -ne "HTTP/1.1 404 Not Found\nContent-type: text/html\n\n404 - Not found\n"
  fi
}

The image fails to display in firefox due to it "containing errors." I'm getting the following output at console.

2014/01/25 08:00:41 socat[11551] N listening on AF=2 0.0.0.0:8080
2014/01/25 08:00:45 socat[11551] N accepting connection from AF=2 $MYIP:55765 on AF=2 $SERVERIP:8080
2014/01/25 08:00:45 socat[11552] N forking off child, using socket for reading and writing
2014/01/25 08:00:45 socat[11551] N forked off child process 11552
2014/01/25 08:00:45 socat[11551] N listening on AF=2 0.0.0.0:8080
2014/01/25 08:00:45 socat[11552] N forked off child process 11553
2014/01/25 08:00:45 socat[11552] N forked off child process 11553
2014/01/25 08:00:45 socat[11552] N starting data transfer loop with FDs [4,4] and [3,3]
2014/01/25 08:00:45 socat[11552] W read(3, 0x8e2e388, 8192): Connection reset by peer
2014/01/25 08:00:45 socat[11552] N socket 2 to socket 1 is in error
2014/01/25 08:00:45 socat[11552] N socket 2 (fd 3) is at EOF
2014/01/25 08:00:45 socat[11552] N socket 1 (fd 4) is at EOF
2014/01/25 08:00:45 socat[11552] N socket 2 (fd 3) is at EOF
2014/01/25 08:00:45 socat[11552] N exiting with status 0

I have seen similar scripts using netcat, but I'm unable to get it working using socat. I'd like to keep using socat as it has the ability to fork and handle multiple connections. Any insights would be appreciated.

Was it helpful?

Solution

Steffen Ullrich had it with omitting the crlf flag from the socat command. It was causing Cariage Returns/Line Feeds to be inserted into the stream automatically by socat (hence the file corruption). After omitting that option, everything worked as expected.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top