Compare commits

..

No commits in common. "f70e87afce3ccfc962e1f7489b70f56931f7d0df" and "18ec014f0ba6c2cfded209c238aa98b9bd8a9685" have entirely different histories.

8 changed files with 218 additions and 370 deletions

View File

@ -14,24 +14,6 @@ $configJSON = file_get_contents(filename: $configFile);
$config = json_decode(json: $configJSON, associative: true);
// TODO make a log class
$oFile = fopen(filename: 'log.txt', mode: 'a');
$uri = parse_url(url: $_SERVER['REQUEST_URI'], component: PHP_URL_PATH);
fputs(stream: $oFile, data: $uri . PHP_EOL);
fputs(stream: $oFile, data: "here");
$uri = explode(separator: '/', string: $uri);
fclose(stream: $oFile);
if ($uri[1] !== 'api') {
$scheme = $_SERVER['REQUEST_SCHEME'];
$host = $_SERVER['SERVER_NAME'];
$header = "$scheme://$host/openapi/index.html";
header(header: "Location: $header");
exit(0);
}
// TODO only valid clients?
header(header: "Access-Control-Allow-Origin: *");
header(header: "Content-Type: application/json; charset=UTF-8");
@ -40,6 +22,19 @@ header(header: "Access-Control-Max-Age: 3600");
header(header: "Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
// TODO make a log class
$oFile = fopen(filename: 'log.txt', mode: 'a');
$uri = parse_url(url: $_SERVER['REQUEST_URI'], component: PHP_URL_PATH);
fputs(stream: $oFile, data: $uri . PHP_EOL);
fclose(stream: $oFile);
$uri = explode(separator: '/', string: $uri);
if ($uri[1] !== 'api') {
header(header: "HTTP/1.1 404 Not Found");
exit();
}
$requestMethod = $_SERVER["REQUEST_METHOD"];
try {

View File

@ -13,7 +13,6 @@ define(constant_name: 'COLOR_DEFAULT', value: "\033[39m");
use App\Entity\Domain;
use App\Entity\Nameserver;
use App\Entity\Panel;
use App\Repository\ApikeyRepository;
use App\Repository\DomainRepository;
@ -25,9 +24,6 @@ use DI\ContainerBuilder;
use DI\DependencyException;
use DI\NotFoundException;
use LucidFrame\Console\ConsoleTable;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
use UnhandledMatchError;
use function DI\autowire;
@ -40,14 +36,14 @@ if (php_sapi_name() !== 'cli') {
*/
class BindAPI
{
private Logger $log;
private ApiController $apiController;
private ApikeyRepository $apikeyRepository;
//private DatabaseConnection $databaseConnection;
private DomainController $domainController;
private DomainRepository $domainRepository;
private NameserverController $nameserverController;
private NameserverRepository $nameserverRepository;
private PanelController $panelController;
private NameserverController $nameserverController;
private CheckController $checkController;
private DomainRepository $domainRepository;
private NameserverRepository $nameserverRepository;
private ApikeyRepository $apikeyRepository;
private PanelRepository $panelRepository;
private Container $container;
@ -59,46 +55,26 @@ class BindAPI
*/
public function __construct(private array $config, private int $argumentsCount, private array $arguments)
{
$dateFormat = "Y:m:d H:i:s";
$output = "%datetime% %channel%.%level_name% %message%\n"; // %context% %extra%
$formatter = new LineFormatter(format: $output, dateFormat: $dateFormat);
$stream = new StreamHandler(stream: dirname(path: __DIR__, levels: 2) . '/bindAPI.log');
$stream->setFormatter(formatter: $formatter);
$this->log = new Logger(name: 'bindAPI');
$this->log->pushHandler(handler: $stream);
$containerBuilder = new ContainerBuilder();
$containerBuilder->addDefinitions([
DatabaseConnection::class => autowire()->constructorParameter(parameter: 'config', value: $this->config),
DomainController::class => autowire()
->constructorParameter(parameter: 'config', value: $this->config)
->constructorParameter(parameter: 'log', value: $this->log),
DomainRepository::class => autowire()
->constructorParameter(parameter: 'config', value: $this->config)
->constructorParameter(parameter: 'log', value: $this->log),
]);
$this->container = $containerBuilder->build();
$this->apiController = $this->container->get(name: ApiController::class);
//$this->databaseConnection = $this->container->get(name: DatabaseConnection::class);
$this->panelController = $this->container->get(name: PanelController::class);
$this->checkController = $this->container->get(name: CheckController::class);
$this->nameserverController = $this->container->get(name: NameserverController::class);
$this->domainController = $this->container->get(name: DomainController::class);
$this->domainRepository = $this->container->get(name: DomainRepository::class);
$this->nameserverController = $this->container->get(name: NameserverController::class);
$this->nameserverRepository = $this->container->get(name: NameserverRepository::class);
$this->panelController = $this->container->get(name: PanelController::class);
$this->panelRepository = $this->container->get(name: PanelRepository::class);
$this->apikeyRepository = $this->container->get(name: ApikeyRepository::class);
//$dotenv->required(['DB_HOST', 'DB_NAME', 'DB_USER', 'DB_PASS']);
$this->panelRepository = $this->container->get(name: PanelRepository::class);
}
function runCommand()
{
if ($this->config['debug']) {
$this->log->debug(message: "runCommand()");
}
if ($this->argumentsCount < 1) {
$this->showUsage();
exit(0);
@ -130,16 +106,12 @@ class BindAPI
*/
function showUsage(): void
{
if ($this->config['debug']) {
$this->log->debug(message: "showUsage()");
}
echo COLOR_YELLOW . 'Usage:' . PHP_EOL;
echo COLOR_DEFAULT . "\t./bin/console {options} {arguments}" . PHP_EOL . PHP_EOL;
echo COLOR_YELLOW . 'Options:' . PHP_EOL;
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_GREEN . "\t-V, --verbose\t\t" . COLOR_DEFAULT . "All :list command are auto-verbose" . PHP_EOL . PHP_EOL;
echo COLOR_YELLOW . "check" . COLOR_DEFAULT . "\t health checks the system can perform" . PHP_EOL;
echo COLOR_GREEN . "\t check:permissions" . PHP_EOL;
@ -150,26 +122,26 @@ class BindAPI
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:delete" . PHP_EOL;
echo COLOR_GREEN . "\t panels:apiping {<ID>}" . PHP_EOL;
echo COLOR_YELLOW . "nameservers" . COLOR_DEFAULT . " 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:update <ID> {name=<name>} {panel_id=<ID>} {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_DEFAULT . " domains this server is responsible for" . PHP_EOL;
echo COLOR_GREEN . "\t domains:list" . PHP_EOL;
echo COLOR_GREEN . "\t domains:create <name> {panel_id=<ID>} | {A=<IPv4>} {AAAA=<IPv6>}" . PHP_EOL;
echo COLOR_GREEN . "\t domains:update <ID> {name=<name>} {panel_id=<ID>} | {A=<IPv4>} {AAAA=<IPv6>}" . PHP_EOL;
echo COLOR_GREEN . "\t domains:create <name> {A=<IPv4>} {AAAA=<IPv6>}" . PHP_EOL;
echo COLOR_GREEN . "\t domains:update <ID> {name=<name>} {A=<IPv4>} {AAAA=<IPv6>}" . PHP_EOL;
echo COLOR_GREEN . "\t domains:delete <ID>" . PHP_EOL;
echo COLOR_YELLOW . "apikeys" . COLOR_DEFAULT . "\t API keys for other nameservers" . PHP_EOL;
echo COLOR_GREEN . "\t apikeys:list" . PHP_EOL;
echo COLOR_GREEN . "\t apikeys:create {name=<name>}" . PHP_EOL;
echo COLOR_GREEN . "\t apikeys:update <ID> {name=<name>}" . PHP_EOL;
echo COLOR_GREEN . "\t apikeys:update <ID> name=<name>" . PHP_EOL;
echo COLOR_GREEN . "\t apikeys:delete <ID>" . PHP_EOL;
echo PHP_EOL . "\033[39me.g. ./bin/console apikeys:list" . PHP_EOL;
@ -177,10 +149,6 @@ class BindAPI
function handleChecks(string $subcommand)
{
if ($this->config['debug']) {
$this->log->debug(message: "handleChecks()");
}
try {
match ($subcommand) {
'permissions' => $this->handleCheckPermissions(),
@ -199,10 +167,6 @@ class BindAPI
*/
function handleCheckPermissions()
{
if ($this->config['debug']) {
$this->log->debug(message: "handleCheckPermissions()");
}
$this->domainController->checkPermissions();
}
@ -212,10 +176,6 @@ class BindAPI
*/
function handleCheckPanels()
{
if ($this->config['debug']) {
$this->log->debug(message: "handleCheckPanels()");
}
$id = intval(value: $this->arguments[1] ?? 0);
if ($id != 0) {
@ -233,22 +193,17 @@ class BindAPI
}
}
/**
* @param \App\Entity\Panel $panel
* @param array $panel
*
* @return void
*/
public function checkSinglePanel(Panel $panel): void
{
if ($this->config['debug']) {
$this->log->debug(message: "checkSinglePanel()");
}
echo COLOR_DEFAULT . 'Keyhelp-Panel: ' . COLOR_YELLOW . $panel->getName() . PHP_EOL;
if (!empty($panel->getAaaa())) {
try {
$result = $this->apiController->sendCommand(
$result = $this->checkController->sendCommand(
requestType: 'GET',
serverName: $panel->getName(),
versionIP: 6,
@ -261,7 +216,7 @@ class BindAPI
}
} else {
try {
$result = $this->apiController->sendCommand(
$result = $this->checkController->sendCommand(
requestType: 'GET',
serverName: $panel->getName(),
versionIP: 4,
@ -308,10 +263,6 @@ class BindAPI
function isValidSecondLevelDomain(string $domainName, string $panel, int $parent): bool
{
if ($this->config['debug']) {
$this->log->debug(message: "isValidSecondLevelDomain()");
}
// subdomain
if ($parent != 0) {
return false;
@ -343,10 +294,6 @@ class BindAPI
*/
function checkNS(string $domainName, $panel)
{
if ($this->config['debug']) {
$this->log->debug(message: "checkNS()");
}
try {
$nameServers = $this->nameserverRepository->findAll();
} catch (DependencyException|NotFoundException $e) {
@ -362,7 +309,7 @@ class BindAPI
}
try {
if (!empty($nameServer->getName())) {
$result = $this->apiController->sendCommand(
$result = $this->checkController->sendCommand(
requestType: 'GET',
serverName: $nameServer->getName(),
versionIP: 6,
@ -370,7 +317,7 @@ class BindAPI
command: 'domains/' . $domainName,
serverType: 'nameserver');
} else {
$result = $this->apiController->sendCommand(
$result = $this->checkController->sendCommand(
requestType: 'GET',
serverName: $nameServer->getName(),
versionIP: 4,
@ -385,7 +332,7 @@ class BindAPI
if ($result['header'] == 200) {
echo COLOR_GREEN . ' OK';
} else {
echo COLOR_RED . $result['header'] . COLOR_DEFAULT;
echo COLOR_RED . ' missing' . COLOR_DEFAULT;
$arguments = $this->parseArguments();
if (!empty($arguments['fix']) && $arguments['fix'] == 'yes') {
echo 'trying to fix …';
@ -395,7 +342,7 @@ class BindAPI
];
try {
if (!empty($nameServer['aaaa'])) {
$this->apiController->sendCommand(
$this->checkController->sendCommand(
requestType: 'POST',
serverName: $nameServer['name'],
versionIP: 6,
@ -404,7 +351,7 @@ class BindAPI
serverType: 'nameserver',
body: $body);
} else {
$this->apiController->sendCommand(
$this->checkController->sendCommand(
requestType: 'POST',
serverName: $nameServer['name'],
versionIP: 4,
@ -428,10 +375,6 @@ class BindAPI
*/
public function parseArguments(): array
{
if ($this->config['debug']) {
$this->log->debug(message: "parseArguments()");
}
$arguments = [];
foreach ($this->arguments as $argument) {
if (str_contains(haystack: $argument, needle: '=')) {
@ -451,10 +394,6 @@ class BindAPI
*/
public function handlePanels(string $subcommand): void
{
if ($this->config['debug']) {
$this->log->debug(message: "handlePanels()");
}
try {
match ($subcommand) {
'create' => $this->handlePanelsCreate(),
@ -475,10 +414,6 @@ class BindAPI
*/
function handlePanelsCreate(): void
{
if ($this->config['debug']) {
$this->log->debug(message: "handlePanelsCreate()");
}
$name = $this->arguments[1] ?? '';
if (empty($name)) {
echo 'You need to supply the panel name.' . PHP_EOL;
@ -523,10 +458,6 @@ class BindAPI
*/
function handlePanelsList(): void
{
if ($this->config['debug']) {
$this->log->debug(message: "handlePanelsList()");
}
echo 'All available panels:' . PHP_EOL;
try {
$panels = $this->panelRepository->findAll();
@ -560,17 +491,12 @@ class BindAPI
exit(0);
}
/**
* @throws \DI\DependencyException
* @throws \DI\NotFoundException
*/
function handlePanelsUpdate()
{
if ($this->config['debug']) {
$this->log->debug(message: "handlePanelsUpdate()");
}
$arguments = $this->parseArguments();
$id = $this->arguments[1] ?? 0;
@ -600,10 +526,6 @@ class BindAPI
*/
function handlePanelsDelete()
{
if ($this->config['debug']) {
$this->log->debug(message: "handlePanelsDelete()");
}
if (empty($this->arguments[1])) {
echo "You need to supply an ID." . PHP_EOL;
exit(1);
@ -628,10 +550,6 @@ class BindAPI
*/
function handleAPIPing(string $type)
{
if ($this->config['debug']) {
$this->log->debug(message: "handleApiPing()");
}
$error = false;
$id = $this->getId();
@ -726,7 +644,7 @@ class BindAPI
echo COLOR_DEFAULT . ' ' . str_pad(string: $a, length: $maxA, pad_type: STR_PAD_LEFT) . ' ';
}
try {
if ($result = $this->apiController->sendCommand(
if ($result = $this->checkController->sendCommand(
requestType: 'GET',
serverName: $server['name'],
versionIP: 4,
@ -753,7 +671,7 @@ class BindAPI
echo COLOR_DEFAULT . ' ' . str_pad(string: $aaaa, length: $maxAAAA, pad_type: STR_PAD_LEFT) . ' ';
}
try {
if ($result = $this->apiController->sendCommand(
if ($result = $this->checkController->sendCommand(
requestType: 'GET',
serverName: $server['name'],
versionIP: 6,
@ -1006,16 +924,16 @@ class BindAPI
echo "Domain: $name already exists." . PHP_EOL;
exit(1);
} else {
$result = $this->domainRepository->insert(name: $name, panelID: $panelID, a: $a, aaaa: $aaaa);
echo "Domain $name has been created with id $result" . PHP_EOL;
if (!empty($panelID)) {
if ($panel = $this->panelController->findByID(id: $panelID)) {
$a = $panel['a'];
$aaaa = $panel['aaaa'];
}
}
$domain = new Domain(name: $name, id: $panelID, panelID: $a, a: $aaaa);
$result = $this->domainRepository->insert(domain: $domain);
echo "Domain $name has been created with id $result" . PHP_EOL;
$this->domainController->createZoneFile(domain: $domain);
$this->domainController->createZoneFile(name: $name, a: $a, aaaa: $aaaa);
exit(0);
}
} catch (DependencyException|NotFoundException $e) {
@ -1045,21 +963,19 @@ class BindAPI
echo "Domain with ID : $id doesn't exist." . PHP_EOL;
exit(1);
}
if (!empty($panelID)) {
$panel = $this->panelController->findByID(id: $panelID);
$a = $panel['a'];
$aaaa = $panel['aaaa'];
}
$newDomain = new Domain(name: $name, id: $panelID, panelID: $a, a: $aaaa);
if ($this->domainRepository->update(domain: $newDomain) !== false) {
if ($this->domainRepository->update(id: $id, name: $name, panelID: $panelID, a: $a, aaaa: $aaaa) !== false) {
echo 'Domain server has been updated' . PHP_EOL;
$this->domainController->createZoneFile(domain: $domain);
if (!empty($panelID)) {
$panel = $this->panelController->findByID(id: $panelID);
$a = $panel['a'];
$aaaa = $panel['aaaa'];
}
$this->domainController->createZoneFile(name: $domain['name'], a: $a, aaaa: $aaaa);
} else {
echo 'Error while updating domain server.' . PHP_EOL;
}
}
/**
* @throws \DI\DependencyException
* @throws \DI\NotFoundException
@ -1076,22 +992,20 @@ class BindAPI
echo "Domain with ID $id not found." . PHP_EOL;
exit(1);
}
if (!$domain = $this->domainRepository->findByID(id: $id)) {
if (!$this->domainRepository->findByID(id: $id)) {
echo "There is no domain with ID $id." . PHP_EOL;
exit(1);
}
$this->domainController->deleteZone(domain: $domain);
$this->domainController->deleteZone(id: $id);
echo "The domain with ID $id has been deleted." . PHP_EOL;
}
/**
* @param string $subcommand
*
* @return void
*/
public
function handleNameservers(string $subcommand): void
public function handleNameservers(string $subcommand): void
{
try {
match ($subcommand) {
@ -1108,7 +1022,6 @@ class BindAPI
}
}
/**
* @return void
*/
@ -1143,8 +1056,7 @@ class BindAPI
echo "Nameserver: $name already exists." . PHP_EOL;
exit(1);
} else {
$nameserver = new Nameserver(name: $name, a: $a, aaaa: $aaaa, apikey: $apikey);
$result = $this->nameserverRepository->insert(nameserver: $nameserver);
$result = $this->nameserverRepository->insert(name: $name, a: $a, aaaa: $aaaa, apikey: $apikey);
echo "Nameserver $name has been created with id $result" . PHP_EOL;
exit(0);
}
@ -1154,7 +1066,6 @@ class BindAPI
}
}
/**
* @return void
*/
@ -1193,7 +1104,6 @@ class BindAPI
exit(0);
}
/**
* @throws \DI\DependencyException
* @throws \DI\NotFoundException
@ -1223,7 +1133,6 @@ class BindAPI
}
}
/**
* @throws \DI\DependencyException
* @throws \DI\NotFoundException

View File

@ -2,10 +2,8 @@
namespace App\Controller;
use App\Entity\Domain;
use App\Repository\DomainRepository;
use App\Repository\NameserverRepository;
use Monolog\Logger;
error_reporting(error_level: E_ALL);
@ -21,13 +19,8 @@ class DomainController
private string $namedConfLocalFile;
private string $zoneCachePath;
public function __construct(private NameserverRepository $nameserverRepository, private ApiController $checkController, private DomainRepository $domainRepository, private array $config, private Logger $log)
public function __construct(private NameserverRepository $nameserverRepository, private CheckController $checkController, private DomainRepository $domainRepository)
{
if ($this->config['debug']) {
$this->log->debug(message: "__construct()");
}
$this->localZoneFile = '/etc/bind/local.zones';
$this->localZonesDir = '/etc/bind/zones/';
$this->namedConfLocalFile = '/etc/bind/named.conf.local';
@ -60,10 +53,6 @@ class DomainController
function createIncludeFile()
{
if ($this->config['debug']) {
$this->log->debug(message: "createIncludeFile()");
}
$domains = $this->domainRepository->findAll();
$oFile = fopen(filename: $this->localZoneFile, mode: 'w');
@ -74,55 +63,69 @@ class DomainController
}
function deleteOnNameservers(Domain $domain)
function delete(int $id)
{
if ($this->config['debug']) {
$this->log->debug(message: "deleteOnNameserver()");
if ($domain = $this->domainRepository->findByID(id: $id)) {
$this->domainRepository->delete(id: $id);
$zoneFile = $this->localZonesDir . $domain['name'];
print($zoneFile . PHP_EOL);
if (file_exists(filename: $this->localZonesDir . $domain['name'])) {
print("file exists");
unlink(filename: $zoneFile);
$this->createIncludeFile();
}
}
$this->deleteOnNameservers(id: $id);
}
function deleteOnNameservers(int $id)
{
$nameservers = $this->nameserverRepository->findAll();
foreach ($nameservers as $nameserver) {
echo($nameserver['name']);
$body = [
'name' => $domain->getName()
'id' => $id
];
if (!empty($nameserver->getAaaa())) {
$this->checkController->sendCommand(requestType: 'DELETE', serverName: $nameserver->getName(), versionIP: 6, apiKey: $nameserver->getApikey(), command: 'delete', serverType: 'nameserver', body: $body);
if (!empty($nameserver['aaaa'])) {
$this->checkController->sendCommand(requestType: 'DELETE', serverName: $nameserver['name'], versionIP: 6, apiKey: $nameserver['apikey'], command: 'delete', serverType: 'nameserver', body: $body);
} else {
$this->checkController->sendCommand(requestType: 'DELETE', serverName: $nameserver->getName(), versionIP: 4, apiKey: $nameserver->getApikey(), command: 'delete', serverType: 'nameserver', body: $body);
$this->checkController->sendCommand(requestType: 'DELETE', serverName: $nameserver['name'], versionIP: 4, apiKey: $nameserver['apikey'], command: 'delete', serverType: 'nameserver', body: $body);
}
}
}
/**
* @param \App\Entity\Domain $domain
* @param int $id
*
* @return void
*/
function deleteZone(Domain $domain)
function deleteZone(int $id)
{
if ($this->config['debug']) {
$this->log->debug(message: "deleteZone()");
if ($domain = $this->domainRepository->findByID(id: $id)) {
$zoneFile = $this->localZonesDir . $domain['name'];
print($zoneFile . PHP_EOL);
if (file_exists(filename: $this->localZonesDir . $domain['name'])) {
print("file exists");
unlink(filename: $zoneFile);
$this->createIncludeFile();
}
}
$zoneFile = $this->localZonesDir . $domain->getName();
if (file_exists(filename: "$zoneFile")) {
unlink(filename: $zoneFile);
}
$this->createIncludeFile();
$this->deleteOnNameservers(domain: $domain);
$this->deleteOnNameservers(id: $id);
$this->domainRepository->delete(id: $id);
}
/**
* @return void
*/
function checkPermissions(): void
{
if ($this->config['debug']) {
$this->log->debug(message: "checkPermissions()");
}
echo 'Checking permission:' . PHP_EOL . PHP_EOL;
$uid = posix_geteuid();
print("UID:\t$uid" . PHP_EOL);
@ -170,7 +173,6 @@ class DomainController
*/
function checkDomains(): array|bool
{
return true;
/*
$domains = $this->findAll();
@ -211,33 +213,28 @@ class DomainController
/**
* @param \App\Entity\Domain $domain
* @param mixed $name
* @param mixed $a
* @param mixed $aaaa
*
* @return void
*/
public function createZoneFile(Domain $domain): void
public function createZoneFile(string $name, string $a, string $aaaa): void
{
if ($this->config['debug']) {
$domainName = $domain->getName();
$this->log->debug(message: "createZoneFile($domainName)");
}
if ($zonefile = fopen(filename: $this->localZonesDir . $domain->getName(), mode: 'w')) {
fputs(stream: $zonefile, data: 'zone \"' . $domain->getA() . '"' . ' IN {' . PHP_EOL);
if ($zonefile = fopen(filename: $this->localZonesDir . $name, mode: 'w')) {
fputs(stream: $zonefile, data: "zone \"$name\" IN {" . PHP_EOL);
fputs(stream: $zonefile, data: "\ttype slave;" . PHP_EOL);
fputs(stream: $zonefile, data: "\tfile \"" . $this->zoneCachePath . $domain->getName() . '.db";' . PHP_EOL);
fputs(stream: $zonefile, data: "\tfile \"" . $this->zoneCachePath . $name . '.db";' . PHP_EOL);
fputs(stream: $zonefile, data: "\tmasters {" . PHP_EOL);
if (!empty($a)) {
fputs(stream: $zonefile, data: "\t\t" . $domain->getA() . ';' . PHP_EOL);
fputs(stream: $zonefile, data: "\t\t$a;" . PHP_EOL);
}
if (!empty($aaaa)) {
fputs(stream: $zonefile, data: "\t\t" . $domain->getAaaa() . ';' . PHP_EOL);
fputs(stream: $zonefile, data: "\t\t$aaaa;" . PHP_EOL);
}
fputs(stream: $zonefile, data: "\t};" . PHP_EOL);
fputs(stream: $zonefile, data: "};" . PHP_EOL);
}
$this->createIncludeFile();
// TODO add on nameservers
}
}

View File

@ -4,11 +4,12 @@ namespace App\Controller;
error_reporting(error_level: E_ALL);
use App\Entity\Domain;
use App\Repository\ApikeyRepository;
use App\Repository\DomainRepository;
use DI\Container;
use DI\ContainerBuilder;
use OpenApi\Annotations\ServerVariable;
use OpenApi\Annotations\Tag;
use OpenApi\Generator;
use UnhandledMatchError;
use function DI\autowire;
@ -17,32 +18,7 @@ use OpenApi\Attributes as OAT;
/**
*
*/
#[OAT\Info(version: '0.0.1', title: 'bindAPI')]
#[OAT\Server(
url: "{schema}://{hostname}/api",
description: "The bindAPI URL.",
variables: [
new OAT\ServerVariable(
serverVariable: "schema",
default: "https",
enum: ["https", "http"]
),
new OAT\ServerVariable(
serverVariable: "hostname",
default: "ns2.24unix.net",
)
]
)]
#[OAT\Tag(
name: "Server"
)]
#[OAT\SecurityScheme(
securityScheme: "Authorization",
type: "apiKey",
description: "description",
name: "X-API-Key",
in: "header"
)]
#[OAT\Info(version: '0.0.1', title: 'bindAPI' )]
class RequestController
{
//private DatabaseConnection $databaseConnection;
@ -76,55 +52,11 @@ class RequestController
}
/**
* @return void
*/
#[OAT\Get(
path: '/domains',
operationId: 'getAllDomains',
description: 'Returns a list of all domains on this server.',
summary: 'Listing all domains.',
// security: [
// 'Authorization' => [
//
// "read:api"
// ]
// ],
servers: [],
tags: ['Domains'],
responses: [
new OAT\Response(
response: 200,
description: 'OK'
),
new OAT\Response(
response: 401,
description: 'API key is missing or invalid.'
),
new OAT\Response(
response: 404,
description: 'Domain not found.'
)]
)]
public function handleAllDomainsGetRequest(): void
{
$domains = $this->domainRepository->findAll();
$resultDomain = [];
foreach ($domains as $singleDomain) {
$domain = [
'id' => $singleDomain->getId(),
'name' => $singleDomain->getName(),
'panel_id' => $singleDomain->getPanelId(),
'a' => $singleDomain->getA(),
'aaaa' => $singleDomain->getAaaa()
];
$resultDomain[] = $domain;
}
$this->result = $resultDomain;
}
/**
* @OA\Server(
* url = "https://ns2.24unix.net/api"
* )
* @OA\Tag(name = "Server")
* @OA\Get(
* path = "/ping",
@ -138,7 +70,61 @@ class RequestController
* }
* )
*
* @OA\SecurityScheme (name="bindAPISecurity",
* type="apiKey",
* description="description",
* name="X-API-Key",
* in="header",
* securityScheme="Authorization"
*
* )
* @SwaggerDefinition(
* securityDefinition = @SecurityDefinition(
* apiKeyAuthDefinitions = {
* @ApiKeyAuthDefinition(
* key = "X-API-Key", in = ApiKeyAuthDefinition.ApiKeyLocation.HEADER, name = "X-API-KEY"
* )
* }
* )
* )
* @OA\Tag(name = "Domains")
* @OA\Get(
* path="/domains",
* summary="Listing all domains.",
* description="desc",
* tags={"Domains"},
* @OA\Response(response="200", description="OK"),
* @OA\Response(response = "401", description = "API key is missing or invalid."),
* @OA\Response(response="404", description="Domain not found."),
* security={
* {"Authorization":{"read":"write"}}
* }
* )
* @OA\Post(
* path="/domains",
* summary="Create a domain.",
* description="Creates a new domain.",
* tags={"Domains"},
* @OA\Response(response="201", description="Created"),
* @OA\Response(response = "400", description = "Invalid request body."),
* @OA\Response(response = "401", description = "API key is missing or invalid."),
* @OA\Response(response="404", description="Domain not found."),
* security={
* {"Authorization":{"read":"write"}}
* }
* )
* @OA\Get(
* path="/domains/{name}",
* summary="Returns a single domain.",
* description="Returns information of a single domain specified by its domain name.",
* tags={"Domains"},
* @OA\Response(response="200", description="OK"),
* @OA\Response(response = "401", description = "API key is missing or invalid."),
* @OA\Response(response="404", description="Domain not found."),
* security={
* {"Authorization":{"read":"write"}}
* }
* )
* @OA\Put(
* path="/domains/{name}",
* summary="Updates a domain.",
@ -163,35 +149,9 @@ class RequestController
* {"Authorization":{"read":"write"}}
* }
* )
*
* @return void
*/
#[OAT\Get(
path: '/domains/{name}',
operationId: 'getSingleDomain',
description: 'Returns information of a single domain specified by its domain name.',
summary: 'Returns a single domain.',
security: [
],
tags: ['Domains'],
parameters: [
new OAT\Parameter(name: 'name', in: 'path', required: true, schema: new OAT\Schema(type: 'string')),
],
responses: [
new OAT\Response(
response: 200,
description: 'OK'
),
new OAT\Response(
response: 401,
description: 'API key is missing or invalid.'
),
new OAT\Response(
response: 404,
description: 'Domain not found.'
)]
)]
public function processRequest()
{
$command = $this->uri[2];
@ -293,7 +253,19 @@ class RequestController
public function handleDomainGetRequest(): void
{
if (empty($this->uri[3])) {
$this->handleAllDomainsGetRequest();
$domains = $this->domainRepository->findAll();
$resultDomain = [];
foreach ($domains as $singleDomain) {
$domain = [
'id' => $singleDomain->getId(),
'name' => $singleDomain->getName(),
'panel_id' => $singleDomain->getPanelId(),
'a' => $singleDomain->getA(),
'aaaa' => $singleDomain->getAaaa()
];
$resultDomain[] = $domain;
}
$this->result = $resultDomain;
} else {
if ($result = $this->domainRepository->findByName(name: $this->uri[3])) {
$domain = [
@ -316,7 +288,8 @@ class RequestController
/**
* @return void
*/
public function handleDomainPostRequest(): void
public
function handleDomainPostRequest(): void
{
$name = $_POST['name'] ?? '';
$panelID = intval(value: $_POST['panel_id'] ?? 0);
@ -337,8 +310,7 @@ class RequestController
$this->status = "400 Bad request";
$this->message = "Domain: $name already exists.";
} else {
$domain = new Domain(name: $name, panelID: $panelID, a: $a, aaaa: $aaaa);
$result = $this->domainRepository->insert(domain: $domain);
$result = $this->domainRepository->insert(name: $name, panelID: $panelID, a: $a, aaaa: $aaaa);
$this->status = "201 Created";
$this->message = $result;
}
@ -362,7 +334,7 @@ class RequestController
$put[$key] = $value;
}
$id = $put['id'] ?? 0;
$name = $put['name'] ?? '';
$name = $put['name'] ?? "";
$panelID = $put['panel_id'] ?? "";
$a = $put['a'] ?? "";
$aaaa = $put['aaaa'] ?? "";
@ -384,8 +356,7 @@ class RequestController
$this->status = "400 Bad Request";
$this->message = "At least one IP address is required.";
} else {
$domain = new Domain(name: $panelID, id: $id, panelID: $name, a: $a, aaaa: $aaaa);
$this->domainRepository->update(domain: $domain);
$this->domainRepository->update(id: $id, name: $panelID, panelID: $name, a: $a, aaaa: $aaaa);
$this->header = "201 Updated";
$this->status = "201 Updated";
$this->message = "201 Updated";
@ -418,13 +389,12 @@ class RequestController
$this->status = "400 Bad Request";
$this->message = "You need to supply an ID.";
} else {
if (!$domain = $this->domainRepository->findByID(id: $id)) {
if (!$this->domainRepository->findByID(id: $id)) {
$this->header = "400 Bad Request";
$this->status = "400 Bad Request";
$this->message = "There is no domain with ID $id.";
} else {
$this->domainRepository->delete(domain: $domain);
$this->domainRepository->delete(id: $id);
$this->header = "204 No content.";
$this->status = "204 No content.";
$this->message = "The domain $id has been deleted.";

View File

@ -2,6 +2,8 @@
namespace App\Entity;
use OpenApi\Attributes as OAT;
/**
*
*/

View File

@ -4,7 +4,6 @@ namespace App\Repository;
use App\Controller\DatabaseConnection;
use App\Entity\Domain;
use Monolog\Logger;
use PDO;
use PDOException;
@ -13,7 +12,7 @@ use PDOException;
*/
class DomainRepository
{
public function __construct(private DatabaseConnection $databaseConnection, private array $config, private Logger $log)
public function __construct(private DatabaseConnection $databaseConnection)
{}
@ -59,7 +58,6 @@ class DomainRepository
$statement->bindParam(param: ':id', var: $id);
$statement->execute();
if ($result = $statement->fetch(mode: PDO::FETCH_ASSOC)) {
return new Domain(name: $result['name'], panelID: $result['panel_id'], a: $result['a'], aaaa: $result['aaaa']);
} else {
return false;
@ -87,7 +85,7 @@ class DomainRepository
$statement->bindParam(param: ':name', var: $name);
$statement->execute();
if ($result = $statement->fetch(mode: PDO::FETCH_ASSOC)) {
return new Domain(name: $result['name'], id: $result['id'], panelID: $result['panel_id'], a: $result['a'], aaaa: $result['aaaa']);
return new Domain(name: $result['name'], panelID: $result['panel_id'], a: $result['a'], aaaa: $result['aaaa']);
} else {
return false;
@ -99,28 +97,23 @@ class DomainRepository
}
/**
* @param \App\Entity\Domain $domain
* @param String $name
* @param int $panelID
* @param String $a
* @param String $aaaa
*
* @return string|false
*/
public function insert(Domain $domain): bool|string
public function insert(string $name, int $panelID, string $a, string $aaaa): bool|string
{
if ($this->config['debug']) {
$domainName = $domain->getName();
$this->log->debug(message: "insert($domainName)");
}
print("here");
$sql = "
INSERT INTO " . DatabaseConnection::TABLE_DOMAINS . " (name, panel_id, a, aaaa)
VALUES (:name, :panel_id, :a, :aaaa)";
try {
$name = $domain->getName();
$panelID = $domain->getPanelID();
$a = $domain->getA();
$aaaa = $domain->getAaaa();
$statement = $this->databaseConnection->getConnection()->prepare(query: $sql);
$statement->bindParam(param: ':name', var: $name);
$statement->bindParam(param: ':panel_id', var: $panelID);
@ -136,18 +129,17 @@ class DomainRepository
/**
* @param \App\Entity\Domain $domain
* @param Int $id
* @param String $name
* @param int $panelID
* @param String $a
* @param String $aaaa
*
* @return false|int
*/
public function update(Domain $domain): bool|int
public function update(int $id, string $name, int $panelID, string $a, string $aaaa): bool|int
{
if ($this->config['debug']) {
$domainName = $domain->getName();
$this->log->debug(message: "update($domainName)");
}
$current = $this->findByID(id: $domain->getId());
$current = $this->findByID(id: $id);
/* doesn't work
$statement = "
@ -159,10 +151,10 @@ class DomainRepository
aaaa=COALESCE(:aaaa, aaaa)";
*/
if (empty($domain->getName())) {
if (empty($name)) {
$name = $current['name'];
}
if (empty($domain->getPanelID())) {
if (empty($panelID)) {
$panelID = $current['panel_id'];
}
$panelID = intval(value: $panelID);
@ -199,24 +191,18 @@ class DomainRepository
/**
* @param \App\Entity\Domain $domain
* @param $id
*
* @return int
*/
public function delete(Domain $domain): int
public function delete($id): int
{
if ($this->config['debug']) {
$domainName = $domain->getName();
$this->log->debug(message: "delete($domainName)");
}
$sql = "
DELETE FROM " . DatabaseConnection::TABLE_DOMAINS . "
WHERE id = :id";
try {
$statement = $this->databaseConnection->getConnection()->prepare(query: $sql);
$id = $domain->getId();
$statement->bindParam(param: 'id', var: $id);
$statement->execute();

View File

@ -13,8 +13,7 @@ use PDOException;
class NameserverRepository
{
public function __construct(private DatabaseConnection $databaseConnection)
{
}
{}
/**
@ -94,21 +93,20 @@ class NameserverRepository
/**
* @param \App\Entity\Nameserver $nameserver
* @param String $name
* @param String $a
* @param String $aaaa
* @param String $apikey
*
* @return string|false
*/
public function insert(Nameserver $nameserver): bool|string
public function insert(string $name, string $a, string $aaaa, String $apikey): bool|string
{
$sql = "
INSERT INTO " . DatabaseConnection::TABLE_NAMESERVERS . " (name, a, aaaa, apikey)
VALUES (:name, :a, :aaaa, :apikey)";
try {
$name = $nameserver->getName();
$a = $nameserver->getA();
$aaaa = $nameserver->getAaaa();
$apikey = $nameserver->getApikey();
$statement = $this->databaseConnection->getConnection()->prepare(query: $sql);
$statement->bindParam(param: ':name', var: $name);
$statement->bindParam(param: ':a', var: $a);
@ -132,7 +130,7 @@ class NameserverRepository
*
* @return false|int
*/
public function update(int $id, string $name, string $a, string $aaaa, string $apikey): bool|int
public function update(int $id, string $name, string $a, string $aaaa, String $apikey): bool|int
{
$current = $this->findByID(id: $id);
@ -212,7 +210,7 @@ class NameserverRepository
*
* @return int
*/
public function getLongestEntry(string $field): int
public function getLongestEntry(String $field): int
{
$sql = "
SELECT MAX(LENGTH(" . $field . ")) as length FROM " . DatabaseConnection::TABLE_NAMESERVERS;
@ -220,7 +218,7 @@ class NameserverRepository
try {
$statement = $this->databaseConnection->getConnection()->prepare(query: $sql);
$statement->execute();
$result = $statement->fetch();
$result = $statement->fetch();
return $result['length'];
} catch (PDOException $e) {
exit($e->getMessage());

View File

@ -26,7 +26,7 @@ class DomainRepositoryTest extends TestCase
private string $localZonesDir;
private string $namedConfLocalFile;
private Logger $log;
private $log;
/**
* @param int|string $dataName
@ -38,7 +38,7 @@ class DomainRepositoryTest extends TestCase
{
parent::__construct(name: $name, data: $data, dataName: $dataName);
$dateFormat = "Y-m-d H:i:s";
$dateFormat = "Y:m:d H:i:s";
$output = "%datetime% %channel%.%level_name% %message%\n"; // %context% %extra%
$formatter = new LineFormatter(format: $output, dateFormat: $dateFormat);
@ -61,13 +61,6 @@ class DomainRepositoryTest extends TestCase
$containerBuilder = new ContainerBuilder();
$containerBuilder->addDefinitions([
DatabaseConnection::class => autowire()->constructorParameter(parameter: 'config', value: $config),
DomainController::class => autowire()
->constructorParameter(parameter: 'config', value: $config)
->constructorParameter(parameter: 'log', value: $this->log),
DomainRepository::class => autowire()
->constructorParameter(parameter: 'config', value: $config)
->constructorParameter(parameter: 'log', value: $this->log),
]);
$this->container = $containerBuilder->build();
@ -96,9 +89,7 @@ class DomainRepositoryTest extends TestCase
$this->domainRepository->insert(domain: $domain);
$this->domainController->createZoneFile(domain: $domain);
// now get the persisted domain with id
$domainTest = $this->domainRepository->findByName(name: 'inserttest.org');
$this->assertIsNotBool(actual: $domainTest);
$this->assertEquals(expected: 'inserttest.org', actual: $domainTest->getName());
@ -120,7 +111,7 @@ class DomainRepositoryTest extends TestCase
// clean up
$this->domainRepository->delete(domain: $domainTest);
$this->domainRepository->delete(id: $domainTest->getId());
}
@ -141,7 +132,7 @@ class DomainRepositoryTest extends TestCase
// domain is valid and created
// now delete and check for cleanup
$this->domainRepository->delete(domain: $domainTest);
$this->domainRepository->delete(id: $domainTest->getId());
$this->domainController->deleteZone(domain: $domainTest);