If you create a very simple webserver in Bash:
#!/usr/bin/env bash
HTML="<!DOCTYPE html><HTML><BODY>Test</BODY></HTML>"
LENGTH="${#HTML}"
RESPONSE="HTTP/1.1 200 OK\nContent-Length: ${LENGTH}\nConnection: close\n\n$HTML\n\n"
while true; do
echo -en "$RESPONSE" | nc -lp 80
done
Then it doesn't work reliable with Chrome. A lot of the times the page will have a timeout with ERR_CONNECTION_RESET
, other times it works fine.
I tried to debug this issue, and it seems what happens is that Chrome fires two requests simultanously (because it also wants to fetch the favicon.ico
file) and because netcat restarts after each request, it will be too late for the the second request. This problem is documented also here: https://carltonhenderson.github.io/nc-makes-a-bad-web-server/ Even the -k
option does not seem to help.
Is there any way to fix this? Because the article suggest using nginx instead, but I would like to keep using netcat.
I would separate the serving part from the response and start a client program with --exec
and also keep the connection open with --keep-open
:
serv.sh
#!/usr/bin/env bash
nc -lp 80 --exec ./resp.sh --keep-open
Then move out your response to resp.sh
:
resp.sh
#!/usr/bin/env bash
HTML="<!DOCTYPE html><HTML><BODY>Test</BODY></HTML>"
LENGTH="${#HTML}"
RESPONSE="HTTP/1.1 200 OK\nContent-Length: ${LENGTH}\nConnection: close\n\n$HTML\n\n"
echo -en "$RESPONSE"
Note: You can modify the maximum connections with the --max-conns
option.
Note: I'm using "Ncat: Version 7.93 ( https://nmap.org/ncat )"