laconia/laconia

72 lines
1.8 KiB
Bash
Executable File

#!/bin/bash
PROGNAME=${0##*/}
VERSION="0.0.1"
error_exit() {
printf "%s: %s\n" "$PROGNAME" "${1:-"Unknown Error"}" >&2
exit 1
}
usage() {
printf "usage: %s [OPTIONS] URI [ARGS]\n" "$PROGNAME"
printf "Simple client for spartan protocol\n"
printf "Options:
-h, --help - display this help
-p, --port - change port number (default is 300)
-m, --message - input as string
-i, --input-file - input as file
-u, --url - url to the capsule\n"
}
request(){
page=$(printf "$host /$path $post_len\r\n$post\r\n" | nc $host $port)
status=$(echo $page | awk 'NR == 1 {print $1}')
meta=$(echo $page | awk 'NR == 1 {$1=="";print}')
if [[ $status == 2 ]]; then
echo -e "$page" | awk 'NR > 1 {print}'
elif [[ $status == 3 ]]; then
#path=$meta
printf "%s %s %s\r\n%s\r\n" "$host" "/$path/" "$post_len" "$post" | nc $host $port | awk 'NR > 1 {print}'
elif [[ $status == 4 ]]; then
printf "Client error: %s\n" "$meta"
elif [[ $status == 5 ]]; then
printf "Server error: %s\n" "$meta"
fi
}
while getopts ":h:p:i:m:u:" arg; do
case $arg in
h | --help)
usage; exit ;;
p | --port)
export port=$OPTARG
;;
i | --input-file)
export post=$(cat $OPTARG)
export post_len=$(echo $post | wc -c )
;;
m | --message)
export post=$OPTARG
export post_len=$(echo $post | wc -c )
;;
u | --url)
url_unparsed=$OPTARG
#pattern=^((spartan)://)?([^/:]+)(:([0-9]+))?/(.*)$
#echo $url_unparsed
if [[ "$url_unparsed" =~ ^((spartan)://)?([^/:]+)(:([0-9]+))?/(.*)$ ]]; then
url=$(echo $url_unparsed | sed -e 's,spartan://,,g')
host=$(echo "$url" | sed -e 's|^[^/]*//||' -e 's|/.*$||')
path="$(echo $url | grep / | cut -d/ -f2-)"
port=${port:-300}
post=${post:-""}
post_len=${post_len:-0}
request
else
echo $url_unparsed is not a Spartan URL
fi
;;
*)
usage; error_exit "unknown option $1" ;;
esac
done