#!/bin/sh
# fix $HOME when run from xinetd (which does run it as root...)
if [ "$HOME" = "/" -o "$HOME" = "" ]; then
HOME="/root"
export HOME
fi
# set up standard environment
. $HOME/.shenv
# Make a tunnel with SSH to send e-mail via the SDF mail exchanger,
# and then netcat to that tunnel. Designed to be run by xinetd.
# An alternative approach is to just run `ssh foo@bar nc ..' but doing
# it with a port-forward means that our SSH can be restricted to the
# command rrsync and a particular port-forward, rather than netcat so
# we can use one SSH key for both purposes.
# Interesting notes for doing this on Windows:
#
SOCKET="$HOME/tmp/smtptun_sock"
ALTSOCKET="/tmp/ssh-swhitton-spw@ma.sdf.org:22"
REMHOST="spw@ma.sdf.org"
FORWARD="-L localhost:8025:mx.sdf.org:25"
ID="-i $HOME/.ssh/id_rsa"
# First see if I'm SSHing to the MetaArray already. Requires running
# as root in order to be able to command the socket to add the port
# forward.
# if ssh -O check -S $ALTSOCKET $REMHOST 2>/dev/null; then
# # Check the port isn't already bound ...
# if ! ssh -O check -S $SOCKET $REMHOST 2>/dev/null; then
# ssh -O forward $FORWARD -S $ALTSOCKET $REMHOST
# fi
# else
# Now see if another invocation of this script has already constructed a tunnel.
if ! ssh -O check -S $SOCKET $REMHOST 2>/dev/null; then
# Okay, we'd better set-up a tunnel. Make it only accessible from
# localhost and have it time out after two minutes of no e-mails
# getting sent down it.
# Due to an OpenSSH bug
# , we
# persist the socket for only five seconds. The following SSH
# process hangs on to STDERR, which means this script doesn't
# exit once the netcat command is finished.
ssh -M -S $SOCKET -o "ControlPersist=5s" \
-f -N $FORWARD $REMHOST $ID
fi
# fi
# Now connect to the tunnel we just made.
nc localhost 8025
# Remove forwarding from swhitton's connection if we added it, and no
# other script invocations are using it (to prevent a situation where
# the other script has started and passed the if-statement to not
# construct the tunnel, but hasn't started netcat yet (if it's already
# started netcat, then it's safe from the -O cancel we do here). A
# crude check.
# if ssh -O check -S $ALTSOCKET $REMHOST 2>/dev/null; then
# us=$(basename $0)
# count=$(pgrep $us | wc -l)
# if ! [ "$count" -gt 3 ]; then
# ssh -O cancel $FORWARD -S $ALTSOCKET $REMHOST
# fi
# fi