#!/bin/sh

# Copyright (C) 2015 by Yuri Victorovich. All rights reserved.

###
### This is the telnet-like application to control the vm-to-tor
### virtual machine.
### It expects the virtual machine name in the form tapN.
### It can only run when vm-to-tor was started with the following
### parameters set in /etc/rc.conf:
### * vm_to_tor_control_socket="YES"
### * vm_to_tor_allow_cookie_auth="YES"
###

## check usage and extract command line arguments

if [ "$#" -ne 1 -o -z "$1" ]; then
  echo "Usage:     ${0##*/} tapN"
  exit 1
fi

VM=$1

## check user

if [ $(id -u) != 0 -a $(id -un) != "_tor" ]; then
  echo "Only root and _tor users can run ${0##*/}" >&2
  exit 1
fi

## directory base of the VM, check that virtual machine exists

VM_DIR=/var/tmp/vm-to-tor/${VM}

if [ ! -d "${VM_DIR}" ]; then
  echo "Virtual machine $VM not found" 2>&1
  exit 1
fi

## check if control socket and cookie exist

if [ ! -S "${VM_DIR}/ctrl" ]; then
  echo "No control socket found for virtual machine $VM" 2>&1
  exit 1
fi
if [ ! -f "${VM_DIR}/data/control_auth_cookie" -o $(ls -l "${VM_DIR}/data/control_auth_cookie" | awk '{ print $5}') != 32 ]; then
  echo "No control socket cookie found for virtual machine $VM" 2>&1
  exit 1
fi

## check if the VM runs

if [ ! -s ${VM_DIR}/tor.pid -o "$(procstat $(cat ${VM_DIR}/tor.pid) | tail -1 | sed -E 's/^[[:space:]]*([0-9]+).*/\1/g' 2>/dev/null)" != "$(cat ${VM_DIR}/tor.pid)" ]; then
  echo "Virtual machine $VM is not running" 2>&1
  exit 1
fi

## Run: automatically authenticate and accept user termonal input

(echo "(auto-login)" >&2; echo -n "AUTHENTICATE " ; hexdump -e '32/1 "%02x""\n"' "${VM_DIR}/data/control_auth_cookie"; cat) | \
  nc -U "${VM_DIR}/ctrl"

