dobroho_vechora/dobroho_vechora.bash

171 lines
2.8 KiB
Bash
Executable File

#!/bin/bash
set -e
mode="${1}"
ip="${2}"
port="${3}"
nick="${4}"
print_usage() {
echo "${1}"
echo "${0} <MODE> <IP> <PORT> [NICK]"
echo "Modes: interactive (intr), send, receive (rec)"
exit
}
[ -z "${ip}" ] && print_usage 'No IP given.'
[ -z "${port}" ] && print_usage 'No port given.'
[ -z "${5}" ] || print_usage 'Too many arguments.'
[ -z "${nick}" ] || nick="<${nick}> "
open_socket() {
exec 3<> "/dev/tcp/${ip}/${port}"
}
close_socket() {
exec 3>&-
}
send_message() {
open_socket
echo "${1}" >&3
close_socket
}
get_message() {
open_socket
echo "${1}" >&3
cat <&3 || true
close_socket
}
case "${mode}" in
intr | interactive)
;;
send)
open_socket
text="${nick}$(cat)"
send_message "0${text}"
close_socket
exit
;;
rec | receive)
length="$(get_message 1)"
open_socket
echo -n 2 >&3
head -c "${length}" <&3
close_socket
exit
;;
*)
echo Unknown mode
exit
esac
encrypt() {
if [ "${enc}" -eq 0 ] || [ -z "${DOBROHO_VECHORA_ENCRYPTION_PASSWORD}" ]; then
cat
return 0
fi
echo "ENCRYPTED"'!'"<$(openssl enc -pbkdf2 -A -aes256 -pass env:DOBROHO_VECHORA_ENCRYPTION_PASSWORD)>"
}
decrypt() {
if [ "${enc}" -eq 0 ] || [ -z "${DOBROHO_VECHORA_ENCRYPTION_PASSWORD}" ]; then
cat
return 0
fi
while IFS="" read -r i || [ -n "${i}" ]
do
echo "${i}"
cipher="$(echo "${i}" | grep -Po 'ENCRYPTED!<\K([a-zA-Z0-9\=\+\/]*)(?=\>)')" || :
if [ -n "${cipher}" ]; then
echo -n "Decrypted: "
echo "$(echo "${cipher}" | openssl enc -pbkdf2 -d -A -aes256 -pass env:DOBROHO_VECHORA_ENCRYPTION_PASSWORD || :)"
fi
done
}
print_messages() {
open_socket
echo -n 2 >&3
head -c "${1}" <&3 | decrypt | sed -e 's/\x1B/ESC/g'
close_socket
}
wait_for_messages() {
tmp=0
trap 'tmp=1' INT
oldlength="${length}"
while :; do
length="$(get_message 1)"
if [ "${oldlength}" -ne "${length}" ]; then
trap - INT
return 0
fi
if [ "${tmp}" -eq 1 ]; then
trap - INT
return 1
fi
echo -n .
sleep 1
done
}
length=0
enc=0
while :; do
read cmd
case "${cmd}" in
I)
tmp="$(mktemp)"
"${VISUAL:-"${EDITOR:-"$(which vi)"}"}" "${tmp}"
[ -s "${tmp}" ] && send_message 0"${nick}$(cat "${tmp}" | encrypt)"
rm "${tmp}"
;;
i)
read a
send_message 0"${nick}$(echo "${a}" | encrypt)"
;;
L)
length="$(get_message 1)"
;;
l)
echo "${length}"
;;
w)
wait_for_messages &&
{
echo
print_messages "${length}"
if [ -n "${DOBROHO_VECHORA_ON_WAIT}" ]; then
${DOBROHO_VECHORA_ON_WAIT}
fi
}
;;
p)
length="$(get_message 1)"
print_messages "${length}"
;;
q)
exit
;;
E)
read -s DOBROHO_VECHORA_ENCRYPTION_PASSWORD
export DOBROHO_VECHORA_ENCRYPTION_PASSWORD
;;
e)
if [ "${enc}" -eq 0 ]; then
enc=1
echo 1
else
enc=0
echo 0
fi
;;
*)
echo '?'
;;
esac
done