Send image over http via socat bash webserver

℡╲_俬逩灬. 提交于 2021-02-08 08:59:48

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/21351097/send-image-over-http-via-socat-bash-webserver

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!