Created
March 12, 2023 21:46
-
-
Save guites/904b7ead024fbd4a2a48a769434a44f8 to your computer and use it in GitHub Desktop.
Simple HTTP web server using netcat and command line utilities. Accepts GET and POST requests.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# $1 vai ser o corpo da resposta a ser enviada | |
http_response() { | |
content_length=$(echo -n "$1" | wc -c) # calcula o número de bytes no corpo da resposta | |
printf $'HTTP/1.1 200 ok\r\n' | |
printf $'Content-Length: %s\r\n' "$content_length" | |
printf $'Content-Type: text/plain\r\n' | |
printf $'Connection: close\r\n' | |
printf $'\r\n' | |
if [ -n "$1" ]; then | |
# caso o corpo da resposta não seja vazio, vamos enviá-lo | |
printf $'%s' "$1" | |
fi | |
} | |
# $1 é uma url que precisamos verificar | |
validate_url() { | |
wget --spider --timeout 1 "$1" 2>/dev/null | |
} | |
# o argumento $1 vai conter a linha com o corpo da requisição | |
# no formato `parametro1=valor1¶metro2=valor2&...` | |
parse_request_body() { | |
readarray -t -d \& request_values <<< "$1" | |
values="${request_values[0]}" | |
param=$(echo "$values" | cut -d"=" -f1) | |
value=$(echo "$values" | cut -d"=" -f2) | |
if [ "$param" != "url" ]; then | |
echo "false" && return | |
fi | |
if ! validate_url "$value"; then | |
echo "false" && return | |
fi | |
echo "$value" | |
} | |
generate_response() { | |
local verb | |
verb="" | |
while true; do | |
if read -t 0.3 -r line; then | |
line="$(sed 's/\r//g' <<< "${line}")" | |
if [ -n "${line}" ]; then | |
if [ -z "${verb}" ]; then | |
read -r verb _ _ <<< "${line}" | |
continue | |
fi | |
else | |
if [ "$verb" == 'GET' ]; then | |
http_response "" | |
verb="" | |
continue | |
fi | |
fi | |
else | |
# o processamento da linha passou | |
# do tempo limite, vamos lidar com o | |
# que recebemos! | |
if [ "$verb" == "POST" ]; then | |
response_body=$(parse_request_body "$line") | |
http_response "$response_body" | |
verb="" | |
continue | |
fi | |
fi | |
done < "$1" | |
} | |
if [ -a "test-pipe" ]; then | |
rm "test-pipe" | |
fi | |
mkfifo "test-pipe" | |
nc -kl 18000 \ | |
0< <(generate_response "test-pipe") \ | |
1> >(while : ; do cat - > "test-pipe"; done) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment