refactored command registration

This commit is contained in:
tracer 2022-09-27 19:13:28 +02:00
parent 4c80ba1543
commit 61ec6aaaa5
1 changed files with 1623 additions and 1387 deletions

View File

@ -11,8 +11,13 @@ define(constant_name: 'COLOR_BLUE', value: "\033[34m");
define(constant_name: 'COLOR_WHITE', value: "\033[37m");
define(constant_name: 'COLOR_DEFAULT', value: "\033[39m");
use App\Controller\Commands\Command;
use App\Controller\Commands\CommandGroup;
use App\Controller\Commands\CommandGroupContainer;
use App\Entity\Apikey;
use App\Entity\Domain;
use App\Entity\DynDNS;
use App\Entity\KeyHelp\KeyHelpDomain;
use App\Entity\Nameserver;
use App\Entity\Panel;
use App\Repository\ApikeyRepository;
@ -22,7 +27,10 @@ use App\Repository\NameserverRepository;
use App\Repository\PanelRepository;
use Arubacao\TldChecker\Validator;
use Exception;
use JsonMapper;
use JsonMapper_Exception;
use LucidFrame\Console\ConsoleTable;
use SodiumException;
if (php_sapi_name() !== 'cli') {
exit;
@ -35,6 +43,7 @@ if (php_sapi_name() !== 'cli') {
class CLIController
{
private array $arguments;
private CommandGroupContainer $commandGroupContainer;
/**
* @throws Exception
@ -48,9 +57,159 @@ class CLIController
private readonly NameserverRepository $nameserverRepository,
private readonly PanelRepository $panelRepository,
private readonly ConfigController $configController,
private readonly EncryptionController $encryptionController,
private $logger)
{
$this->checkSetup();
$this->commandGroupContainer = (new CommandGroupContainer())
->add(commandGroup: (new CommandGroup(name: 'check', description: 'health checks the system can perform'))
->addCommand(command: new Command(
name: 'permissions',
callback: function () {
$this->handleCheckPermissions();
},
description: 'health checks the system can perform'))
->addCommand(command: new Command(
name: 'panels',
callback: function () {
$this->handleCheckPanels();
},
optionalParameters: ['ID', 'fix=xes']))
->addCommand(command: new Command(
name: 'domains',
callback: function () {
$this->handleCheckDomains();
}))
->addCommand(command: new Command(
name: 'showincludes',
callback: function () {
$this->handleCheckShowIncludes();
},
description: 'Shows needed setting on panels'))
->addCommand(command: new Command(
name: 'generatekey',
callback: function () {
$this->handleCheckGenerateKey();
},
description: 'Generates a a new key for encryption'))
->addCommand(command: new Command(
name: 'setup',
callback: function () {
$this->handleCheckSetup();
},
mandatoryParameters: ['username'],
description: 'Adapt filesystem permissions (requires elaborated permissions)'))
->addCommand(command: new Command(
name: 'version',
callback: function () {
$this->handleChecksVersion();
},
optionalParameters: ['major:minor:patch'],
description: 'Read or set the bindApi version in the database')))
->add(commandGroup: (new CommandGroup(name: 'panels', description: 'all KeyHelp systems configured'))
->addCommand(command: new Command(
name: 'list',
callback: function () {
$this->handlePanelsList();
}))
->addCommand(command: new Command(
name: 'create',
callback: function () {
$this->handlePanelsCreate();
},
mandatoryParameters: ['name'],
optionalParameters: ['A=<IPv4>', 'AAAA=<IPv6>', 'apikey=<API-Key>']))
->addCommand(command: new Command(
name: 'update',
callback: function () {
$this->handlePanelsUpdate();
},
mandatoryParameters: ['ID'],
optionalParameters: ['name=<name>', 'A=<IPv4>', 'AAAA=<IPv6>', 'apikey=<API-Key>']))
->addCommand(command: new Command(
name: 'delete',
callback: function () {
$this->handlePanelsDelete();
},
mandatoryParameters: ['ID']))
->addCommand(command: new Command(
name: 'apiping',
callback: function () {
$this->handleApiPing();
},
optionalParameters: ['ID'])))
->add(commandGroup: (new CommandGroup(name: 'nameservers', description: 'available nameservers'))
->addCommand(command: new Command(
name: 'list',
callback: function () {
$this->handleNameserversList();
}))
->addCommand(command: new Command(
name: 'create',
callback: function () {
$this->handleNameserversCreate();
},
mandatoryParameters: ['name'],
optionalParameters: ['A=<IPv4>', 'AAAA=<IPv6>', 'apikey=<API-Key>']))
->addCommand(command: new Command(
name: 'update',
callback: function () {
$this->handleNameserversUpdate();
},
mandatoryParameters: ['ID'],
optionalParameters: ['name=<name>', 'A=<IPv4>', 'AAAA=<IPv6>', 'apikey=<API-Key>']))
->addCommand(command: new Command(
name: 'delete',
callback: function () {
$this->handleNameserversDelete();
},
mandatoryParameters: ['ID']))
->addCommand(command: new Command(
name: 'apiping',
callback: function () {
$this->handleApiPing();
},
optionalParameters: ['ID'])))
->add(commandGroup: (new CommandGroup(name: 'domains', description: 'configured domains'))
->addCommand(command: new Command(
name: 'list',
callback: function () {
$this->handleDomainsList();
}))
->addCommand(command: new Command(
name: 'refresh',
callback: function () {
$this->handleDomainsRefresh();
},
mandatoryParameters: ['name'],
optionalParameters: ['A=<IPv4>', 'AAAA=<IPv6>', 'apikey=<API-Key>'])))
->add(commandGroup: (new CommandGroup(name: 'dyndns', description: 'handle DynDNS entries'))
->addCommand(command: new Command(
name: 'list',
callback: function () {
$this->handleDynDnsList();
}))
->addCommand(command: new Command(
name: 'create',
callback: function () {
$this->handlePanelsCreate();
},
mandatoryParameters: ['hostname.example.com', 'password'],
description: 'FQDN within a domain where this server is master'))
->addCommand(command: new Command(
name: 'update',
callback: function () {
$this->handlePanelsUpdate();
},
mandatoryParameters: ['ID'],
optionalParameters: ['name=<name>', 'A=<IPv4>', 'AAAA=<IPv6>', 'apikey=<API-Key>']))
->addCommand(command: new Command(
name: 'delete',
callback: function () {
$this->handlePanelsDelete();
},
mandatoryParameters: ['ID'])));
}
function checkSetup(): void
@ -76,8 +235,6 @@ class CLIController
}
// TODO encrypt the password in the config file, key in config
function runCommand(array $arguments): void
{
if (count($arguments) < 1) {
@ -96,16 +253,7 @@ class CLIController
}
$this->arguments = $this->parseArguments(arguments: $arguments);
match ($command) {
'check' => $this->handleChecks(subcommand: $subcommand),
'panels' => $this->handlePanels(subcommand: $subcommand),
'apikeys' => $this->handleApiKeys(subcommand: $subcommand),
'domains' => $this->handleDomains(subcommand: $subcommand),
'dyndns' => $this->handleDynDns(subcommand: $subcommand),
'nameservers' => $this->handleNameservers(subcommand: $subcommand),
default => $this->unknownCommand(command: $command)
};
$this->commandGroupContainer->run(command: $command, subcommand: $subcommand);
}
@ -116,6 +264,15 @@ class CLIController
{
$this->logger->debug(message: "showUsage()");
$debug = $this->configController->getConfig(configKey: 'debug');
echo 'bindAPI version: todo (env: todo) ';
if ($debug) {
echo 'true';
} else {
echo 'false';
}
echo COLOR_DEFAULT . ')' . PHP_EOL;
echo COLOR_YELLOW . 'Usage:' . PHP_EOL;
echo COLOR_DEFAULT . "\t./bin/console {options} {arguments}" . PHP_EOL . PHP_EOL;
@ -123,33 +280,9 @@ class CLIController
echo COLOR_GREEN . "\t-v, --version\t\t" . COLOR_DEFAULT . "Display the version of the API" . PHP_EOL;
echo COLOR_GREEN . "\t-V, --verbose\t\t" . COLOR_DEFAULT . "All :lists command are auto-verbose" . PHP_EOL . PHP_EOL;
echo COLOR_YELLOW . 'Arguments:' . PHP_EOL;
echo COLOR_YELLOW . "check" . COLOR_WHITE . "\t health checks the system can perform" . PHP_EOL;
echo COLOR_GREEN . "\t check:permissions" . PHP_EOL;
echo COLOR_GREEN . "\t check:panels {ID} {fix=yes}" . PHP_EOL;
echo COLOR_GREEN . "\t check:domains" . PHP_EOL;
echo COLOR_GREEN . "\t check:showincludes" . COLOR_WHITE . " Shows needed setting on panels" . PHP_EOL;
echo COLOR_GREEN . "\t check:generatekey" . COLOR_WHITE . " Generates a key for encryption" . PHP_EOL;
echo COLOR_GREEN . "\t check:setup <username>" . COLOR_WHITE . " Adapt filesystem permissions (requires elaborated permissions)" . PHP_EOL;
echo COLOR_YELLOW . 'Arguments: ' . COLOR_WHITE . '<mandatory> {optional}' . PHP_EOL;
echo COLOR_YELLOW . "panels" . COLOR_WHITE . "\t all KeyHelp systems configured" . PHP_EOL;
echo COLOR_GREEN . "\t panels:list" . PHP_EOL;
echo COLOR_GREEN . "\t panels:create <name> {A=<IPv4>} {AAAA=<IPv6>} {apikey=<API-Key>}" . PHP_EOL;
echo COLOR_GREEN . "\t panels:update <ID> {name=<name>} {A=<IPv4>} {AAAA=<IPv6>} {apikey=<API-Key>}" . PHP_EOL;
echo COLOR_GREEN . "\t panels:delete <ID>" . PHP_EOL;
echo COLOR_GREEN . "\t panels:apiping {<ID>}" . PHP_EOL;
echo COLOR_YELLOW . "nameservers" . COLOR_WHITE . " available nameservers" . PHP_EOL;
echo COLOR_GREEN . "\t nameservers:list" . PHP_EOL;
echo COLOR_GREEN . "\t nameservers:create <name> {A=<IPv4>} {AAAA=<IPv6>} {apikey=<API-Key>}" . PHP_EOL;
echo COLOR_GREEN . "\t nameservers:update <ID> {name=<name>} {A=<IPv4>} {AAAA=<IPv6>} {apikey=<API-Key>}" . PHP_EOL;
echo COLOR_GREEN . "\t nameservers:delete <ID>" . PHP_EOL;
echo COLOR_GREEN . "\t nameservers:apiping {<ID>}" . PHP_EOL;
echo COLOR_YELLOW . "domains" . COLOR_WHITE . " configured domains" . PHP_EOL;
echo COLOR_GREEN . "\t domains:list" . PHP_EOL;
echo COLOR_GREEN . "\t domains:refresh" . PHP_EOL;
$this->commandGroupContainer->printCommands();
echo COLOR_YELLOW . "dyndns" . COLOR_WHITE . " handle dyndns entries" . PHP_EOL;
echo COLOR_GREEN . "\t dyndns:list" . PHP_EOL;
@ -166,21 +299,6 @@ class CLIController
echo PHP_EOL . "\033[39me.g. ./bin/console apikeys:list" . PHP_EOL;
}
function handleChecks(string $subcommand): void
{
$this->logger->debug(message: "handleChecks()");
match ($subcommand) {
'permissions' => $this->handleCheckPermissions(),
'panels' => $this->handleCheckPanels(),
'domains' => $this->handleCheckDomains(),
'showincludes' => $this->handleCheckShowIncludes(),
'generatekey' => $this->handleCheckGenerateKey(),
'setup' => $this->handleCheckSetup(),
default => $this->unknownSubcommand(subcommand: $subcommand)
};
}
function unknownCommand(string $command): void
{
@ -199,7 +317,7 @@ class CLIController
/**
*/
function handleCheckPermissions(): void
public function handleCheckPermissions(): void
{
$this->logger->debug(message: "handleCheckPermissions()");
@ -215,6 +333,23 @@ class CLIController
}
/*
public function handleCheckPermissions(): void
{
$this->logger->debug(message: "handleCheckPermissions()");
if (!$this->domainController->checkPermissions()) {
if ($this->configController->getConfig(configKey: 'verbose')) {
echo PHP_EOL . COLOR_DEFAULT;
echo 'Missing permissions, please run ' . COLOR_YELLOW . './bin/console check:setup' . COLOR_DEFAULT . ' as root or with sudo.' . PHP_EOL;
}
exit(1);
} else {
exit(0);
}
}
*/
function handleCheckSetup(): void
{
if (count($this->arguments) < 2) {
@ -322,7 +457,7 @@ class CLIController
/**
* @param \App\Entity\Panel $panel
* @param Panel $panel
*
* @return void
*/
@ -330,7 +465,10 @@ class CLIController
{
$this->logger->debug(message: "checkSinglePanel()");
echo COLOR_DEFAULT . 'KeyHelp-Panel: ' . COLOR_YELLOW . $panel->getName();
echo COLOR_DEFAULT . 'KeyHelp-Panel: ' . COLOR_YELLOW . $panel->getName() . COLOR_DEFAULT;
$encryptionKey = $this->configController->getConfig(configKey: 'encryptionKey');
$decryptedKey = $this->encryptionController->safeDecrypt(encrypted: $panel->getApikey(), key: $encryptionKey);
if ($this->configController->getConfig(configKey: 'verbose')) {
if (empty($panel->getA())) {
@ -338,7 +476,7 @@ class CLIController
requestType: 'GET',
serverName: $panel->getName(),
versionIP: 6,
apiKey: $panel->getApikey(),
apiKey: $decryptedKey,
command: '/server',
serverType: 'panel');
} else {
@ -346,7 +484,7 @@ class CLIController
requestType: 'GET',
serverName: $panel->getName(),
versionIP: 4,
apiKey: $panel->getApikey(),
apiKey: $decryptedKey,
command: '/server',
serverType: 'panel');
}
@ -368,8 +506,8 @@ class CLIController
requestType: 'GET',
serverName: $panel->getName(),
versionIP: 6,
apiKey: $panel->getApikey(),
command: 'domains?sort=domain',
apiKey: $decryptedKey,
command: 'domains?sort=domain&subdomains=false',
serverType: 'panel'
);
} else {
@ -377,8 +515,8 @@ class CLIController
requestType: 'GET',
serverName: $panel->getName(),
versionIP: 4,
apiKey: $panel->getApikey(),
command: 'domains?sort=domain',
apiKey: $decryptedKey,
command: 'domains?sort=domain&subdomains=false',
serverType: 'panel');
}
@ -394,30 +532,89 @@ class CLIController
}
$maxDomainNameLength = 0;
$tmpDomainlist = [];
$tmpDomainList = [];
$mapper = new JsonMapper();
if (count($domains) > 0) {
foreach ($domains as $domain) {
if ($this->isValidSecondLevelDomain(domainName: $domain->domain, panel: $panel->getName(), parent: $domain->id_parent_domain)) {
$tmpDomainlist[] = $domain;
$mapper->bExceptionOnUndefinedProperty = true;
$mapper->bStrictNullTypes = false;
try {
$domainObject = $mapper->map(json: $domain, object: new KeyHelpDomain());
} catch (JsonMapper_Exception $e) {
die($e->getMessage() . PHP_EOL);
}
$tmpDomainList[] = $domainObject;
if (strlen(string: $domain->domain) > $maxDomainNameLength) {
$maxDomainNameLength = strlen(string: $domain->domain);
}
}
}
}
$domainCount = 0;
foreach ($tmpDomainlist as $domain) {
echo COLOR_DEFAULT . " Domain: " . COLOR_YELLOW . str_pad(string: $domain->domain, length: $maxDomainNameLength);
$this->checkNS(domainName: $domain->domain, panel: $panel);
foreach ($tmpDomainList as $domain) {
echo COLOR_DEFAULT . " Domain: " . COLOR_YELLOW . str_pad(string: $domain->getDomain(), length: $maxDomainNameLength);
if (!$domain->isSubdomain()) {
$this->checkNS(domainName: $domain->getDomain(), panel: $panel);
$domainCount++;
}
}
if ($domainCount == 0) {
echo 'No second level domains found.' . COLOR_DEFAULT . PHP_EOL;
}
echo PHP_EOL;
try {
sodium_memzero(string: $decryptedKey);
} catch (SodiumException $e) {
die($e->getMessage() . PHP_EOL);
}
}
function isSubDomain(Domain $domain): bool
{
$this->logger->debug(message: "isSubDomain()");
// valid second level domain
if (!Validator::endsWithTld(value: $domain)) {
return false;
}
$domainParts = explode(separator: '.', string: $domain->getName());
$reversedParts = array_reverse(array: $domainParts);
$testDomain = '';
$foundDomain = '';
foreach ($reversedParts as $part) {
if ($testDomain) {
$testDomain = $part . '.' . $testDomain;
} else {
$testDomain = $part;
}
if ($this->domainRepository->findByName(name: $testDomain)) {
$foundDomain = $testDomain;
echo $part . PHP_EOL;
}
}
echo "fould domain ***" . $foundDomain . PHP_EOL;
/*
// system domain
if (str_contains(haystack: $domainName, needle: $panel)) {
return false;
}
// no second level domain
if (substr_count(haystack: $domainName, needle: '.') > 1) {
return false;
}
*/
return true;
}
function isValidSecondLevelDomain(string $domainName, string $panel, int $parent): bool
{
@ -449,7 +646,7 @@ class CLIController
/**
* @param String $domainName
* @param \App\Entity\Panel $panel
* @param Panel $panel
*
* @return void
*/
@ -562,7 +759,7 @@ class CLIController
'list' => $this->handlePanelsList(),
'update' => $this->handlePanelsUpdate(),
'delete' => $this->handlePanelsDelete(),
'apiping' => $this->handleAPIPing(type: 'panel'),
'apiping' => $this->handleApiPing(type: 'panel'),
default => $this->unknownSubcommand(subcommand: $subcommand)
};
}
@ -595,14 +792,15 @@ class CLIController
exit(0);
}
$apikey = $this->arguments['apikey'] ?? '';
$self = intval(value: $this->arguments['self'] ?? 0);
$self = $this->arguments['self'] ?? 'no';
if ($this->panelRepository->findByName(name: $name)) {
echo "Panel: $name already exists." . PHP_EOL;
exit(1);
} else {
$result = $this->panelRepository->insert(name: $name, a: $a, aaaa: $aaaa, apikey: $apikey, self: $self);
$panel = new Panel(name: $name, a: $a, aaaa: $aaaa, passphrase: $apikey, self: $self);
$result = $this->panelRepository->insert(panel: $panel);
echo "Panel $name has been created with id $result" . PHP_EOL;
exit(0);
}
@ -620,20 +818,15 @@ class CLIController
echo 'All available panels:' . PHP_EOL;
$table = new ConsoleTable();
$table->setHeaders(content: ['ID', 'Name', 'A', 'AAAA', 'API Key (Prefix)', 'This Panel']);
foreach ($panels as $panel) {
$row = [];
$token = strtok(string: $panel->getApikey(), token: '.');
$row[] = $panel->getID();
$row[] = $panel->getName();
$row[] = $panel->getA();
$row[] = $panel->getAaaa();
$row[] = $token;
if ($panel->getSelf() == 1) {
$row[] = 'Yes';
} else {
$row[] = 'No';
}
$row[] = $panel->getApikeyPrefix();
$row[] = ucfirst(string: $panel->getSelf());
$table->addRow(data: $row);
}
$table->setPadding(value: 2);
@ -657,12 +850,7 @@ class CLIController
$a = $this->arguments['a'] ?? '';
$aaaa = $this->arguments['aaaa'] ?? '';
$apikey = $this->arguments['apikey'] ?? '';
$self = intval(value: $this->arguments['self'] ?? 0);
// a workaround for 0 being equal to false …
if ($self == 0) {
$self = -1;
}
$self = $this->arguments['self'] ?? '';
if ($id == 0) {
echo 'An ID is required' . PHP_EOL;
@ -672,8 +860,13 @@ class CLIController
echo "Panel with ID : $id doesn't exist." . PHP_EOL;
exit(1);
}
if ($this->panelRepository->update(id: $id, name: $name, a: $a, aaaa: $aaaa, apikey: $apikey, self: $self) !== false) {
echo 'Panel has been updated' . PHP_EOL;
if ($apikey) {
$panel = new Panel(name: $name, id: $id, a: $a, aaaa: $aaaa, passphrase: $apikey, self: $self);
} else {
$panel = new Panel(name: $name, id: $id, a: $a, aaaa: $aaaa, self: $self);
}
if ($this->panelRepository->update(panel: $panel) !== false) {
echo 'Panel ' . COLOR_YELLOW . $id . COLOR_DEFAULT . ' has been updated' . PHP_EOL;
} else {
echo 'Error while updating domain server.' . PHP_EOL;
}
@ -705,7 +898,7 @@ class CLIController
/**
*/
function handleAPIPing(string $type): void
function handleApiPing(string $type): void
{
$this->logger->debug(message: "handleApiPing()");
@ -725,7 +918,7 @@ class CLIController
$error = true;
}
} else {
if ($this->configController->getConfig(configKey: 'verbose')) {
if (!$this->configController->getConfig(configKey: 'quiet')) {
echo "Unknown $type ID $id" . PHP_EOL;
}
$error = true;
@ -742,10 +935,13 @@ class CLIController
}
}
}
if ($this->configController->getConfig(configKey: 'verbose')) {
if (!$this->configController->getConfig(configKey: 'quiet')) {
echo PHP_EOL;
}
if ($error) {
if (!$this->configController->getConfig(configKey: 'verbose')) {
echo 'There were errors, run command with -V (or -verbose) to see the errors.' . PHP_EOL;
}
exit(1);
} else {
exit(0);
@ -771,13 +967,15 @@ class CLIController
}
/**
* @param \App\Entity\Panel|\App\Entity\Nameserver $server
* @param Panel|Nameserver $server
* @param String $type
*
* @return bool
*/
public function checkPing(Panel|Nameserver $server, string $type): bool
{
$this->logger->debug(message: "handleApiPing() - server, type: " . $server->getName() . ', ' . $type);
$error = false;
if ($type == 'nameserver') {
@ -790,12 +988,16 @@ class CLIController
$maxAAAA = $this->panelRepository->getLongestEntry(field: 'aaaa');
}
if ($this->configController->getConfig(configKey: 'verbose')) {
if (!$this->configController->getConfig(configKey: 'quiet')) {
echo COLOR_YELLOW . str_pad(string: $server->getName(), length: $maxName);
}
$encryptionKey = $this->configController->getConfig(configKey: 'encryptionKey');
$decryptedKey = $this->encryptionController->safeDecrypt(encrypted: $server->getApikey(), key: $encryptionKey);
$a = $server->getA() ?? '';
if (!empty($a)) {
$this->logger->debug("check a");
if ($this->configController->getConfig(configKey: 'verbose')) {
echo COLOR_DEFAULT . ' ' . str_pad(string: $a, length: $maxA, pad_type: STR_PAD_LEFT) . ' ';
}
@ -803,14 +1005,17 @@ class CLIController
requestType: 'GET',
serverName: $server->getName(),
versionIP: 4,
apiKey: $server->getApikey(),
apiKey: $decryptedKey,
command: 'ping',
serverType: $type)) {
if ($this->configController->getConfig(configKey: 'verbose')) {
if (!$this->configController->getConfig(configKey: 'quiet')) {
if ($result['data'] == 'pong') {
echo COLOR_GREEN . $result['data'];
echo ' ' . COLOR_GREEN . $result['data'];
} else {
echo COLOR_BLUE . 'skip';
echo COLOR_BLUE . ' skip' . COLOR_DEFAULT;
if ($this->configController->getConfig(configKey: 'verbose')) {
echo ' ' . $result['data'];
}
}
}
} else {
@ -819,6 +1024,7 @@ class CLIController
}
$aaaa = $server->getAaaa() ?? '';
if (!empty($aaaa)) {
$this->logger->debug("check aaaa");
if ($this->configController->getConfig(configKey: 'verbose')) {
echo COLOR_DEFAULT . ' ' . str_pad(string: $aaaa, length: $maxAAAA, pad_type: STR_PAD_LEFT) . ' ';
}
@ -826,24 +1032,33 @@ class CLIController
requestType: 'GET',
serverName: $server->getName(),
versionIP: 6,
apiKey: $server->getApikey(),
apiKey: $decryptedKey,
command: 'ping',
serverType: $type)) {
if ($this->configController->getConfig(configKey: 'verbose')) {
if (!$this->configController->getConfig(configKey: 'quiet')) {
if ($result['data'] == 'pong') {
echo COLOR_GREEN . $result['data'];
echo ' ' . COLOR_GREEN . $result['data'];
} else {
echo COLOR_BLUE . $result['data']; // TODO 'skip';
echo COLOR_BLUE . ' skip' . COLOR_DEFAULT;
if ($this->configController->getConfig(configKey: 'verbose')) {
echo ' ' . $result['data'];
}
}
}
} else {
$error = true;
}
}
if ($this->configController->getConfig(configKey: 'verbose')) {
echo PHP_EOL;
try {
sodium_memzero(string: $decryptedKey);
} catch (SodiumException $e) {
die($e->getMessage() . PHP_EOL);
}
return $error;
if (!$this->configController->getConfig(configKey: 'quiet')) {
echo COLOR_DEFAULT . PHP_EOL;
}
return !$error;
}
/**
@ -869,9 +1084,27 @@ class CLIController
{
$name = $this->arguments['name'] ?? '';
$result = $this->apikeyRepository->create(name: $name);
echo 'API key ' . COLOR_YELLOW . $result['row'] . COLOR_DEFAULT . ' has been generated. Store it in a save place, it cannot be recovered.' . PHP_EOL;
echo "\033[32m\t" . $result['tokenPrefix'] . '.' . $result['key'] . PHP_EOL;
$apiKeyPrefix = uniqid();
try {
$apikeyRand = bin2hex(string: random_bytes(length: 24));
} catch (Exception $e) {
die($e->getMessage() . PHP_EOL);
}
$passphrase = password_hash(password: $apiKeyPrefix . '.' . $apikeyRand, algo: PASSWORD_ARGON2ID);
$apikey = new Apikey(name: $name, apikeyPrefix: $apiKeyPrefix, passphrase: $passphrase);
$result = $this->apikeyRepository->insert(apikey: $apikey);
if ($name) {
echo 'API key ' . COLOR_YELLOW . $name . COLOR_DEFAULT;
} else {
echo 'Unnamed API key ';
}
echo ' with ID ' . COLOR_YELLOW . $result . COLOR_DEFAULT . ' has been generated. Store it in a safe place, it cannot be recovered.' . PHP_EOL;
echo COLOR_YELLOW . $apiKeyPrefix . '.' . $apikeyRand . COLOR_DEFAULT . PHP_EOL;
exit(0);
}
@ -889,7 +1122,7 @@ class CLIController
$row = [];
$row[] = $key->getID();
$row[] = $key->getName();
$row[] = $key->getApiTokenPrefix();
$row[] = $key->getApikeyPrefix();
$table->addRow(data: $row);
}
$table->setPadding(value: 2);
@ -905,24 +1138,24 @@ class CLIController
*/
function handleApikeysUpdate(): void
{
// TODO check for use of id instead of number, mind for all occurences
$id = $this->arguments[1] ?? 0;
$id = intval(value: $this->arguments[1]) ?? 0;
$name = $this->arguments['name'] ?? '';
if ($id == 0) {
echo 'An ID is required' . PHP_EOL;
exit(1);
}
if (empty($name)) {
echo 'You need to supply the new name.' . PHP_EOL;
exit(1);
}
if (!$this->apikeyRepository->findByID(id: intval(value: $id))) {
echo "Apikeys with ID : $id doesn't exist." . PHP_EOL;
exit(1);
}
if ($this->apikeyRepository->update(id: intval(value: $id), name: $name) !== false) {
if (!$name) {
echo 'You need tu supply a name.' . PHP_EOL;
exit(1);
}
$apikey = new Apikey(id: $id, name: $name);
if ($this->apikeyRepository->update(apikey: $apikey) !== false) {
echo 'Apikey has been updated' . PHP_EOL;
} else {
echo 'Error while updating apikey.' . PHP_EOL;
@ -960,6 +1193,7 @@ class CLIController
match ($subcommand) {
'list' => $this->handleDomainsList(),
'refresh' => $this->handleDomainsRefresh(),
'update' => $this->handleDomainsUpdate(),
'delete' => $this->handleDomainsDelete(),
default => $this->unknownSubcommand(subcommand: $subcommand)
};
@ -1077,7 +1311,7 @@ class CLIController
if ($this->configController->getConfig(configKey: 'verbose')) {
echo "DynDNS host " . COLOR_YELLOW . $name . COLOR_DEFAULT . "will be created." . PHP_EOL;
// insert in db
$dyndnsHost = new DynDNS();
$dyndnsHost = new DynDNS(name: $name);
$dyndnsHost->setName($name);
}
}
@ -1125,8 +1359,7 @@ class CLIController
exit(1);
}
$arguments = $this->parseArguments();
$panel = $arguments['panel'] ?? '';
$panel = $this->arguments['panel'] ?? '';
if (empty($panel)) {
echo 'You need to supply the panel name.' . PHP_EOL;
@ -1159,11 +1392,9 @@ class CLIController
exit(1);
}
$arguments = $this->parseArguments();
$id = intval(value: $this->arguments[1] ?? 0);
$name = $arguments['name'] ?? '';
$panelName = $arguments['panel'] ?? '';
$name = $this->arguments['name'] ?? '';
$panelName = $this->arguments['panel'] ?? '';
if ($id == 0) {
echo 'An ID is required' . PHP_EOL;
@ -1273,23 +1504,27 @@ class CLIController
exit(1);
}
$arguments = $this->parseArguments();
$a = $arguments['a'] ?? '';
$aaaa = $arguments['aaaa'] ?? '';
$a = $this->arguments['a'] ?? '';
$aaaa = $this->arguments['aaaa'] ?? '';
if (empty($a) && empty($aaaa)) {
echo 'At least one IP address is required.' . PHP_EOL;
exit(0);
}
$apikey = $arguments['apikey'] ?? '';
$apikey = $this->arguments['apikey'] ?? '';
if (empty($apikey)) {
echo 'An API key is required.' . PHP_EOL;
exit(0);
}
if ($this->nameserverRepository->findByName(name: $name)) {
echo "Nameserver: $name already exists." . PHP_EOL;
exit(1);
} else {
$nameserver = new Nameserver(name: $name, a: $a, aaaa: $aaaa, apikey: $apikey);
$nameserver = new Nameserver(name: $name, a: $a, aaaa: $aaaa, passphrase: $apikey);
$result = $this->nameserverRepository->insert(nameserver: $nameserver);
echo "Nameserver $name has been created with id $result" . PHP_EOL;
echo 'Nameserver ' . COLOR_YELLOW . $name . COLOR_DEFAULT . ' has been created with id ' . COLOR_YELLOW . $result . COLOR_DEFAULT . PHP_EOL;
exit(0);
}
}
@ -1307,12 +1542,11 @@ class CLIController
$table->setHeaders(content: ['ID', 'Name', 'A', 'AAAA', 'API Key']);
foreach ($nameservers as $nameserver) {
$row = [];
$token = strtok(string: $nameserver->getApiKey(), token: '.');
$row[] = $nameserver->getId();
$row[] = $nameserver->getName();
$row[] = $nameserver->getA();
$row[] = $nameserver->getAaaa();
$row[] = $token;
$row[] = $nameserver->getApikeyPrefix();
$table->addRow(data: $row);
}
$table->setPadding(value: 2);
@ -1329,13 +1563,11 @@ class CLIController
*/
function handleNameserversUpdate(): void
{
$arguments = $this->parseArguments();
$id = $this->arguments[1] ?? 0;
$name = $arguments['name'] ?? '';
$a = $arguments['a'] ?? '';
$aaaa = $arguments['aaaa'] ?? '';
$apikey = $arguments['apikey'] ?? '';
$name = $this->arguments['name'] ?? '';
$a = $this->arguments['a'] ?? '';
$aaaa = $this->arguments['aaaa'] ?? '';
$apikey = $this->arguments['apikey'] ?? '';
if ($id == 0) {
echo 'An ID is required.' . PHP_EOL;
@ -1345,7 +1577,14 @@ class CLIController
echo 'Nameserver with ID ' . COLOR_YELLOW . $id . COLOR_DEFAULT . " doesn't exist." . PHP_EOL;
exit(1);
}
if ($this->nameserverRepository->update(id: intval(value: $id), name: $name, a: $a, aaaa: $aaaa, apikey: $apikey) !== false) {
if ($apikey) {
$nameserver = new Nameserver(name: $name, id: intval(value: $id), a: $a, aaaa: $aaaa, passphrase: $apikey);
} else {
$nameserver = new Nameserver(name: $name, id: intval(value: $id), a: $a, aaaa: $aaaa);
}
if ($this->nameserverRepository->update(nameserver: $nameserver) !== false) {
echo 'Nameserver ' . COLOR_YELLOW . $id . COLOR_DEFAULT . ' has been updated.' . PHP_EOL;
} else {
echo 'Error while updating nameserver ' . COLOR_YELLOW . $id . '.' . PHP_EOL;
@ -1480,26 +1719,27 @@ class CLIController
exit(0);
}
private
function handleCheckGenerateKey(): void
/**
*/
private function handleCheckGenerateKey(): void
{
echo 'This generates a fresh encryption key.' . PHP_EOL;
echo 'Copy it to config.json.' . PHP_EOL;
echo 'Note: You must update all API-Keys for panels and nameservers after changing the key!' . PHP_EOL;
$cStrong = false;
$bytes = null;
while (!$cStrong) {
$bytes = openssl_random_pseudo_bytes(length: 18, strong_result: $cStrong);
}
$hex = bin2hex(string: $bytes);
echo 'Suggested new key : ' . COLOR_YELLOW . $hex . COLOR_DEFAULT . '.' . PHP_EOL;
try {
$key = sodium_bin2hex(string: sodium_crypto_secretbox_keygen());
echo 'Suggested new key : "' . COLOR_YELLOW . $key . COLOR_DEFAULT . '".' . PHP_EOL;
echo PHP_EOL;
exit(0);
} catch (SodiumException $e) {
die($e->getMessage() . PHP_EOL);
}
private
function handleDomainsRefresh(): void
}
private function handleDomainsRefresh(): void
{
// TODO check for self in check:permissions
@ -1507,15 +1747,17 @@ class CLIController
$this->logger->debug(message: "handleDomainsRefresh()");
// TODO create getSelf()
$panel = $this->panelRepository->findByName(name: 'keyhelp.lab.24unix.net');
$panels = $this->panelRepository->findAll();
foreach ($panels as $panel) {
echo COLOR_DEFAULT . 'Checking panel ' . COLOR_YELLOW . $panel->getName() . COLOR_DEFAULT . PHP_EOL;
if (empty($panel->getA())) {
$result = $this->apiController->sendCommand(
requestType: 'GET',
serverName: $panel->getName(),
versionIP: 6,
apiKey: $panel->getApikey(),
command: 'domains?sort=domain',
command: 'domains?sort=domain&subdomains=false',
serverType: 'panel'
);
} else {
@ -1524,7 +1766,7 @@ class CLIController
serverName: $panel->getName(),
versionIP: 4,
apiKey: $panel->getApikey(),
command: 'domains?sort=domain',
command: 'domains?sort=domain&subdomains=false',
serverType: 'panel');
}
@ -1539,30 +1781,24 @@ class CLIController
exit(1);
}
// TODO remove stale domains
$domainCount = 0;
if (count($domains) > 0) {
foreach ($domains as $domain) {
if ($this->isValidSecondLevelDomain(domainName: $domain->domain, panel: $panel->getName(), parent: $domain->id_parent_domain)) {
$domainCount++;
echo COLOR_YELLOW . $domain->domain;
echo COLOR_YELLOW . ' ' . $domain->domain;
if ($this->domainRepository->findByName(name: $domain->domain)) {
echo COLOR_GREEN . ' OK';
echo COLOR_GREEN . ' OK' . COLOR_DEFAULT . PHP_EOL;
} else {
$newDomain = new Domain(name: $domain->domain, panel: $panel->getName());
$result = $this->domainRepository->insert(domain: $newDomain);
echo COLOR_DEFAULT . ' has been created with id ' . COLOR_YELLOW . $result . COLOR_DEFAULT . '.' . PHP_EOL;
}
echo PHP_EOL;
}
}
}
if ($domainCount == 0) {
echo 'No second level domains found.' . COLOR_DEFAULT . PHP_EOL;
}
echo PHP_EOL;
}
$this->domainController->updateSlaveZones();
}
}