Skip to content

Commit

Permalink
Add urldecode and cookie parser
Browse files Browse the repository at this point in the history
  • Loading branch information
dzove855 authored Feb 18, 2022
1 parent f18152e commit 8cbc6d6
Showing 1 changed file with 24 additions and 0 deletions.
24 changes: 24 additions & 0 deletions bash-server.sh
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
#!/usr/local/bin/bash

# https://github.com/dylanaraps/pure-bash-bible#decode-a-percent-encoded-string
urldecode() {
: "${1//+/ }"
printf '%b\n' "${_//%/\\x}"
}

parseHttpRequest(){
# Get information about the request
read -r REQUEST_METHOD REQUEST_PATH HTTP_VERSION
Expand All @@ -20,6 +26,9 @@ parseGetData(){
# Split QUERY_STRING into an assoc, so it can be easy reused
IFS='?' read -r REQUEST_PATH get <<<"$REQUEST_PATH"

# Url decode get data
get="$(urldecode "$get")"

# Split html #
IFS='#' read -r REQUEST_PATH _ <<<"$REQUEST_PATH"
QUERY_STRING="$get"
Expand All @@ -43,6 +52,17 @@ parsePostData(){
fi
}

parseCookieData(){
local -a cookie
local entry key value
IFS=';' read -ra cookie <<<"${HTTP_HEADERS["Cookie"]}"

for entry in "${cookie[@]}"; do
IFS='=' read -r key value <<<"$entry"
COOKIE["${key# }"]="${value% }"
done
}

httpSendStatus(){
local -A status_code=(
[200]="200 OK"
Expand Down Expand Up @@ -107,6 +127,7 @@ parseAndPrint(){
local -A POST
local -A GET
local -A HTTP_RESPONSE_HEADERS
local -A COOKIE

# Now mktemp will write create files inside the temporary directory
local -r TMPDIR="$serverTmpDir"
Expand All @@ -120,6 +141,9 @@ parseAndPrint(){
# Parse Get Data
parseGetData

# Parse cookie data
parseCookieData

# Parse post data only if length is > 0 and post is specified
# bash (( will not fail if var is not a number, it will just return 1, no need of int check
if [[ "$REQUEST_METHOD" == "POST" ]] && (( ${HTTP_HEADERS['Content-Length']} > 0 )); then
Expand Down

0 comments on commit 8cbc6d6

Please sign in to comment.