385 lines
13 KiB
Go
385 lines
13 KiB
Go
// Package mail mengintegrasikan Hostora dengan Postfix/Dovecot nyata.
|
|
//
|
|
// Prinsip keamanan (v0.3):
|
|
// - Hostora HANYA menulis file miliknya sendiri di bawah /etc/postfix
|
|
// (virtual-*-hostora) dan /etc/dovecot/hostora-users. File milik panel
|
|
// lain (mis. GarudaPanel, yang juga memakai Postfix/Dovecot di VPS
|
|
// yang sama) TIDAK PERNAH ditimpa atau dihapus.
|
|
// - /etc/postfix/main.cf hanya ditambah (append) lewat EnsureMainCf,
|
|
// dengan backup .bak terlebih dahulu. Bila main.cf sudah memakai
|
|
// virtual map dari panel lain, EnsureMainCf menolak dan meminta
|
|
// operator menggabungkan manual — bukan menimpa.
|
|
// - /etc/dovecot/conf.d/99-hostora.conf ditulis sekali (tidak pernah
|
|
// ditimpa) lewat EnsureDovecotConfig, supaya passdb/userdb Dovecot
|
|
// membaca /etc/dovecot/hostora-users untuk login IMAP.
|
|
// - Semua pemanggilan biner eksternal (postmap, postfix reload,
|
|
// dovecot reload, doveadm pw, systemctl) memakai timeout dan
|
|
// bersifat best-effort: kegagalannya dikembalikan sebagai warning,
|
|
// bukan crash panel.
|
|
// - Tidak ada surat yang dikirim oleh package ini; Probe hanya
|
|
// berjabat tangan (EHLO/STARTTLS).
|
|
//
|
|
// Semua path produksi (/etc/postfix, /etc/dovecot, /var/vmail) hidup di
|
|
// Config dan bisa diganti — wajib untuk pengujian, karena di VM build
|
|
// Postfix/Dovecot tidak terpasang dan /etc/postfix tidak boleh ditulis
|
|
// oleh tes.
|
|
package mail
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"os"
|
|
"os/exec"
|
|
"os/user"
|
|
"path/filepath"
|
|
"regexp"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
// Status MTA yang dikembalikan Detect/Status.
|
|
const (
|
|
// StatusNotInstalled: Postfix dan Dovecot tidak ditemukan.
|
|
StatusNotInstalled = "belum-terpasang"
|
|
// StatusInstalled: biner ada, tapi layanan tidak berjalan.
|
|
StatusInstalled = "terpasang"
|
|
// StatusActive: Postfix + Dovecot berjalan (systemctl is-active).
|
|
StatusActive = "aktif"
|
|
)
|
|
|
|
// InstallHint adalah perintah instalasi di VPS (Debian/Ubuntu).
|
|
const InstallHint = "sudo apt install postfix dovecot-imapd dovecot-sieve"
|
|
|
|
// VmailUID/VmailGID adalah uid/gid pemilik Maildir virtual.
|
|
const (
|
|
VmailUID = 5000
|
|
VmailGID = 5000
|
|
VmailUser = "vmail"
|
|
)
|
|
|
|
// HeaderFile adalah komentar di atas setiap file yang dikelola Hostora.
|
|
const HeaderFile = "# Hostora — jangan edit manual, dikelola panel Hostora\n"
|
|
|
|
// ErrNoSieve dikembalikan bila Dovecot Sieve tidak tersedia; pemanggil
|
|
// harus menyimpan autoresponder di panel dengan Backend="planned-sieve".
|
|
var ErrNoSieve = errors.New("sieve tidak tersedia di server ini (dovecot-sieve belum terpasang)")
|
|
|
|
// ErrNoDoveadm dikembalikan HashPassword bila doveadm tidak ada dan
|
|
// tidak ada hash bcrypt panel yang bisa dipakai sebagai fallback.
|
|
var ErrNoDoveadm = errors.New("doveadm tidak ditemukan dan tidak ada hash bcrypt panel untuk dipakai")
|
|
|
|
// ErrConflictingSetup dikembalikan EnsureMainCf bila main.cf sudah
|
|
// memakai virtual setup dari panel lain.
|
|
var ErrConflictingSetup = errors.New("main.cf sudah memakai virtual setup lain")
|
|
|
|
// Config menampung semua path yang dipakai package ini. Field kosong
|
|
// berarti memakai default produksi (/etc/postfix, /etc/dovecot,
|
|
// /var/vmail). Tes mengisi field ini dengan direktori di /tmp.
|
|
type Config struct {
|
|
PostfixDir string // default /etc/postfix
|
|
DovecotDir string // default /etc/dovecot
|
|
VmailDir string // default /var/vmail
|
|
DovecotLibDir string // default /usr/lib/dovecot (tempat plugin sieve)
|
|
MainCfPath string // default <PostfixDir>/main.cf
|
|
DomainsFile string // default <PostfixDir>/virtual-domains-hostora
|
|
MailboxesFile string // default <PostfixDir>/virtual-mailboxes-hostora
|
|
AliasesFile string // default <PostfixDir>/virtual-aliases-hostora
|
|
PasswdFile string // default <DovecotDir>/hostora-users
|
|
VmailUID int // default 5000 (0 = default)
|
|
VmailGID int // default 5000 (0 = default)
|
|
}
|
|
|
|
// DefaultConfig mengembalikan Config dengan default produksi.
|
|
func DefaultConfig() Config { return Config{} }
|
|
|
|
func (c Config) postfixDir() string {
|
|
if c.PostfixDir != "" {
|
|
return c.PostfixDir
|
|
}
|
|
return "/etc/postfix"
|
|
}
|
|
|
|
func (c Config) dovecotDir() string {
|
|
if c.DovecotDir != "" {
|
|
return c.DovecotDir
|
|
}
|
|
return "/etc/dovecot"
|
|
}
|
|
|
|
func (c Config) vmailDir() string {
|
|
if c.VmailDir != "" {
|
|
return c.VmailDir
|
|
}
|
|
return "/var/vmail"
|
|
}
|
|
|
|
func (c Config) dovecotLibDir() string {
|
|
if c.DovecotLibDir != "" {
|
|
return c.DovecotLibDir
|
|
}
|
|
return "/usr/lib/dovecot"
|
|
}
|
|
|
|
func (c Config) mainCfPath() string {
|
|
if c.MainCfPath != "" {
|
|
return c.MainCfPath
|
|
}
|
|
return filepath.Join(c.postfixDir(), "main.cf")
|
|
}
|
|
|
|
func (c Config) domainsFile() string {
|
|
if c.DomainsFile != "" {
|
|
return c.DomainsFile
|
|
}
|
|
return filepath.Join(c.postfixDir(), "virtual-domains-hostora")
|
|
}
|
|
|
|
func (c Config) mailboxesFile() string {
|
|
if c.MailboxesFile != "" {
|
|
return c.MailboxesFile
|
|
}
|
|
return filepath.Join(c.postfixDir(), "virtual-mailboxes-hostora")
|
|
}
|
|
|
|
func (c Config) aliasesFile() string {
|
|
if c.AliasesFile != "" {
|
|
return c.AliasesFile
|
|
}
|
|
return filepath.Join(c.postfixDir(), "virtual-aliases-hostora")
|
|
}
|
|
|
|
func (c Config) passwdFile() string {
|
|
if c.PasswdFile != "" {
|
|
return c.PasswdFile
|
|
}
|
|
return filepath.Join(c.dovecotDir(), "hostora-users")
|
|
}
|
|
|
|
func (c Config) vmailUID() int {
|
|
if c.VmailUID != 0 {
|
|
return c.VmailUID
|
|
}
|
|
return VmailUID
|
|
}
|
|
|
|
func (c Config) vmailGID() int {
|
|
if c.VmailGID != 0 {
|
|
return c.VmailGID
|
|
}
|
|
return VmailGID
|
|
}
|
|
|
|
// Detection adalah hasil deteksi biner dan layanan MTA.
|
|
type Detection struct {
|
|
Postfix bool `json:"postfix"`
|
|
Dovecot bool `json:"dovecot"`
|
|
Sieve bool `json:"sieve"`
|
|
PostfixRunning bool `json:"postfix_running"`
|
|
DovecotRunning bool `json:"dovecot_running"`
|
|
Status string `json:"mta_status"` // belum-terpasang | terpasang | aktif
|
|
}
|
|
|
|
// MailStatus adalah hasil deteksi lengkap untuk endpoint /api/mail/status.
|
|
type MailStatus struct {
|
|
Detection
|
|
InstallHint string `json:"install_hint"`
|
|
MapsPresent bool `json:"maps_present"`
|
|
VmailDirPresent bool `json:"vmail_dir_present"`
|
|
DovecotConfig bool `json:"dovecot_config"` // 99-hostora.conf sudah ada
|
|
DomainsFile string `json:"domains_file"`
|
|
MailboxesFile string `json:"mailboxes_file"`
|
|
AliasesFile string `json:"aliases_file"`
|
|
PasswdFile string `json:"passwd_file"`
|
|
}
|
|
|
|
// Detect mendeteksi Postfix, Dovecot, dan Sieve (default produksi).
|
|
func Detect() Detection { return DefaultConfig().Detect() }
|
|
|
|
// Detect mendeteksi biner (postconf/postfix, dovecot/doveadm, plugin
|
|
// sieve) dan apakah layanan berjalan (systemctl is-active).
|
|
func (c Config) Detect() Detection {
|
|
d := Detection{}
|
|
if _, err := exec.LookPath("postconf"); err == nil {
|
|
d.Postfix = true
|
|
} else if _, err := exec.LookPath("postfix"); err == nil {
|
|
d.Postfix = true
|
|
}
|
|
if _, err := exec.LookPath("dovecot"); err == nil {
|
|
d.Dovecot = true
|
|
} else if _, err := exec.LookPath("doveadm"); err == nil {
|
|
d.Dovecot = true
|
|
}
|
|
d.Sieve = c.SieveAvailable()
|
|
if d.Postfix {
|
|
d.PostfixRunning = serviceActive("postfix")
|
|
}
|
|
if d.Dovecot {
|
|
d.DovecotRunning = serviceActive("dovecot")
|
|
}
|
|
switch {
|
|
case d.PostfixRunning && d.DovecotRunning:
|
|
d.Status = StatusActive
|
|
case d.Postfix || d.Dovecot:
|
|
d.Status = StatusInstalled
|
|
default:
|
|
d.Status = StatusNotInstalled
|
|
}
|
|
return d
|
|
}
|
|
|
|
// Status mengembalikan status MTA lengkap (default produksi).
|
|
func Status() MailStatus { return DefaultConfig().Status() }
|
|
|
|
// Status mengembalikan status MTA lengkap beserta keberadaan file map.
|
|
func (c Config) Status() MailStatus {
|
|
d := c.Detect()
|
|
st := MailStatus{
|
|
Detection: d,
|
|
InstallHint: InstallHint,
|
|
DomainsFile: c.domainsFile(), MailboxesFile: c.mailboxesFile(),
|
|
AliasesFile: c.aliasesFile(), PasswdFile: c.passwdFile(),
|
|
DovecotConfig: c.DovecotConfigExists(),
|
|
}
|
|
_, errD := os.Stat(c.domainsFile())
|
|
_, errM := os.Stat(c.mailboxesFile())
|
|
_, errA := os.Stat(c.aliasesFile())
|
|
st.MapsPresent = errD == nil && errM == nil && errA == nil
|
|
if _, err := os.Stat(c.vmailDir()); err == nil {
|
|
st.VmailDirPresent = true
|
|
}
|
|
return st
|
|
}
|
|
|
|
// SieveAvailable melaporkan apakah plugin Dovecot Sieve terpasang.
|
|
func SieveAvailable() bool { return DefaultConfig().SieveAvailable() }
|
|
|
|
// SieveAvailable memeriksa: biner sievec, file konfigurasi sieve di
|
|
// conf.d, atau file plugin sieve di direktori lib Dovecot.
|
|
func (c Config) SieveAvailable() bool {
|
|
if _, err := exec.LookPath("sievec"); err == nil {
|
|
return true
|
|
}
|
|
for _, p := range []string{
|
|
filepath.Join(c.dovecotDir(), "conf.d", "90-sieve.conf"),
|
|
filepath.Join(c.dovecotDir(), "conf.d", "90-sieve-extprograms.conf"),
|
|
filepath.Join(c.dovecotDir(), "conf.d", "20-managesieve.conf"),
|
|
} {
|
|
if _, err := os.Stat(p); err == nil {
|
|
return true
|
|
}
|
|
}
|
|
for _, pattern := range []string{
|
|
filepath.Join(c.dovecotLibDir(), "*sieve*"),
|
|
filepath.Join(c.dovecotLibDir(), "modules", "*sieve*"),
|
|
} {
|
|
if matches, _ := filepath.Glob(pattern); len(matches) > 0 {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// serviceActive melaporkan systemctl is-active <name> == active.
|
|
// Bila systemctl tidak ada, selalu false (bukan error).
|
|
func serviceActive(name string) bool {
|
|
if _, err := exec.LookPath("systemctl"); err != nil {
|
|
return false
|
|
}
|
|
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
|
defer cancel()
|
|
out, err := exec.CommandContext(ctx, "systemctl", "is-active", name).Output()
|
|
if err != nil {
|
|
return false
|
|
}
|
|
return strings.TrimSpace(string(out)) == "active"
|
|
}
|
|
|
|
// runTimeout menjalankan perintah dengan timeout; mengembalikan output
|
|
// gabungan. Kegagalan TIDAK boleh membuat panel crash — pemanggil
|
|
// mengubahnya menjadi warning.
|
|
func runTimeout(timeout time.Duration, name string, args ...string) (string, error) {
|
|
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
|
defer cancel()
|
|
cmd := exec.CommandContext(ctx, name, args...)
|
|
out, err := cmd.CombinedOutput()
|
|
if ctx.Err() == context.DeadlineExceeded {
|
|
return string(out), fmt.Errorf("%s: timeout %s", name, timeout)
|
|
}
|
|
return string(out), err
|
|
}
|
|
|
|
var (
|
|
localRe = regexp.MustCompile(`^[a-z0-9][a-z0-9._%+\-]*[a-z0-9]$|^[a-z0-9]$`)
|
|
domainRe = regexp.MustCompile(`^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$`)
|
|
)
|
|
|
|
// splitAddress memecah "user@domain" menjadi (user, domain) ternormalisasi.
|
|
func splitAddress(address string) (user, domain string, err error) {
|
|
address = strings.ToLower(strings.TrimSpace(address))
|
|
parts := strings.Split(address, "@")
|
|
if len(parts) != 2 || parts[0] == "" || parts[1] == "" {
|
|
return "", "", fmt.Errorf("alamat email tidak valid: %q", address)
|
|
}
|
|
if !localRe.MatchString(parts[0]) {
|
|
return "", "", fmt.Errorf("bagian lokal email tidak valid: %q", parts[0])
|
|
}
|
|
if !domainRe.MatchString(parts[1]) {
|
|
return "", "", fmt.Errorf("domain email tidak valid: %q", parts[1])
|
|
}
|
|
return parts[0], parts[1], nil
|
|
}
|
|
|
|
// validDomain melaporkan apakah domain aman dipakai sebagai komponen path.
|
|
func validDomain(domain string) bool {
|
|
return domainRe.MatchString(strings.ToLower(strings.TrimSpace(domain)))
|
|
}
|
|
|
|
// validLocal melaporkan apakah bagian lokal aman dipakai sebagai path.
|
|
func validLocal(user string) bool {
|
|
return localRe.MatchString(strings.ToLower(strings.TrimSpace(user)))
|
|
}
|
|
|
|
// writeFileAtomic menulis file secara atomik (tmp + rename) dengan
|
|
// permission yang diminta, membuat direktori induk bila perlu.
|
|
func writeFileAtomic(path string, data []byte, perm os.FileMode) error {
|
|
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
|
|
return err
|
|
}
|
|
tmp := path + ".tmp-hostora"
|
|
if err := os.WriteFile(tmp, data, perm); err != nil {
|
|
return err
|
|
}
|
|
return os.Rename(tmp, path)
|
|
}
|
|
|
|
// fixPasswdFilePerms membuat file passwd Hostora bisa dibaca proses
|
|
// auth Dovecot (yang berjalan sebagai user `dovecot`, bukan root):
|
|
// owner root, grup `dovecot`, mode 0640. Tanpa ini Dovecot gagal
|
|
// membuka file (log: "open(...) failed: Permission denied
|
|
// (euid=112(dovecot) ...)") dan login IMAP selalu "Temporary
|
|
// authentication failure" — bug yang ditemukan saat tes nyata v0.4.3
|
|
// di VPS 49.128.189.171 (file ditulis 0600 root:root).
|
|
// Bila grup `dovecot` tidak ada (Dovecot belum terpasang), perms
|
|
// dibiarkan apa adanya dan error dikembalikan supaya pemanggil bisa
|
|
// memberi warning; best-effort, jangan jadikan fatal.
|
|
func (c Config) fixPasswdFilePerms() error {
|
|
path := c.passwdFile()
|
|
grp, err := user.LookupGroup("dovecot")
|
|
if err != nil {
|
|
return fmt.Errorf("grup dovecot tidak ditemukan: %w", err)
|
|
}
|
|
gid, err := strconv.Atoi(grp.Gid)
|
|
if err != nil {
|
|
return fmt.Errorf("gid grup dovecot tidak valid: %w", err)
|
|
}
|
|
if err := os.Chown(path, -1, gid); err != nil {
|
|
return fmt.Errorf("chown %s ke grup dovecot: %w", path, err)
|
|
}
|
|
if err := os.Chmod(path, 0o640); err != nil {
|
|
return fmt.Errorf("chmod 0640 %s: %w", path, err)
|
|
}
|
|
return nil
|
|
}
|