Skip to content

Instantly share code, notes, and snippets.

@alex-phillips
Created July 29, 2015 12:39
Show Gist options
  • Save alex-phillips/7dbdb7f58009ad2d8075 to your computer and use it in GitHub Desktop.
Save alex-phillips/7dbdb7f58009ad2d8075 to your computer and use it in GitHub Desktop.
<?php
class VPNNetMonitoring extends Primer\Console\Command\BaseCommand
{
private $vpnInterface = 'ppp0';
public function configure()
{
$this->setName('netmon:transmission');
$this->setDescription("Monitoring the necessary network interface to bind all Transmission traffic through");
}
public function run()
{
if ($this->isVpnConnected()) {
return;
}
// Quit Transmission
`osascript -e 'quit app "Transmission"'`;
$count = 0;
do {
if ($count === 5) {
$this->out("Unable to start FrootVPN. Exiting.");
return;
}
// Start the VPN
`/usr/sbin/scutil --nc start FrootVPN`;
sleep(10);
$count++;
} while (!$this->isVpnConnected());
$interface = json_decode($this->getIpByInterface($this->vpnInterface), true);
$ip = trim($interface['ip_address']);
$this->out("VPN is connected with IP '{$ip}'");
$this->out("Writing Transmission defaults variable");
`defaults write org.m0k.transmission BindAddressIPv4 "$ip"`;
sleep(2);
$value = trim(`defaults read org.m0k.transmission BindAddressIPv4`);
if ($value !== $ip) {
$this->out("Defaults value doesn't not match IP. IP = $ip, value = $value");
return;
}
$this->out("Opening Transmission");
`open /Applications/Transmission.app`;
}
private function isVpnConnected()
{
$status = `/usr/sbin/scutil --nc status FrootVPN`;
if (preg_match('#\AConnected#', $status)) {
return true;
}
return false;
}
private function getIpByInterface($interface)
{
$cmd = <<<__CMD__
function get_address {
ELEM=($(echo $1 | tr ":" "\\n"))
echo \${ELEM[1]}
}
PLATFORM=$(uname)
IFACE="$1"
IFCFG=$(ifconfig "$interface")
if [ \$PLATFORM == "Linux" ]; then
IFACE_DATA=($(echo "\$IFCFG" | grep "inet addr" | awk '{print $2"\n"$3"\n"$4}'))
MACADDR=$(echo "\$IFCFG" | grep HWaddr | awk '{print $5}')
ADDRESS=$(get_address \${IFACE_DATA[0]})
BROADCAST=$(get_address \${IFACE_DATA[1]})
NETMASK=$(get_address \${IFACE_DATA[2]})
else #On OS X (\$PLATFORM == "Darwin")
IFACE_DATA=($(echo "\$IFCFG" | grep "inet " | awk '{print $2"\\n"$4"\\n"$6}'))
MACADDR=$(echo "\$IFCFG" | grep ether | awk '{print $2}')
ADDRESS=\${IFACE_DATA[0]}
BROADCAST=\${IFACE_DATA[2]}
NETMASK=\${IFACE_DATA[1]}
fi
echo "{"
echo " \"dev\": \"\$IFACE\","
echo " \"mac_address\": \"\${MACADDR}\","
echo " \"ip_address\": \"\${ADDRESS}\","
echo " \"broadcast\": \"\${BROADCAST}\","
echo " \"netmask\": \"\${NETMASK}\""
echo "}"
__CMD__;
return `$cmd`;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment