Skip to content

Commit 19766b3

Browse files
committed
Fixes for final v1.0.0
1 parent 6289eee commit 19766b3

File tree

3 files changed

+129
-186
lines changed

3 files changed

+129
-186
lines changed

env-sample

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,9 @@ MIN_TTL=86400
2525
# List of name servers (NS) for the zone. Add up to NS13 if needed.
2626
NS1=ns1.example.com.
2727
NS2=ns2.example.com.
28-
# NS3=ns3.example.com.
28+
NS3=ns3.example.com.
29+
NS4=ns4.example.com.
30+
NS5=ns5.example.com.
2931
# Continue adding NS records up to NS13, as needed...
3032

3133
# Database connection settings for the application:

helpers.php

Lines changed: 38 additions & 82 deletions
Original file line numberDiff line numberDiff line change
@@ -18,31 +18,23 @@
1818

1919
/**
2020
* Sets up and returns a Logger instance.
21-
*
22-
* @param string $logFilePath Full path to the log file.
23-
* @param string $channelName Name of the log channel (optional).
24-
* @return Logger
2521
*/
2622
function setupLogger($logFilePath, $channelName = 'app') {
27-
// Create a log channel
2823
$log = new Logger($channelName);
29-
30-
// Set up the console handler
3124
$consoleHandler = new StreamHandler('php://stdout', Logger::DEBUG);
3225
$consoleFormatter = new LineFormatter(
3326
"[%datetime%] %channel%.%level_name%: %message% %context% %extra%\n",
34-
"Y-m-d H:i:s.u", // Date format
35-
true, // Allow inline line breaks
36-
true // Ignore empty context and extra
27+
"Y-m-d H:i:s.u",
28+
true,
29+
true
3730
);
3831
$consoleHandler->setFormatter($consoleFormatter);
3932
$log->pushHandler($consoleHandler);
4033

41-
// Set up the file handler
4234
$fileHandler = new RotatingFileHandler($logFilePath, 0, Logger::DEBUG);
4335
$fileFormatter = new LineFormatter(
4436
"[%datetime%] %channel%.%level_name%: %message% %context% %extra%\n",
45-
"Y-m-d H:i:s.u" // Date format
37+
"Y-m-d H:i:s.u"
4638
);
4739
$fileHandler->setFormatter($fileFormatter);
4840
$log->pushHandler($fileHandler);
@@ -57,30 +49,24 @@ function isIpWhitelisted($ip, $pdo) {
5749
return $count > 0;
5850
}
5951

60-
// Function to update the permitted IPs from the database
6152
function updatePermittedIPs($pool, $permittedIPsTable) {
6253
$pdo = $pool->get();
6354
$query = "SELECT ip_address FROM whitelist";
6455
$stmt = $pdo->query($query);
6556
$permittedIPs = $stmt->fetchAll(PDO::FETCH_COLUMN, 0);
6657
$pool->put($pdo);
6758

68-
// Manually clear the table by removing each entry
6959
foreach ($permittedIPsTable as $key => $value) {
7060
$permittedIPsTable->del($key);
7161
}
7262

73-
// Insert new values
7463
foreach ($permittedIPs as $ip) {
7564
$permittedIPsTable->set($ip, ['ip_address' => $ip]);
7665
}
7766
}
7867

7968
/**
80-
* Load and save zone files.
81-
*
82-
* @param Badcow\DNS\Zone $zone
83-
* @throws Exception if unable to save the zone file
69+
* Save the zone file.
8470
*/
8571
function saveZone($zone) {
8672
$zoneDir = $_ENV['BIND9_ZONE_DIR'];
@@ -93,80 +79,53 @@ function saveZone($zone) {
9379
}
9480

9581
/**
96-
* Backup the configuration file before modifying.
97-
*
98-
* @param string $configFile
99-
* @throws Exception if unable to create a backup
82+
* Backup the configuration file.
10083
*/
10184
function backupConfigFile(string $configFile): void {
10285
$backupFile = $configFile . '.bak.' . date('YmdHis');
103-
10486
if (!copy($configFile, $backupFile)) {
10587
throw new Exception("Failed to create backup of $configFile");
10688
}
10789
}
10890

10991
/**
110-
* Remove a zone block from named.conf.local
111-
*
112-
* @param string $zoneName
113-
* @throws Exception if unable to modify the config file or zone block not found
92+
* Remove a zone block from named.conf.local.
11493
*/
11594
function removeZoneFromConfig(string $zoneName): void {
11695
$configFile = $_ENV['BIND9_CONF_FILE'];
117-
118-
// Backup the config file before modifying
11996
backupConfigFile($configFile);
120-
121-
// Read the current config file
12297
$configContent = file_get_contents($configFile);
12398
if ($configContent === false) {
12499
throw new Exception("Unable to read $configFile");
125100
}
126-
127-
// Define a regex pattern to match the zone block
128101
$pattern = '/zone\s+"'.preg_quote($zoneName, '/').'"\s*\{[^}]*\};\n?/i';
129-
130-
// Check if the zone block exists
131102
if (!preg_match($pattern, $configContent)) {
132103
throw new Exception("Zone block for '$zoneName' not found in $configFile");
133104
}
134-
135-
// Remove the zone block
136105
$newConfigContent = preg_replace($pattern, '', $configContent, 1);
137-
138106
if ($newConfigContent === null) {
139107
throw new Exception("Error occurred while removing the zone block");
140108
}
141-
142-
// Write the updated config back to the file
143109
if (file_put_contents($configFile, $newConfigContent, LOCK_EX) === false) {
144110
throw new Exception("Unable to write to $configFile");
145111
}
146112
}
147113

148114
/**
149-
* Append a new zone block to named.conf.local
150-
*
151-
* @param string $zoneName
152-
* @param string $zoneFilePath
153-
* @throws Exception if unable to write to the config file
115+
* Append a new zone block to named.conf.local.
154116
*/
155117
function addZoneToConfig(string $zoneName, string $zoneFilePath): void {
156118
$configFile = $_ENV['BIND9_CONF_FILE'];
157-
158-
// Backup the config file before modifying
159119
backupConfigFile($configFile);
160-
161-
// Define the zone block
162120
$zoneBlock = "\nzone \"$zoneName\" {\n type master;\n file \"$zoneFilePath\";\n};\n";
163-
164-
// Append the zone block to the config file
165121
if (file_put_contents($configFile, $zoneBlock, FILE_APPEND | LOCK_EX) === false) {
166122
throw new Exception("Unable to write to $configFile");
167123
}
168124
}
169125

126+
/**
127+
* Load a zone file.
128+
*/
170129
function loadZone($zoneName) {
171130
$zoneDir = $_ENV['BIND9_ZONE_DIR'];
172131
$zoneFile = "$zoneDir/$zoneName.zone";
@@ -178,23 +137,24 @@ function loadZone($zoneName) {
178137
return $zone;
179138
}
180139

140+
/**
141+
* Reload BIND9 configuration and notify slaves.
142+
*/
181143
function reloadBIND9() {
182-
// Reload BIND9 configuration
183144
exec('sudo rndc reload', $output, $return_var);
184145
if ($return_var !== 0) {
185146
throw new Exception("Failed to reload BIND9: " . implode("\n", $output));
186147
}
187-
188-
// Notify slave servers
189148
exec('sudo rndc notify', $notify_output, $notify_return_var);
190149
if ($notify_return_var !== 0) {
191150
throw new Exception("Failed to notify slave servers: " . implode("\n", $notify_output));
192151
}
193152
}
194153

195-
// Authentication Middleware
154+
/**
155+
* Authentication middleware.
156+
*/
196157
function authenticate($request, $pdo, $log) {
197-
// Get the token from the Authorization header
198158
$authHeader = $request->header['authorization'] ?? '';
199159
if (!$authHeader) {
200160
return false;
@@ -206,13 +166,11 @@ function authenticate($request, $pdo, $log) {
206166
}
207167

208168
$token = $authParts[1];
209-
210169
if (!$token) {
211170
return false;
212171
}
213172

214173
try {
215-
// Prepare statement to fetch session securely
216174
$stmt = $pdo->prepare('
217175
SELECT s.user_id, u.username, s.expires_at, s.ip_address, s.user_agent
218176
FROM sessions s
@@ -224,32 +182,24 @@ function authenticate($request, $pdo, $log) {
224182
$session = $stmt->fetch(PDO::FETCH_ASSOC);
225183

226184
if (!$session) {
227-
// Invalid token
228185
return false;
229186
}
230-
231-
// Check if the session has expired
232187
if (strtotime($session['expires_at']) < time()) {
233-
// Session has expired
234188
return false;
235189
}
236-
237-
// Authentication successful
238-
// Return user information (e.g., user ID and username)
239190
return [
240191
'user_id' => $session['user_id'],
241192
'username' => $session['username']
242193
];
243194
} catch (Exception $e) {
244-
// Log the exception internally without exposing details to the client
245195
$log->error('Authentication error: ' . $e->getMessage());
246196
return false;
247197
}
248198
}
249199

250200
function generateInitialSerialNumber() {
251-
$currentDate = date('Ymd'); // YYYYMMDD
252-
return $currentDate . '01'; // Initial serial number
201+
$currentDate = date('Ymd');
202+
return $currentDate . '01';
253203
}
254204

255205
function getCurrentSerialNumber($pdo, $domainName) {
@@ -267,29 +217,35 @@ function insertInitialSerialNumber($pdo, $domainName) {
267217

268218
function updateSerialNumber($pdo, $domainName) {
269219
$currentSerial = getCurrentSerialNumber($pdo, $domainName);
270-
$currentDate = date('Ymd'); // YYYYMMDD
271-
272-
// Extract date and change number (NN) from current serial number
220+
$currentDate = date('Ymd');
273221
$serialDate = substr($currentSerial, 0, 8);
274222
$changeNumber = (int)substr($currentSerial, 8, 2);
275223

276224
if ($serialDate === $currentDate) {
277-
// Increment the change number
278225
$changeNumber++;
279-
if ($changeNumber < 10) {
280-
$changeNumber = '0' . $changeNumber; // Ensure it is two digits
281-
}
226+
$changeNumber = str_pad($changeNumber, 2, '0', STR_PAD_LEFT);
282227
} else {
283-
// New date, reset change number to '01'
284228
$changeNumber = '01';
285229
}
286230

287-
// Construct new serial number
288231
$newSerial = $currentDate . $changeNumber;
289-
290-
// Update serial number in the database
291232
$stmt = $pdo->prepare('UPDATE zones SET current_soa = :serial_number WHERE domain_name = :domain_name');
292233
$stmt->execute([':serial_number' => $newSerial, ':domain_name' => $domainName]);
293-
294234
return $newSerial;
295-
}
235+
}
236+
237+
/**
238+
* Update the SOA record in the zone by updating its serial number.
239+
*/
240+
function updateZoneSoa($zone, $zoneName, $pdo) {
241+
$newSerial = updateSerialNumber($pdo, $zoneName);
242+
foreach ($zone->getResourceRecords() as $record) {
243+
if (strtoupper($record->getType()) === 'SOA') {
244+
$soaRdata = $record->getRdata();
245+
$soaRdata->setSerial($newSerial);
246+
$record->setRdata($soaRdata);
247+
break;
248+
}
249+
}
250+
saveZone($zone);
251+
}

0 commit comments

Comments
 (0)