Skip to content

Commit

Permalink
Some quick fixes for the built-in statics functions
Browse files Browse the repository at this point in the history
  • Loading branch information
TooTallNate committed Jun 6, 2018
1 parent 9ed9eef commit bb62d7a
Showing 1 changed file with 46 additions and 45 deletions.
91 changes: 46 additions & 45 deletions bashttpd
Original file line number Diff line number Diff line change
Expand Up @@ -217,7 +217,6 @@ flush_response() {
fail_with() {
set_response_code "$1"
echo "$1 ${HTTP_RESPONSE[$1]}"
exit 1
}

# Set the response status code.
Expand All @@ -238,27 +237,31 @@ set_response_header() {
}

serve_file() {
local file=$1

CONTENT_TYPE=
case "$file" in
*\.css)
CONTENT_TYPE="text/css"
;;
*\.js)
CONTENT_TYPE="text/javascript"
;;
*)
read -r CONTENT_TYPE < <(file -b --mime-type "$file")
;;
esac

set_response_header "Content-Type" "$CONTENT_TYPE"

read -r CONTENT_LENGTH < <(stat -c'%s' "$file") && \
local file="$1"
local length="$(stat -c'%s' "$file")"
if [ $? -ne 0 ]; then
fail_with 404
else
CONTENT_TYPE=
case "$file" in
*\.css)
CONTENT_TYPE="text/css"
;;
*\.js)
CONTENT_TYPE="text/javascript"
;;
*)
CONTENT_TYPE="$(file -b --mime-type "$file")"
;;
esac

set_response_header "Content-Type" "$CONTENT_TYPE"

read -r CONTENT_LENGTH < <(stat -c'%s' "$file") && \
set_response_header "Content-Length" "$CONTENT_LENGTH"

cat "$file"
cat "$file"
fi
}

serve_dir_with_tree() {
Expand All @@ -280,36 +283,34 @@ serve_dir_with_ls() {
}

serve_dir() {
local dir=$1
local dir=$1

# If `tree` is installed, use that for pretty output.
which tree &>/dev/null && \
serve_dir_with_tree "$@"
# If `tree` is installed, use that for pretty output.
which tree &>/dev/null && \
serve_dir_with_tree "$@"

serve_dir_with_ls "$@"
serve_dir_with_ls "$@"
}

serve_dir_or_file_from() {
local URL_PATH=$1/$3
shift

# sanitize URL_PATH
URL_PATH=${URL_PATH//[^a-zA-Z0-9_~\-\.\/]/}
[[ $URL_PATH == *..* ]] && fail_with 400

# Serve index file if exists in requested directory
[[ -d $URL_PATH && -f $URL_PATH/index.html && -r $URL_PATH/index.html ]] && \
URL_PATH="$URL_PATH/index.html"

if [[ -f $URL_PATH ]]; then
[[ -r $URL_PATH ]] && \
serve_file "$URL_PATH" "$@" || fail_with 403
elif [[ -d $URL_PATH ]]; then
[[ -x $URL_PATH ]] && \
serve_dir "$URL_PATH" "$@" || fail_with 403
fi

fail_with 404
local URL_PATH=$1/$3
shift

# sanitize URL_PATH
URL_PATH=${URL_PATH//[^a-zA-Z0-9_~\-\.\/]/}
[[ $URL_PATH == *..* ]] && fail_with 400

# Serve index file if exists in requested directory
[[ -d $URL_PATH && -f $URL_PATH/index.html && -r $URL_PATH/index.html ]] && \
URL_PATH="$URL_PATH/index.html"

if [[ -f $URL_PATH ]] && [[ -r $URL_PATH ]]; then
serve_file "$URL_PATH" "$@"
elif [[ -d $URL_PATH ]] && [[ -x $URL_PATH ]]; then
serve_dir "$URL_PATH" "$@"
fi

#fail_with 404
}

serve_static_string() {
Expand Down

0 comments on commit bb62d7a

Please sign in to comment.