Initial commit — migrated from GitHub (account suspended)
This commit is contained in:
commit
09d0ee68c8
65 files changed
+23255
No files matched your search
@@ -0,0 +1,401 @@
|
||||
// Package dns mengintegrasikan Hostora dengan PowerDNS (authoritative
|
||||
// server) memakai backend gsqlite3.
|
||||
//
|
||||
// Desain (v0.3):
|
||||
//
|
||||
// - Panel (store JSON) tetap sumber kebenaran (source of truth). Setiap
|
||||
// CRUD zona/record di panel lalu ditulis ke PowerDNS secara best
|
||||
// effort; bila PowerDNS tidak ada, zona tetap Backend="panel" dan
|
||||
// panel terus berfungsi normal.
|
||||
// - Backend PowerDNS adalah satu file SQLite di
|
||||
// /var/lib/hostora/pdns.sqlite3 (bisa diubah lewat Backend.DBPath).
|
||||
// Tidak ada driver sqlite Go (tanpa CGO): tulis/baca dilakukan lewat
|
||||
// CLI `sqlite3` bila ada, bila tidak lewat `python3` (modul sqlite3
|
||||
// stdlib). Bila keduanya tidak ada, operasi mengembalikan error yang
|
||||
// jelas, bukan diam-diam gagal.
|
||||
// - Bila `pdnsutil` tersedia, perintah tulis (create-zone, add-record,
|
||||
// delete-record, delete-zone) dicoba lewat pdnsutil dulu, lalu jatuh
|
||||
// ke tulis SQLite langsung bila pdnsutil gagal. MX/SRV selalu ditulis
|
||||
// langsung ke SQLite karena `pdnsutil add-record` tidak punya argumen
|
||||
// prioritas. Baca (ListRecords) memakai SQLite langsung karena output
|
||||
// `pdnsutil list-zone` adalah teks untuk manusia, bukan format mesin;
|
||||
// list-zone tetap dicoba sebagai fallback bila SQLite tidak bisa dibaca.
|
||||
//
|
||||
// Keamanan koeksistensi: Hostora TIDAK PERNAH menimpa file konfigurasi
|
||||
// PowerDNS milik panel lain. Hostora hanya menulis file SQLite-nya
|
||||
// sendiri dan /etc/powerdns/pdns.d/hostora.conf bila file itu belum ada
|
||||
// dan tidak ada konfigurasi lain yang sudah mengatur gsqlite3-database
|
||||
// (lihat WriteConfig).
|
||||
//
|
||||
// systemd-resolved dan port 53: PowerDNS harus menjadi satu-satunya yang
|
||||
// mendengarkan UDP/TCP 53. Di Ubuntu, systemd-resolved biasanya sudah
|
||||
// mengikat 127.0.0.53:53 (stub listener) sehingga pdns gagal bind
|
||||
// ("Unable to bind UDP socket to '0.0.0.0:53'"). Perintah
|
||||
// `hostora dns-setup` menangani semuanya: mematikan stub listener
|
||||
// (DNSStubListener=no + restart systemd-resolved), menulis konfigurasi
|
||||
// Hostora, membuat database, memperbaiki izin direktori data untuk
|
||||
// user pdns, lalu me-restart pdns dan memverifikasi port 53.
|
||||
//
|
||||
// Secara manual, stub bisa dimatikan dengan:
|
||||
//
|
||||
// # /etc/systemd/resolved.conf, bagian [Resolve]:
|
||||
// DNSStubListener=no
|
||||
// systemctl restart systemd-resolved
|
||||
// systemctl restart pdns
|
||||
//
|
||||
// Konfigurasi Hostora sendiri mengikat pdns ke 0.0.0.0:53
|
||||
// (local-address=0.0.0.0, local-port=53). Periksa siapa yang mendengarkan
|
||||
// port 53 dengan CheckPort53.
|
||||
package dns
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// DefaultDBPath adalah lokasi file SQLite backend gsqlite3 milik Hostora.
|
||||
const DefaultDBPath = "/var/lib/hostora/pdns.sqlite3"
|
||||
|
||||
// DefaultConfigDir adalah direktori drop-in konfigurasi PowerDNS.
|
||||
const DefaultConfigDir = "/etc/powerdns/pdns.d"
|
||||
|
||||
// DefaultConfigFile adalah file konfigurasi PowerDNS milik Hostora.
|
||||
const DefaultConfigFile = "/etc/powerdns/pdns.d/hostora.conf"
|
||||
|
||||
// InstallHint adalah perintah pemasangan PowerDNS di Ubuntu/Debian.
|
||||
// Paketnya `pdns-server` — `powerdns` TIDAK ADA di Ubuntu 24.04
|
||||
// (noble): "E: Unable to locate package powerdns".
|
||||
const InstallHint = "apt install pdns-server pdns-backend-sqlite3"
|
||||
|
||||
// Backend adalah penghubung ke PowerDNS. DBPath bisa diubah (mis. ke
|
||||
// /tmp/... untuk pengujian); kosong berarti DefaultDBPath.
|
||||
type Backend struct {
|
||||
DBPath string
|
||||
ConfigDir string // kosong berarti DefaultConfigDir
|
||||
ConfigFile string // kosong berarti DefaultConfigFile
|
||||
}
|
||||
|
||||
// Default mengembalikan Backend dengan jalur bawaan Hostora.
|
||||
func Default() *Backend {
|
||||
return &Backend{DBPath: DefaultDBPath, ConfigDir: DefaultConfigDir, ConfigFile: DefaultConfigFile}
|
||||
}
|
||||
|
||||
func (b *Backend) dbPath() string {
|
||||
if b == nil || b.DBPath == "" {
|
||||
return DefaultDBPath
|
||||
}
|
||||
return b.DBPath
|
||||
}
|
||||
|
||||
func (b *Backend) configDir() string {
|
||||
if b == nil || b.ConfigDir == "" {
|
||||
return DefaultConfigDir
|
||||
}
|
||||
return b.ConfigDir
|
||||
}
|
||||
|
||||
func (b *Backend) configPath() string {
|
||||
if b != nil && b.ConfigFile != "" {
|
||||
return b.ConfigFile
|
||||
}
|
||||
return filepath.Join(b.configDir(), "hostora.conf")
|
||||
}
|
||||
|
||||
// Status melaporkan keadaan integrasi PowerDNS di mesin ini.
|
||||
type Status struct {
|
||||
// Backend: "powerdns" (terpasang + berjalan), "terpasang" (binari
|
||||
// ada tapi pdns tidak berjalan), atau "belum-terpasang".
|
||||
Backend string `json:"backend"`
|
||||
PDNSInstalled bool `json:"pdns_installed"`
|
||||
PDNSUtilAvailable bool `json:"pdnsutil_available"`
|
||||
PDNSRunning bool `json:"pdns_running"`
|
||||
DBExists bool `json:"db_exists"`
|
||||
DBPath string `json:"db_path"`
|
||||
InstallHint string `json:"install_hint"`
|
||||
}
|
||||
|
||||
// Detect memeriksa mesin ini: keberadaan binari pdns_server/pdnsutil,
|
||||
// keberadaan file SQLite backend, dan apakah layanan pdns berjalan.
|
||||
// Tidak pernah mengklaim PowerDNS ada bila tidak ada — di mesin tanpa
|
||||
// pdns, Backend-nya "belum-terpasang".
|
||||
func Detect() Status {
|
||||
return Default().Status()
|
||||
}
|
||||
|
||||
// Status sama dengan Detect, tetapi memakai DBPath Backend ini.
|
||||
func (b *Backend) Status() Status {
|
||||
st := Status{DBPath: b.dbPath(), InstallHint: InstallHint}
|
||||
if _, err := exec.LookPath("pdns_server"); err == nil {
|
||||
st.PDNSInstalled = true
|
||||
}
|
||||
if _, err := exec.LookPath("pdnsutil"); err == nil {
|
||||
st.PDNSUtilAvailable = true
|
||||
}
|
||||
if _, err := os.Stat(b.dbPath()); err == nil {
|
||||
st.DBExists = true
|
||||
}
|
||||
st.PDNSRunning = b.isRunning()
|
||||
switch {
|
||||
case st.PDNSInstalled && st.PDNSRunning:
|
||||
st.Backend = "powerdns"
|
||||
case st.PDNSInstalled:
|
||||
st.Backend = "terpasang"
|
||||
default:
|
||||
st.Backend = "belum-terpasang"
|
||||
}
|
||||
return st
|
||||
}
|
||||
|
||||
// isRunning melaporkan apakah layanan pdns aktif (systemctl) atau ada
|
||||
// proses pdns_server yang berjalan (pgrep).
|
||||
func (b *Backend) isRunning() bool {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
defer cancel()
|
||||
if out, err := exec.CommandContext(ctx, "systemctl", "is-active", "pdns").Output(); err == nil {
|
||||
if strings.TrimSpace(string(out)) == "active" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
ctx2, cancel2 := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
defer cancel2()
|
||||
if err := exec.CommandContext(ctx2, "pgrep", "-x", "pdns_server").Run(); err == nil {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Port53Info melaporkan proses apa yang mendengarkan port 53.
|
||||
type Port53Info struct {
|
||||
Listening bool `json:"listening"`
|
||||
Listeners []string `json:"listeners"` // mis. "127.0.0.53:53/udp (systemd-resolved)"
|
||||
Detail string `json:"detail"`
|
||||
Source string `json:"source"` // "ss" atau "/proc/net/*"
|
||||
}
|
||||
|
||||
// CheckPort53 melaporkan siapa yang mendengarkan UDP/TCP 53.
|
||||
//
|
||||
// systemd-resolved dan port 53: di Ubuntu, systemd-resolved biasanya
|
||||
// sudah mengikat stub 127.0.0.53:53. PowerDNS tidak bisa bind 0.0.0.0:53
|
||||
// selama stub itu aktif. Matikan stub-nya sebelum menyalakan pdns:
|
||||
//
|
||||
// systemctl stop systemd-resolved && systemctl disable systemd-resolved
|
||||
// systemctl restart pdns
|
||||
//
|
||||
// atau pertahankan resolved tanpa stub listener:
|
||||
//
|
||||
// # /etc/systemd/resolved.conf -> [Resolve] DNSStubListener=no
|
||||
// systemctl restart systemd-resolved && systemctl restart pdns
|
||||
//
|
||||
// lalu pastikan hanya pdns yang mendengarkan :53 (cek ulang dengan
|
||||
// fungsi ini).
|
||||
func CheckPort53() Port53Info {
|
||||
if info, ok := checkPort53ViaSS(); ok {
|
||||
return info
|
||||
}
|
||||
return checkPort53ViaProc()
|
||||
}
|
||||
|
||||
func checkPort53ViaSS() (Port53Info, bool) {
|
||||
if _, err := exec.LookPath("ss"); err != nil {
|
||||
return Port53Info{}, false
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
out, err := exec.CommandContext(ctx, "ss", "-tulnp").Output()
|
||||
if err != nil {
|
||||
return Port53Info{}, false
|
||||
}
|
||||
info := Port53Info{Source: "ss", Listeners: []string{}}
|
||||
procRe := regexp.MustCompile(`users:\(\("([^"]+)"`)
|
||||
for _, line := range strings.Split(string(out), "\n") {
|
||||
f := strings.Fields(line)
|
||||
if len(f) < 5 {
|
||||
continue
|
||||
}
|
||||
local := f[4]
|
||||
// Alamat lokal berbentuk IP:port atau [IPv6]:port.
|
||||
idx := strings.LastIndex(local, ":")
|
||||
if idx < 0 || strings.TrimSpace(local[idx+1:]) != "53" {
|
||||
continue
|
||||
}
|
||||
proto := strings.ToLower(f[0])
|
||||
proc := ""
|
||||
if m := procRe.FindStringSubmatch(line); m != nil {
|
||||
proc = " (" + m[1] + ")"
|
||||
}
|
||||
info.Listeners = append(info.Listeners, local+"/"+proto+proc)
|
||||
}
|
||||
info.Listening = len(info.Listeners) > 0
|
||||
if info.Listening {
|
||||
info.Detail = "port 53 didengarkan oleh: " + strings.Join(info.Listeners, ", ")
|
||||
} else {
|
||||
info.Detail = "tidak ada proses yang mendengarkan port 53"
|
||||
}
|
||||
return info, true
|
||||
}
|
||||
|
||||
// checkPort53ViaProc membaca /proc/net/{tcp,tcp6,udp,udp6} bila `ss`
|
||||
// tidak tersedia. Alamat lokal disimpan sebagai heksadesimal.
|
||||
func checkPort53ViaProc() Port53Info {
|
||||
info := Port53Info{Source: "/proc/net/tcp,tcp6,udp,udp6", Listeners: []string{}}
|
||||
for _, entry := range []struct {
|
||||
file string
|
||||
proto string
|
||||
tcp bool
|
||||
}{
|
||||
{"/proc/net/tcp", "tcp", true},
|
||||
{"/proc/net/tcp6", "tcp", true},
|
||||
{"/proc/net/udp", "udp", false},
|
||||
{"/proc/net/udp6", "udp", false},
|
||||
} {
|
||||
raw, err := os.ReadFile(entry.file)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
for _, line := range strings.Split(string(raw), "\n")[1:] {
|
||||
f := strings.Fields(line)
|
||||
if len(f) < 4 {
|
||||
continue
|
||||
}
|
||||
// f[1] = alamat lokal "HEXIP:HEXPORT", f[3] = state.
|
||||
parts := strings.SplitN(f[1], ":", 2)
|
||||
if len(parts) != 2 {
|
||||
continue
|
||||
}
|
||||
port, err := strconv.ParseInt(parts[1], 16, 32)
|
||||
if err != nil || port != 53 {
|
||||
continue
|
||||
}
|
||||
if entry.tcp && f[3] != "0A" { // 0A = LISTEN
|
||||
continue
|
||||
}
|
||||
info.Listeners = append(info.Listeners, decodeProcAddr(parts[0])+":53/"+entry.proto+" (proses tidak diketahui — baca /proc/net)")
|
||||
}
|
||||
}
|
||||
info.Listening = len(info.Listeners) > 0
|
||||
if info.Listening {
|
||||
info.Detail = "port 53 didengarkan oleh: " + strings.Join(info.Listeners, ", ")
|
||||
} else {
|
||||
info.Detail = "tidak ada proses yang mendengarkan port 53"
|
||||
}
|
||||
return info
|
||||
}
|
||||
|
||||
// decodeProcAddr mengubah alamat heksadesimal /proc/net menjadi IP.
|
||||
// IPv4 disimpan little-endian per byte; IPv6 little-endian per grup
|
||||
// 4 byte (format kernel).
|
||||
func decodeProcAddr(hexIP string) string {
|
||||
if len(hexIP) == 8 {
|
||||
b := make([]byte, 4)
|
||||
for i := 0; i < 4; i++ {
|
||||
v, err := strconv.ParseUint(hexIP[i*2:i*2+2], 16, 8)
|
||||
if err != nil {
|
||||
return hexIP
|
||||
}
|
||||
b[3-i] = byte(v)
|
||||
}
|
||||
return fmt.Sprintf("%d.%d.%d.%d", b[0], b[1], b[2], b[3])
|
||||
}
|
||||
if len(hexIP) == 32 {
|
||||
groups := make([]string, 8)
|
||||
for i := 0; i < 8; i++ {
|
||||
// Tiap grup 32-bit dibalik per byte.
|
||||
raw := hexIP[i*8 : i*8+8]
|
||||
rev := raw[6:8] + raw[4:6] + raw[2:4] + raw[0:2]
|
||||
v, err := strconv.ParseUint(rev, 16, 32)
|
||||
if err != nil {
|
||||
return hexIP
|
||||
}
|
||||
groups[i] = strconv.FormatUint(v, 16)
|
||||
}
|
||||
return "[" + strings.Join(groups, ":") + "]"
|
||||
}
|
||||
return hexIP
|
||||
}
|
||||
|
||||
// ConfigExists melaporkan apakah file hostora.conf sudah ada
|
||||
// (dipakai `hostora dns-setup` untuk melewati WriteConfig tanpa
|
||||
// menimpa).
|
||||
func (b *Backend) ConfigExists() bool {
|
||||
_, err := os.Stat(b.configPath())
|
||||
return err == nil
|
||||
}
|
||||
|
||||
// WriteConfig menulis /etc/powerdns/pdns.d/hostora.conf dengan pengaman
|
||||
// koeksistensi:
|
||||
//
|
||||
// - Gagal bila direktori /etc/powerdns/pdns.d tidak ada (PowerDNS
|
||||
// belum dipasang — Hostora tidak membuat struktur milik paket lain).
|
||||
// - TIDAK PERNAH menimpa file hostora.conf yang sudah ada.
|
||||
// - Gagal bila ada konfigurasi PowerDNS lain (pdns.conf atau file
|
||||
// *.conf di pdns.d) yang sudah mengatur gsqlite3-database — operator
|
||||
// harus menggabungkan manual, karena menimpa bisa merusak panel lain
|
||||
// yang juga memakai PowerDNS.
|
||||
//
|
||||
// Isi yang ditulis: launch=gsqlite3 dengan database milik Hostora,
|
||||
// bind 0.0.0.0:53, DNSSEC off.
|
||||
func (b *Backend) WriteConfig() error {
|
||||
dir := b.configDir()
|
||||
st, err := os.Stat(dir)
|
||||
if err != nil || !st.IsDir() {
|
||||
return fmt.Errorf("direktori %s tidak ada — pasang PowerDNS dulu (%s)", dir, InstallHint)
|
||||
}
|
||||
cfg := b.configPath()
|
||||
if _, err := os.Stat(cfg); err == nil {
|
||||
return fmt.Errorf("file %s sudah ada — tidak ditimpa; gabungkan manual bila perlu", cfg)
|
||||
}
|
||||
// Pindai konflik: file konfigurasi mana pun yang sudah mengatur
|
||||
// gsqlite3-database berarti backend SQLite sudah dimiliki pihak lain.
|
||||
candidates := []string{"/etc/powerdns/pdns.conf"}
|
||||
matches, _ := filepath.Glob(filepath.Join(dir, "*.conf"))
|
||||
candidates = append(candidates, matches...)
|
||||
for _, f := range candidates {
|
||||
if f == cfg {
|
||||
continue
|
||||
}
|
||||
if setsGsqlite3Database(f) {
|
||||
return fmt.Errorf("konflik: %s sudah mengatur gsqlite3-database — gabungkan konfigurasi PowerDNS manual, Hostora tidak menimpa konfigurasi panel lain", f)
|
||||
}
|
||||
}
|
||||
content := `# Hostora — backend PowerDNS (gsqlite3).
|
||||
# Dibuat oleh Hostora. Jangan arahkan gsqlite3-database ke file lain
|
||||
# tanpa memindahkan juga data zona, dan jangan biarkan panel lain
|
||||
# menimpa file ini.
|
||||
launch=gsqlite3
|
||||
gsqlite3-database=` + b.dbPath() + `
|
||||
gsqlite3-dnssec=off
|
||||
local-address=0.0.0.0
|
||||
local-port=53
|
||||
`
|
||||
if err := os.WriteFile(cfg, []byte(content), 0o644); err != nil {
|
||||
return fmt.Errorf("gagal menulis %s: %w", cfg, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// setsGsqlite3Database melaporkan apakah file konfigurasi mengatur
|
||||
// gsqlite3-database (baris aktif, bukan komentar).
|
||||
func setsGsqlite3Database(path string) bool {
|
||||
raw, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
re := regexp.MustCompile(`(?m)^\s*gsqlite3-database\s*=`)
|
||||
for _, line := range strings.Split(string(raw), "\n") {
|
||||
// Buang komentar '#' (nilai gsqlite3-database tidak mengandung '#').
|
||||
if i := strings.Index(line, "#"); i >= 0 {
|
||||
line = line[:i]
|
||||
}
|
||||
if re.MatchString(line) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
Reference in new issue
Block a user