KSH Web Server
This is a barely functioning webserver I wrote for fun while staying in a cabin in the woods.
#!/bin/ksh
# Settings
app_name="Shell Webserver"
version="0.2"
port="8080"
fifo="/home/cosmic/http"
# Trap
trap 'clean_exit' INT TERM HUP KILL
# Functions
clean_exit() {
echo
rm "$fifo" && log "FIFO destroyed"
pkill nc && log "nc killed" || log "nc not running"
log "Bye! :)"
exit 0
}
log() {
date_string="$(date +"%Y-%m-%d %H:%M:%S")"
printf "%s: %s\n" "$date_string" "$1"
}
# Init
log "${app_name} v${version} - Starting up"
# Create pipe
test -p "$fifo" || (mkfifo "$fifo"; log "FIFO created")
# Main loop
counter=0
while true
do
log "Inc counter"
counter=$(( $counter + 1 ))
log "Configuring response"
http_status="200 OK"
content_type="text/plain"
response_text="Hello, world! Visitor number: ${counter}"
log "Creating response"
response=$(
cat <<EOF
HTTP/${http_status}
Host: $(hostname)
Content-Type: ${content_type}
Content-Length: ${#response_text}
${response_text}
EOF
)
# Server
log "Start server..."
HTTP_RESPONSE="$(
# Start listener
nc -l "$port" < $fifo &
log "Now listening on port ${port}"
log "Incoming request: ${counter}"
# Send response
printf "%s" "$response" > $fifo &
)"
printf "%s" "$response" > $fifo &
# Print request
log "Request data:"
echo "${HTTP_RESPONSE}"
log "Request EOF"
done