Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #! /bin/bash
- #
- # Simple http server with CGI support (launched within inetd/xinetd)
- # Command line: httpd.sh [-c] [-d <path>]
- # -c - show content of current directory if index.html is not found
- # -d <path> - set base directory (default - /home/http)
- # -v - be verbose
- #
- # simple logger
- function msg
- {
- [[ $VERBOSE -eq 1 ]] && logger -t httpd.sh -p daemon.info "$1"
- }
- # cleanup on exit
- trap "rm -rf /tmp/httpd" EXIT
- # parse command line
- SHOW_DIR=0
- base=/home/http
- OPTIND=1
- while getopts cd:v opt ; do
- case "$opt" in
- c) SHOW_DIR=1 ;;
- d) base="$OPTARG" ;;
- v) VERBOSE=1 ;;
- esac
- done
- # get request
- read request
- # get header
- mkdir -p /tmp/httpd
- while true; do
- read header
- echo $header >> /tmp/httpd/header-$$
- [[ "$header" == $'\r' ]] && break;
- done
- # parse request
- url="${request#GET }"
- url="${url% HTTP/*}"
- query="${url#*\?}"
- url="${url%%\?*}"
- encoding="utf-8"
- # set default start page
- [[ $url != "/" ]] && fn="$base$url" || fn="$base/index.html"
- if [[ "$url" =~ "cgi-bin" ]]; then
- is_cgi="yes"
- [[ "$query" == "$url" ]] && query=
- fi
- # decode filename
- filename=$(printf '%b' ${fn//%/\\x})
- dirname=${filename%index.html}
- if [[ $is_cgi == "yes" && -x "$filename" ]]; then
- # run CGI script
- msg "Execute CGI request: $filename"
- export QUERY_STRING="$query"
- echo -e "HTTP/1.1 200 OK\r"
- eval ${filename@Q} $(echo ${query@Q} | sed 's/+/ /g')
- echo -e "\r"
- elif [[ -f "$filename" ]]; then
- # show requested file
- msg "Show file: $filename"
- mime=$(file -bi "$filename")
- size=$(wc -c "$filename" | cut -f1 -d' ')
- echo -e "HTTP/1.1 200 OK\r"
- echo -e "Content-Type: $mime\r"
- echo -e "Content-Length: $size\r"
- echo -e "\r"
- cat "$filename"
- echo -e "\r"
- elif [[ $SHOW_DIR -eq 1 && -d "$dirname" ]]; then
- # show directory
- msg "Show directory context: $dirname"
- echo -e "HTTP/1.1 200 OK\r"
- echo -e "Content-Type: text/plain; charset=$encoding\r"
- echo -e "\r"
- ls -1gGhB --quoting-style=literal "$dirname"
- echo -e "\r"
- else
- # file not found
- msg "File not found: $filename"
- echo -e "HTTP/1.1 404 Not Found\r"
- echo -e "Content-Type: text/html; charset=$encoding\r"
- echo -e "\r"
- echo -e "404 Not Found<br />\r"
- echo -e "The requested resource was not found on the server<br />\r"
- echo -e "\r"
- fi
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement