openvpn plugin refactor

This commit is contained in:
kirillius 2024-12-26 14:27:57 +03:00
parent 5ed9abb12f
commit fdd33ffe31
6 changed files with 85 additions and 37 deletions

29
bin/ovpn-connect Executable file
View File

@ -0,0 +1,29 @@
#!/usr/bin/php
<?php
require_once dirname(__DIR__) . "/loader.php";
require_once dirname(__DIR__) . "/plugins/openvpn/Openvpn.php";
try {
if (!isset($argv[1])) {
throw new RuntimeException("Output config is not set");
}
$rpc = new StaticRPC();
$instance = $rpc->getPlugins()["openvpn"] ?? null;
if ($instance === null) {
throw new RuntimeException("Plugin is not enabled");
}
/**
* @var Openvpn $instance
*/
$config = $instance->getRoutingConfig();
$outfile = $argv[1];
file_put_contents($outfile, implode("\n", $config));
} catch (Exception $e) {
echo "\nError:" . $e->getMessage() . "\n";
exit(1);
}
exit(0);

View File

@ -2,8 +2,8 @@
class RPC
{
private Config $config;
private array $plugins = [];
protected Config $config;
protected array $plugins = [];
public function __construct()
{

15
classes/StaticRPC.php Normal file
View File

@ -0,0 +1,15 @@
<?php
class StaticRPC extends RPC
{
public function __construct()
{
parent::__construct();
}
public function getPlugins(): array
{
return $this->plugins;
}
}

33
plugins/openvpn/Openvpn.php Executable file
View File

@ -0,0 +1,33 @@
#!/usr/bin/php
<?php
class Openvpn implements IPluggable
{
private PluginContext $context;
public function init(PluginContext $context)
{
$this->context = $context;
}
public function getRoutingConfig(): array
{
$networks = (new NetworkConfigReader())->getConfigs();
$data = [];
//add new routes
foreach ($this->context->getConfig() ["networks"] as $key) {
if (isset($networks[$key])) {
foreach ($networks[$key]["networks"] as $route) {
$parts = explode("/", $route);
$mask = long2ip(-1 << (32 - (int)$parts[1]));
$dst = $parts[0];
$data[] = "push \"route {$dst} {$mask}\"";
}
}
}
return $data;
}
}

View File

@ -0,0 +1,6 @@
{
"class": "Openvpn",
"config": {
}
}

View File

@ -1,35 +0,0 @@
#!/usr/bin/php
<?php
if (!isset($argv[1])) {
exit(1);
}
$TMPFILE = $argv[1];
require_once dirname(__DIR__, 2) . "/loader.php";
try {
$networks = (new NetworkConfigReader())->getConfigs();
$config = new Config();
$config->read();
$data = [];
//add new routes
foreach ($config["networks"] as $key) {
if (isset($networks[$key])) {
foreach ($networks[$key]["networks"] as $route) {
$parts = explode("/", $route);
$mask = long2ip(-1 << (32 - (int)$parts[1]));
$dst = $parts[0];
$data[] = "push \"route {$dst} {$mask}\"";
}
}
}
file_put_contents($TMPFILE, implode("\n", $data));
} catch (Exception $e) {
echo "\nError:" . $e->getMessage() . "\n";
exit(1);
}
exit(0);