trim($l) !== ''); if (!$nonempty) return $lines; preg_match('/^(\s*)/', reset($nonempty), $ind); $prefix = $ind[1]; foreach ($nonempty as $l) { preg_match('/^(\s*)/', $l, $m); $len = min(strlen($prefix), strlen($m[1])); while ($len > 0 && substr($prefix, 0, $len) !== substr($m[1], 0, $len)) $len--; $prefix = substr($prefix, 0, $len); } return $prefix !== '' ? array_map(fn($l) => substr($l, strlen($prefix)), $lines) : $lines; } function parseCaddyfile(string $content): array { $result = ['global' => '', 'sites' => []]; $lines = explode("\n", $content); $n = count($lines); $i = 0; while ($i < $n) { $trimmed = trim($lines[$i]); if ($trimmed === '' || str_starts_with($trimmed, '#')) { $i++; continue; } // Global options block: lone opening brace if ($trimmed === '{') { $block = []; $depth = 1; $i++; while ($i < $n && $depth > 0) { $depth += substr_count($lines[$i], '{') - substr_count($lines[$i], '}'); if ($depth > 0) $block[] = $lines[$i]; $i++; } $result['global'] = implode("\n", dedent($block)); continue; } // Site block: address(es) { if (preg_match('/^(.+?)\s*\{(.*)$/', $trimmed, $m)) { $address = trim($m[1]); $block = trim($m[2]) !== '' ? [trim($m[2])] : []; $depth = 1; $i++; while ($i < $n && $depth > 0) { $depth += substr_count($lines[$i], '{') - substr_count($lines[$i], '}'); if ($depth > 0) $block[] = $lines[$i]; $i++; } $result['sites'][] = ['address' => $address, 'body' => implode("\n", dedent($block))]; continue; } $i++; } return $result; } function buildCaddyfile(string $global, array $sites): string { $out = ''; if (trim($global) !== '') $out .= "{\n" . $global . "\n}\n\n"; foreach ($sites as $site) { $out .= trim($site['address']) . " {\n" . $site['body'] . "\n}\n\n"; } return rtrim($out) . "\n"; } function caddyLoad(string $caddyfile): array { $url = rtrim(CADDY_ADMIN_URL, '/') . '/load'; $ch = curl_init($url); curl_setopt_array($ch, [ CURLOPT_POST => true, CURLOPT_POSTFIELDS => $caddyfile, CURLOPT_HTTPHEADER => ['Content-Type: text/caddyfile'], CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 10, ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_HTTP_CODE); $err = curl_error($ch); curl_close($ch); if ($err) return ['ok' => false, 'error' => 'Cannot reach Caddy admin API: ' . $err]; if ($status === 200) return ['ok' => true]; // Try to extract a clean message from Caddy's JSON error response $decoded = json_decode($body, true); $msg = $decoded['error'] ?? trim($body) ?: "HTTP $status"; return ['ok' => false, 'error' => $msg]; } function checkUpstream(string $host, int $port): bool { $fp = @fsockopen($host, $port, $errno, $errstr, 3); if ($fp) { fclose($fp); return true; } return false; } // ─── API handlers ───────────────────────────────────────────────────────────── if (isset($_GET['action'])) { while (@ob_end_clean()); ini_set('display_errors', 0); header('Content-Type: application/json'); switch ($_GET['action']) { case 'login': $user = trim($_POST['user'] ?? ''); $pass = $_POST['pass'] ?? ''; if ($auth_enabled && $user === AUTH_USER && password_verify($pass, AUTH_PASS)) { $_SESSION['koncad_auth'] = true; echo json_encode(['ok' => true]); } else { echo json_encode(['ok' => false, 'error' => 'Invalid credentials']); } exit; case 'logout': session_destroy(); echo json_encode(['ok' => true]); exit; default: if ($auth_enabled && !$logged_in) { echo json_encode(['ok' => false, 'error' => 'Unauthorized']); exit; } } switch ($_GET['action']) { case 'check_admin': $parsed = parse_url(CADDY_ADMIN_URL); $host = $parsed['host'] ?? 'localhost'; $port = $parsed['port'] ?? 2019; $fp = @fsockopen($host, $port, $errno, $errstr, 3); if ($fp) { fclose($fp); echo json_encode(['ok' => true]); } else { echo json_encode(['ok' => false, 'error' => "Cannot reach {$host}:{$port} — {$errstr}"]); } exit; case 'load': if (CADDYFILE_IMPORT && file_exists(CADDYFILE_IMPORT)) { $raw = file_get_contents(CADDYFILE_IMPORT); } elseif (file_exists(CADDYFILE_STORE)) { $raw = file_get_contents(CADDYFILE_STORE); } else { $raw = ''; } echo json_encode(['ok' => true, 'data' => parseCaddyfile($raw)]); exit; case 'save': $input = json_decode(file_get_contents('php://input'), true); if (!$input) { echo json_encode(['ok' => false, 'error' => 'Invalid JSON']); exit; } $cf = buildCaddyfile($input['global'] ?? '', $input['sites'] ?? []); $result = caddyLoad($cf); if ($result['ok']) file_put_contents(CADDYFILE_STORE, $cf); echo json_encode($result); exit; case 'check_upstreams': $input = json_decode(file_get_contents('php://input'), true); $targets = $input['targets'] ?? []; $results = []; foreach ($targets as $t) { $host = $t['host'] ?? ''; $port = (int)($t['port'] ?? 80); if ($host === '') continue; $results[] = [ 'host' => $host, 'port' => $port, 'reachable' => checkUpstream($host, $port), ]; } echo json_encode(['ok' => true, 'results' => $results]); exit; } echo json_encode(['ok' => false, 'error' => 'Unknown action']); exit; } // ─── Login page ─────────────────────────────────────────────────────────────── if ($auth_enabled && !$logged_in): $login_error = ''; if ($_SERVER['REQUEST_METHOD'] === 'POST') { $u = trim($_POST['user'] ?? ''); $p = $_POST['pass'] ?? ''; if ($u === AUTH_USER && password_verify($p, AUTH_PASS)) { $_SESSION['koncad_auth'] = true; header('Location: /'); exit; } $login_error = 'Invalid credentials'; } ?> KonCad — Login

KonCad

KonCad

KonCad

Loading…
▶ Global Options
— required for KonCad to reach Caddy
Sites
No sites configured. Click "+ Add Site" to create one.