1161 lines
35 KiB
Go
1161 lines
35 KiB
Go
package apps
|
|
|
|
import (
|
|
"archive/tar"
|
|
"archive/zip"
|
|
"bytes"
|
|
"compress/gzip"
|
|
"context"
|
|
"crypto/rand"
|
|
"crypto/sha1"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"os"
|
|
"os/exec"
|
|
"os/user"
|
|
"path/filepath"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/maspend/hostora/internal/store"
|
|
)
|
|
|
|
// Batas dan timeout unduhan.
|
|
const (
|
|
maxDownloadBytes = 500 << 20 // ~500 MB
|
|
downloadTimeout = 10 * time.Minute
|
|
checksumTimeout = 30 * time.Second
|
|
commandTimeout = 5 * time.Minute
|
|
)
|
|
|
|
// Result adalah hasil instalasi yang berhasil. Password admin dan
|
|
// password database HANYA ada di sini (ditampilkan sekali oleh
|
|
// handler) — tidak pernah ditulis ke store.
|
|
type Result struct {
|
|
Installed store.InstalledApp `json:"installed"`
|
|
AdminURL string `json:"admin_url"`
|
|
SiteURL string `json:"site_url"`
|
|
AdminUser string `json:"admin_user"`
|
|
AdminPassword string `json:"admin_password"`
|
|
DBName string `json:"db_name,omitempty"`
|
|
DBUser string `json:"db_user,omitempty"`
|
|
DBPassword string `json:"db_password,omitempty"`
|
|
Notes []string `json:"notes,omitempty"`
|
|
}
|
|
|
|
// UpdateInfo adalah hasil pengecekan update (hanya cek — eksekusi
|
|
// update BELUM didukung di v0.4.3).
|
|
type UpdateInfo struct {
|
|
UpdateAvailable bool `json:"update_available"`
|
|
Latest string `json:"latest"`
|
|
Installed string `json:"installed"`
|
|
Note string `json:"note"`
|
|
}
|
|
|
|
// markerFile adalah file penanda di document root: membuktikan root
|
|
// ini dibuat oleh installer Hostora, sehingga Delete berani
|
|
// menghapus isinya.
|
|
const markerFile = ".hostora-app.json"
|
|
|
|
type marker struct {
|
|
App string `json:"app"`
|
|
Version string `json:"version"`
|
|
SiteID string `json:"site_id"`
|
|
Domain string `json:"domain"`
|
|
Database string `json:"database,omitempty"`
|
|
InstalledAt time.Time `json:"installed_at"`
|
|
}
|
|
|
|
// CheckUpdate membandingkan versi terpasang dengan versi katalog.
|
|
// Eksekusi update TIDAK dilakukan — hanya pengecekan.
|
|
func CheckUpdate(installed store.InstalledApp) (UpdateInfo, error) {
|
|
app, ok := Find(installed.App)
|
|
if !ok {
|
|
return UpdateInfo{}, fmt.Errorf("aplikasi %q tidak dikenal di katalog", installed.App)
|
|
}
|
|
info := UpdateInfo{
|
|
Latest: app.Version,
|
|
Installed: installed.Version,
|
|
Note: "update hanya dicek, eksekusi update belum didukung",
|
|
}
|
|
if compareVersions(installed.Version, app.Version) < 0 {
|
|
info.UpdateAvailable = true
|
|
}
|
|
return info, nil
|
|
}
|
|
|
|
// Delete menghapus aplikasi terpasang dari document root situsnya.
|
|
//
|
|
// Aman: hanya berjalan bila document root berisi file penanda
|
|
// .hostora-app.json dengan slug yang cocok. Tanpa penanda, Delete
|
|
// MENOLAK — supaya tidak pernah menghapus file situs yang bukan
|
|
// dibuat installer ini. Database di-drop bila MariaDB tersedia
|
|
// (best effort — kegagalan drop tidak menggagalkan hapus).
|
|
func Delete(installed store.InstalledApp) error {
|
|
root := installed.Path
|
|
if root == "" {
|
|
return fmt.Errorf("path document root kosong — tidak bisa menghapus dengan aman")
|
|
}
|
|
m, err := readMarker(root)
|
|
if err != nil {
|
|
return fmt.Errorf("menolak menghapus %s: %v (hapus manual bila yakin)", root, err)
|
|
}
|
|
if m.App != installed.App {
|
|
return fmt.Errorf("menolak menghapus %s: penanda milik aplikasi %q, bukan %q", root, m.App, installed.App)
|
|
}
|
|
entries, err := os.ReadDir(root)
|
|
if err != nil {
|
|
return fmt.Errorf("tidak bisa membaca document root: %w", err)
|
|
}
|
|
for _, e := range entries {
|
|
_ = os.RemoveAll(filepath.Join(root, e.Name()))
|
|
}
|
|
// Placeholder supaya situs tidak menampilkan directory listing kosong.
|
|
_ = os.WriteFile(filepath.Join(root, "index.html"), []byte(fmt.Sprintf(
|
|
"<!doctype html><html lang=\"id\"><head><meta charset=\"utf-8\"><title>%s</title></head>"+
|
|
"<body><h1>%s</h1><p>Aplikasi %s telah dihapus lewat Hostora.</p></body></html>\n",
|
|
installed.Domain, installed.Domain, installed.Name)), 0o644)
|
|
if installed.Database != "" {
|
|
dropDatabaseBestEffort(installed.Database, installed.DBUser)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func readMarker(root string) (marker, error) {
|
|
var m marker
|
|
raw, err := os.ReadFile(filepath.Join(root, markerFile))
|
|
if err != nil {
|
|
return m, fmt.Errorf("file penanda %s tidak ditemukan — root ini bukan hasil instalasi Hostora", markerFile)
|
|
}
|
|
if err := json.Unmarshal(raw, &m); err != nil {
|
|
return m, fmt.Errorf("file penanda rusak: %v", err)
|
|
}
|
|
return m, nil
|
|
}
|
|
|
|
// Install memasang satu aplikasi katalog ke situs.
|
|
//
|
|
// Urutan (gagal di langkah awal = TIDAK ada file yang dibuat dan
|
|
// TIDAK ada yang dicatat — tidak ada instalasi setengah jalan):
|
|
// 1. validasi situs + document root (dibuat bila belum ada)
|
|
// 2. PHP wajib ada di PATH
|
|
// 3. aplikasi yang butuh DB wajib diberi db aktif (MariaDB); bila
|
|
// db nil → gagal dengan pesan yang jelas
|
|
// 4. unduh rilis (maks ~500 MB), verifikasi checksum bila ada,
|
|
// lalu ukuran > 0 + magic arsip
|
|
// 5. ekstrak ke document root (strip direktori teratas bila ada)
|
|
// 6. tulis konfigurasi + coba installer CLI resmi bila tersedia
|
|
// 7. tulis file penanda, atur permission/ownership
|
|
//
|
|
// adminPassword kosong → dibuat acak. Password admin dan password
|
|
// database dikembalikan di Result (tampil sekali) dan TIDAK PERNAH
|
|
// disimpan ke store.
|
|
func Install(app App, site store.Site, adminUser, adminPassword string, db *store.Database, dbPassword string) (Result, error) {
|
|
var res Result
|
|
if _, ok := Find(app.Slug); !ok {
|
|
return res, fmt.Errorf("aplikasi %q tidak dikenal di katalog", app.Slug)
|
|
}
|
|
if strings.TrimSpace(site.Domain) == "" || strings.TrimSpace(site.Root) == "" {
|
|
return res, fmt.Errorf("situs tidak valid (domain/root kosong)")
|
|
}
|
|
if strings.TrimSpace(adminUser) == "" {
|
|
adminUser = "admin"
|
|
}
|
|
if adminPassword == "" {
|
|
pw, err := randomPassword(16)
|
|
if err != nil {
|
|
return res, fmt.Errorf("gagal membuat password admin: %w", err)
|
|
}
|
|
adminPassword = pw
|
|
res.Notes = append(res.Notes, "password admin dibuat acak (ditampilkan sekali di bawah)")
|
|
}
|
|
|
|
// 1. Document root: buat bila belum ada. Tolak root yang sudah
|
|
// berisi aplikasi lain (kecuali placeholder index.html).
|
|
root := filepath.Clean(site.Root)
|
|
if err := os.MkdirAll(root, 0o755); err != nil {
|
|
return res, fmt.Errorf("tidak bisa membuat document root %s: %w", root, err)
|
|
}
|
|
if _, err := os.Stat(filepath.Join(root, markerFile)); err == nil {
|
|
return res, fmt.Errorf("situs %s sudah berisi aplikasi terpasang — hapus dulu sebelum memasang %s", site.Domain, app.Name)
|
|
}
|
|
if entries, err := os.ReadDir(root); err == nil {
|
|
for _, e := range entries {
|
|
if e.Name() != "index.html" {
|
|
return res, fmt.Errorf("document root %s tidak kosong (berisi %q) — kosongkan dulu atau pilih situs baru", root, e.Name())
|
|
}
|
|
}
|
|
}
|
|
|
|
// 2. PHP wajib ada.
|
|
phpBin, err := exec.LookPath("php")
|
|
if err != nil {
|
|
return res, fmt.Errorf("PHP belum terpasang di server — instal dulu (mis. apt install php8.3-cli php8.3-fpm, atau hostora install --with-dns/--with-mail), lalu coba lagi")
|
|
}
|
|
|
|
// 3. Database wajib untuk aplikasi yang butuh DB.
|
|
if app.NeedsDB {
|
|
if db == nil {
|
|
return res, fmt.Errorf("MariaDB belum terpasang — instal dulu atau buat database manual")
|
|
}
|
|
if db.Status != "active" {
|
|
return res, fmt.Errorf("database %s belum aktif di MariaDB (status: %s) — buat database dulu lewat tab Database", db.Name, db.Status)
|
|
}
|
|
if dbPassword == "" {
|
|
return res, fmt.Errorf("password database %s tidak tersedia — buat ulang database lewat tab Database agar password baru ditampilkan sekali", db.Name)
|
|
}
|
|
}
|
|
|
|
// 4. Unduh + verifikasi.
|
|
archive, err := download(app.DownloadURL)
|
|
if err != nil {
|
|
return res, fmt.Errorf("gagal mengunduh %s: %w", app.Name, err)
|
|
}
|
|
if err := verifyArchive(app, archive); err != nil {
|
|
return res, err
|
|
}
|
|
|
|
// 5. Ekstrak. Bila gagal di tengah jalan, bersihkan file yang
|
|
// sudah terekstrak supaya tidak tertinggal instalasi setengah jalan.
|
|
extracted, err := extract(archive, app.DownloadURL, root)
|
|
if err != nil {
|
|
cleanupExtracted(root, extracted)
|
|
return res, fmt.Errorf("gagal mengekstrak %s: %w", app.Name, err)
|
|
}
|
|
|
|
// 6. Konfigurasi + installer CLI (best effort per aplikasi).
|
|
cfg := &configCtx{
|
|
app: app, site: site, root: root, phpBin: phpBin,
|
|
adminUser: adminUser, adminPassword: adminPassword,
|
|
db: db, dbPassword: dbPassword, notes: &res.Notes,
|
|
}
|
|
if err := writeConfig(cfg); err != nil {
|
|
cleanupExtracted(root, extracted)
|
|
return res, fmt.Errorf("gagal menulis konfigurasi %s: %w", app.Name, err)
|
|
}
|
|
|
|
// 7. Penanda + permission.
|
|
mk := marker{App: app.Slug, Version: app.Version, SiteID: site.ID, Domain: site.Domain, InstalledAt: time.Now()}
|
|
if db != nil {
|
|
mk.Database = db.Name
|
|
}
|
|
raw, _ := json.MarshalIndent(mk, "", " ")
|
|
if err := os.WriteFile(filepath.Join(root, markerFile), raw, 0o644); err != nil {
|
|
cleanupExtracted(root, extracted)
|
|
return res, fmt.Errorf("gagal menulis file penanda: %w", err)
|
|
}
|
|
applyPermissions(root, app.Slug)
|
|
|
|
installed := store.InstalledApp{
|
|
ID: fmt.Sprintf("app-%d", time.Now().UnixNano()),
|
|
App: app.Slug,
|
|
Name: app.Name,
|
|
Version: app.Version,
|
|
SiteID: site.ID,
|
|
Domain: site.Domain,
|
|
AdminUser: adminUser,
|
|
AdminURL: app.AdminURL(site.Domain),
|
|
SiteURL: app.SiteURL(site.Domain),
|
|
Path: root,
|
|
InstalledAt: time.Now(),
|
|
}
|
|
if db != nil {
|
|
installed.Database = db.Name
|
|
installed.DBUser = db.User
|
|
installed.DBStatus = db.Status
|
|
}
|
|
res.Installed = installed
|
|
res.AdminURL = installed.AdminURL
|
|
res.SiteURL = installed.SiteURL
|
|
res.AdminUser = adminUser
|
|
res.AdminPassword = adminPassword
|
|
if db != nil {
|
|
res.DBName = db.Name
|
|
res.DBUser = db.User
|
|
res.DBPassword = dbPassword
|
|
}
|
|
return res, nil
|
|
}
|
|
|
|
// ---------- unduh & verifikasi ----------
|
|
|
|
func download(url string) ([]byte, error) {
|
|
ctx, cancel := context.WithTimeout(context.Background(), downloadTimeout)
|
|
defer cancel()
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
req.Header.Set("User-Agent", "Hostora/0.6.1 (App Installer)")
|
|
client := &http.Client{}
|
|
resp, err := client.Do(req)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer resp.Body.Close()
|
|
if resp.StatusCode != http.StatusOK {
|
|
return nil, fmt.Errorf("server unduhan menjawab HTTP %d untuk %s", resp.StatusCode, url)
|
|
}
|
|
data, err := io.ReadAll(io.LimitReader(resp.Body, maxDownloadBytes+1))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if len(data) > maxDownloadBytes {
|
|
return nil, fmt.Errorf("arsip lebih besar dari batas 500 MB")
|
|
}
|
|
if len(data) == 0 {
|
|
return nil, fmt.Errorf("arsip kosong")
|
|
}
|
|
return data, nil
|
|
}
|
|
|
|
// verifyArchive memeriksa checksum bila dipublikasikan, lalu selalu
|
|
// memeriksa ukuran > 0 dan magic arsip (zip "PK" / gzip 0x1f 0x8b).
|
|
func verifyArchive(app App, data []byte) error {
|
|
if app.ChecksumAlgo != "" && app.ChecksumURL != "" {
|
|
if err := verifyChecksum(app, data); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
if len(data) == 0 {
|
|
return fmt.Errorf("arsip %s kosong", app.Name)
|
|
}
|
|
if !isZip(data) && !isGzip(data) {
|
|
return fmt.Errorf("arsip %s bukan zip/tar.gz yang valid (magic tidak dikenal)", app.Name)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func isZip(data []byte) bool {
|
|
if len(data) < 4 || data[0] != 'P' || data[1] != 'K' {
|
|
return false
|
|
}
|
|
// PK\x03\x04 (local header), PK\x05\x06 (empty), PK\x07\x08 (spanned).
|
|
return data[2] == 0x03 || data[2] == 0x05 || data[2] == 0x07
|
|
}
|
|
|
|
func isGzip(data []byte) bool {
|
|
return len(data) >= 2 && data[0] == 0x1f && data[1] == 0x8b
|
|
}
|
|
|
|
// verifyChecksum mengunduh file checksum resmi dan membandingkan
|
|
// hash arsip. Ketidakcocokan = gagal total. Bila file checksum
|
|
// tidak bisa diunduh (jaringan / proyek tidak menyediakan file),
|
|
// instalasi LANJUT dengan verifikasi ukuran + magic arsip saja —
|
|
// dicatat di NOTES.md, bukan disembunyikan. Alasan: checksum
|
|
// adalah verifikasi tambahan; URL unduhan sudah HTTPS resmi.
|
|
func verifyChecksum(app App, data []byte) error {
|
|
ctx, cancel := context.WithTimeout(context.Background(), checksumTimeout)
|
|
defer cancel()
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, app.ChecksumURL, nil)
|
|
if err != nil {
|
|
return nil // tidak bisa membuat request: lanjut dengan magic saja
|
|
}
|
|
req.Header.Set("User-Agent", "Hostora/0.6.1 (App Installer)")
|
|
resp, err := http.DefaultClient.Do(req)
|
|
if err != nil || resp.StatusCode != http.StatusOK {
|
|
if resp != nil {
|
|
resp.Body.Close()
|
|
}
|
|
return nil // file checksum tidak bisa diambil: lanjut dengan magic saja
|
|
}
|
|
defer resp.Body.Close()
|
|
raw, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
want := firstHexToken(string(raw))
|
|
if want == "" {
|
|
return nil
|
|
}
|
|
var got string
|
|
switch app.ChecksumAlgo {
|
|
case "sha1":
|
|
sum := sha1.Sum(data)
|
|
got = hex.EncodeToString(sum[:])
|
|
case "sha256":
|
|
sum := sha256.Sum256(data)
|
|
got = hex.EncodeToString(sum[:])
|
|
default:
|
|
return nil
|
|
}
|
|
if !strings.EqualFold(got, want) {
|
|
return fmt.Errorf("checksum %s %s tidak cocok (ingin %s, dapat %s) — arsip mungkin rusak atau dipalsukan", app.ChecksumAlgo, app.Name, want, got)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func firstHexToken(s string) string {
|
|
for _, f := range strings.Fields(s) {
|
|
if isHex(f) && len(f) >= 32 {
|
|
return strings.ToLower(f)
|
|
}
|
|
}
|
|
return ""
|
|
}
|
|
|
|
func isHex(s string) bool {
|
|
for _, c := range s {
|
|
if !(c >= '0' && c <= '9' || c >= 'a' && c <= 'f' || c >= 'A' && c <= 'F') {
|
|
return false
|
|
}
|
|
}
|
|
return len(s) > 0
|
|
}
|
|
|
|
// ---------- ekstrak ----------
|
|
|
|
// extract mengekstrak arsip ke root dan mengembalikan daftar path
|
|
// yang dibuat (untuk cleanup bila langkah berikutnya gagal).
|
|
// Direktori teratas tunggal (mis. "wordpress/") di-strip; arsip
|
|
// yang filenya langsung di root (mis. Joomla) diekstrak apa adanya.
|
|
// Path traversal (absolut / ".." / symlink) ditolak.
|
|
func extract(data []byte, url, root string) ([]string, error) {
|
|
if isZip(data) {
|
|
return extractZip(data, root)
|
|
}
|
|
return extractTarGz(data, root)
|
|
}
|
|
|
|
func extractZip(data []byte, root string) ([]string, error) {
|
|
zr, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
names := make([]string, 0, len(zr.File))
|
|
for _, f := range zr.File {
|
|
names = append(names, f.Name)
|
|
}
|
|
strip := commonTopDir(names)
|
|
var created []string
|
|
for _, f := range zr.File {
|
|
rel := stripPrefix(f.Name, strip)
|
|
if rel == "" {
|
|
continue // direktori teratas itu sendiri
|
|
}
|
|
full, err := safeJoin(root, rel)
|
|
if err != nil {
|
|
return created, err
|
|
}
|
|
if f.FileInfo().IsDir() {
|
|
if err := os.MkdirAll(full, 0o755); err != nil {
|
|
return created, err
|
|
}
|
|
created = append(created, full)
|
|
continue
|
|
}
|
|
if err := os.MkdirAll(filepath.Dir(full), 0o755); err != nil {
|
|
return created, err
|
|
}
|
|
rc, err := f.Open()
|
|
if err != nil {
|
|
return created, err
|
|
}
|
|
w, err := os.OpenFile(full, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o644)
|
|
if err != nil {
|
|
rc.Close()
|
|
return created, err
|
|
}
|
|
_, err = io.Copy(w, rc)
|
|
rc.Close()
|
|
w.Close()
|
|
if err != nil {
|
|
return created, err
|
|
}
|
|
created = append(created, full)
|
|
}
|
|
return created, nil
|
|
}
|
|
|
|
func extractTarGz(data []byte, root string) ([]string, error) {
|
|
gz, err := gzip.NewReader(bytes.NewReader(data))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer gz.Close()
|
|
tr := tar.NewReader(gz)
|
|
var names []string
|
|
// Baca dulu semua nama untuk menghitung direktori teratas.
|
|
for {
|
|
hdr, err := tr.Next()
|
|
if err == io.EOF {
|
|
break
|
|
}
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
names = append(names, hdr.Name)
|
|
}
|
|
strip := commonTopDir(names)
|
|
var created []string
|
|
// Tar tidak bisa di-seek; baca ulang dari awal.
|
|
gz2, err := gzip.NewReader(bytes.NewReader(data))
|
|
if err != nil {
|
|
return created, err
|
|
}
|
|
defer gz2.Close()
|
|
tr2 := tar.NewReader(gz2)
|
|
for {
|
|
hdr, err := tr2.Next()
|
|
if err == io.EOF {
|
|
break
|
|
}
|
|
if err != nil {
|
|
return created, err
|
|
}
|
|
if hdr.Typeflag == tar.TypeSymlink || hdr.Typeflag == tar.TypeLink {
|
|
continue // jangan ikuti symlink dari arsip
|
|
}
|
|
rel := stripPrefix(hdr.Name, strip)
|
|
if rel == "" {
|
|
continue
|
|
}
|
|
full, err := safeJoin(root, rel)
|
|
if err != nil {
|
|
return created, err
|
|
}
|
|
switch hdr.Typeflag {
|
|
case tar.TypeDir:
|
|
if err := os.MkdirAll(full, 0o755); err != nil {
|
|
return created, err
|
|
}
|
|
created = append(created, full)
|
|
case tar.TypeReg, tar.TypeRegA:
|
|
if err := os.MkdirAll(filepath.Dir(full), 0o755); err != nil {
|
|
return created, err
|
|
}
|
|
w, err := os.OpenFile(full, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o644)
|
|
if err != nil {
|
|
return created, err
|
|
}
|
|
_, err = io.Copy(w, tr2)
|
|
w.Close()
|
|
if err != nil {
|
|
return created, err
|
|
}
|
|
created = append(created, full)
|
|
}
|
|
}
|
|
return created, nil
|
|
}
|
|
|
|
// commonTopDir mengembalikan komponen pertama bila SEMUA entri
|
|
// berbagi satu direktori teratas yang sama, "" bila tidak.
|
|
func commonTopDir(names []string) string {
|
|
var top string
|
|
for _, n := range names {
|
|
n = strings.TrimPrefix(n, "./")
|
|
parts := strings.Split(n, "/")
|
|
if len(parts) < 2 {
|
|
return "" // ada file di root arsip → jangan strip
|
|
}
|
|
if top == "" {
|
|
top = parts[0]
|
|
} else if parts[0] != top {
|
|
return ""
|
|
}
|
|
}
|
|
return top
|
|
}
|
|
|
|
func stripPrefix(name, top string) string {
|
|
if top == "" {
|
|
return strings.TrimPrefix(name, "./")
|
|
}
|
|
name = strings.TrimPrefix(name, "./")
|
|
if name == top || strings.HasPrefix(name, top+"/") {
|
|
return strings.TrimPrefix(strings.TrimPrefix(name, top), "/")
|
|
}
|
|
return name
|
|
}
|
|
|
|
// safeJoin memastikan path hasil tetap di dalam root.
|
|
func safeJoin(root, rel string) (string, error) {
|
|
rel = filepath.Clean("/" + rel)
|
|
full := filepath.Join(root, rel)
|
|
abs, err := filepath.Abs(full)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
rootAbs, err := filepath.Abs(root)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if abs != rootAbs && !strings.HasPrefix(abs, rootAbs+string(os.PathSeparator)) {
|
|
return "", fmt.Errorf("path arsip %q keluar dari document root", rel)
|
|
}
|
|
return abs, nil
|
|
}
|
|
|
|
func cleanupExtracted(root string, created []string) {
|
|
// Hapus file hasil ekstrak (terdalam dulu), lalu direktori kosong.
|
|
for i := len(created) - 1; i >= 0; i-- {
|
|
_ = os.RemoveAll(created[i])
|
|
}
|
|
}
|
|
|
|
// ---------- konfigurasi per aplikasi ----------
|
|
|
|
type configCtx struct {
|
|
app App
|
|
site store.Site
|
|
root string
|
|
phpBin string
|
|
adminUser string
|
|
adminPassword string
|
|
db *store.Database
|
|
dbPassword string
|
|
notes *[]string
|
|
}
|
|
|
|
func (c *configCtx) note(format string, args ...any) {
|
|
*c.notes = append(*c.notes, fmt.Sprintf(format, args...))
|
|
}
|
|
|
|
func writeConfig(c *configCtx) error {
|
|
switch c.app.Slug {
|
|
case "wordpress":
|
|
return writeWordPress(c)
|
|
case "joomla":
|
|
return writeJoomla(c)
|
|
case "nextcloud":
|
|
return writeNextcloud(c)
|
|
case "laravel":
|
|
return writeLaravel(c)
|
|
case "moodle":
|
|
return writeMoodle(c)
|
|
case "codeigniter":
|
|
return writeCodeIgniter(c)
|
|
default:
|
|
return fmt.Errorf("aplikasi %q belum didukung penulis konfigurasinya", c.app.Slug)
|
|
}
|
|
}
|
|
|
|
func phpQuote(s string) string {
|
|
return strings.ReplaceAll(strings.ReplaceAll(s, `\`, `\\`), `'`, `\'`)
|
|
}
|
|
|
|
func randomString(n int, alphabet string) (string, error) {
|
|
b := make([]byte, n)
|
|
if _, err := rand.Read(b); err != nil {
|
|
return "", err
|
|
}
|
|
for i := range b {
|
|
b[i] = alphabet[int(b[i])%len(alphabet)]
|
|
}
|
|
return string(b), nil
|
|
}
|
|
|
|
func randomPassword(n int) (string, error) {
|
|
const alphabet = "abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789!@#$%^&*"
|
|
return randomString(n, alphabet)
|
|
}
|
|
|
|
func randomHex(n int) (string, error) {
|
|
b := make([]byte, n)
|
|
if _, err := rand.Read(b); err != nil {
|
|
return "", err
|
|
}
|
|
return hex.EncodeToString(b), nil
|
|
}
|
|
|
|
// runCmd menjalankan perintah dengan timeout; stdout+stderr
|
|
// digabung. Kegagalan TIDAK fatal bagi pemanggil (best effort)
|
|
// kecuali pemanggil memeriksanya.
|
|
func runCmd(timeout time.Duration, dir, name string, args ...string) (string, error) {
|
|
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
|
defer cancel()
|
|
cmd := exec.CommandContext(ctx, name, args...)
|
|
cmd.Dir = dir
|
|
out, err := cmd.CombinedOutput()
|
|
return string(out), err
|
|
}
|
|
|
|
// ---------- WordPress ----------
|
|
|
|
func writeWordPress(c *configCtx) error {
|
|
salts := fetchWPSalts()
|
|
cfg := fmt.Sprintf(`<?php
|
|
// wp-config.php — dibuat oleh Hostora App Installer (v0.3.0).
|
|
define( 'DB_NAME', '%s' );
|
|
define( 'DB_USER', '%s' );
|
|
define( 'DB_PASSWORD', '%s' );
|
|
define( 'DB_HOST', 'localhost' );
|
|
define( 'DB_CHARSET', 'utf8mb4' );
|
|
define( 'DB_COLLATE', '' );
|
|
%s
|
|
$table_prefix = 'wp_';
|
|
define( 'WP_DEBUG', false );
|
|
if ( ! defined( 'ABSPATH' ) ) {
|
|
define( 'ABSPATH', __DIR__ . '/' );
|
|
}
|
|
require_once ABSPATH . 'wp-settings.php';
|
|
`,
|
|
phpQuote(c.db.Name), phpQuote(c.db.User), phpQuote(c.dbPassword), salts)
|
|
if err := os.WriteFile(filepath.Join(c.root, "wp-config.php"), []byte(cfg), 0o600); err != nil {
|
|
return err
|
|
}
|
|
// Coba buat admin lewat WP-CLI bila tersedia; bila tidak, admin
|
|
// dibuat lewat installer web /wp-admin/install.php.
|
|
if wpBin, err := exec.LookPath("wp"); err == nil {
|
|
// Argumen global WP-CLI (--path, --allow-root) harus
|
|
// mendahului subcommand.
|
|
args := []string{"--path=" + c.root}
|
|
if os.Geteuid() == 0 {
|
|
args = append(args, "--allow-root")
|
|
}
|
|
args = append(args, "core", "install",
|
|
"--url=https://"+c.site.Domain, "--title="+c.site.Domain,
|
|
"--admin_user="+c.adminUser, "--admin_password="+c.adminPassword,
|
|
"--admin_email=admin@"+c.site.Domain, "--skip-email")
|
|
if out, err := runCmd(commandTimeout, c.root, wpBin, args...); err != nil {
|
|
c.note("WP-CLI gagal membuat admin (%s) — selesaikan instalasi di %s (pakai user/password di atas)", firstLine(out), c.app.AdminURL(c.site.Domain))
|
|
} else {
|
|
c.note("admin WordPress dibuat lewat WP-CLI")
|
|
}
|
|
} else {
|
|
c.note("WP-CLI tidak ditemukan — buka %s dan selesaikan instalasi web (pakai user/password di atas)", c.app.AdminURL(c.site.Domain))
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// fetchWPSalts mengambil salts dari api.wordpress.org; gagal →
|
|
// dibuat acak lokal (format define() yang sama).
|
|
func fetchWPSalts() string {
|
|
ctx, cancel := context.WithTimeout(context.Background(), checksumTimeout)
|
|
defer cancel()
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://api.wordpress.org/secret-key/1.1/salt/", nil)
|
|
if err == nil {
|
|
resp, err := http.DefaultClient.Do(req)
|
|
if err == nil && resp.StatusCode == http.StatusOK {
|
|
raw, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
|
|
resp.Body.Close()
|
|
if err == nil && strings.Contains(string(raw), "AUTH_KEY") {
|
|
return strings.TrimSpace(string(raw))
|
|
}
|
|
} else if resp != nil {
|
|
resp.Body.Close()
|
|
}
|
|
}
|
|
// Fallback lokal.
|
|
var b strings.Builder
|
|
for _, k := range []string{"AUTH_KEY", "SECURE_AUTH_KEY", "LOGGED_IN_KEY", "NONCE_KEY", "AUTH_SALT", "SECURE_AUTH_SALT", "LOGGED_IN_SALT", "NONCE_SALT"} {
|
|
v, _ := randomString(64, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()-_=+[]{}<>?/")
|
|
fmt.Fprintf(&b, "define( '%s', '%s' );\n", k, v)
|
|
}
|
|
return b.String()
|
|
}
|
|
|
|
// ---------- Joomla ----------
|
|
|
|
func writeJoomla(c *configCtx) error {
|
|
secret, _ := randomHex(16)
|
|
for _, d := range []string{"administrator/logs", "tmp"} {
|
|
_ = os.MkdirAll(filepath.Join(c.root, d), 0o755)
|
|
}
|
|
cfg := fmt.Sprintf(`<?php
|
|
// configuration.php — dibuat oleh Hostora App Installer (v0.3.0).
|
|
// Selesaikan instalasi web di /installation, lalu hapus folder installation.
|
|
class JConfig {
|
|
public $dbtype = 'mysqli';
|
|
public $host = 'localhost';
|
|
public $user = '%s';
|
|
public $password = '%s';
|
|
public $db = '%s';
|
|
public $dbprefix = 'jos_';
|
|
public $secret = '%s';
|
|
public $sitename = '%s';
|
|
public $live_site = '';
|
|
public $log_path = '%s/administrator/logs';
|
|
public $tmp_path = '%s/tmp';
|
|
public $offline = false;
|
|
public $debug = false;
|
|
public $error_reporting = 'default';
|
|
public $session_handler = 'database';
|
|
}
|
|
`,
|
|
phpQuote(c.db.User), phpQuote(c.dbPassword), phpQuote(c.db.Name),
|
|
secret, phpQuote(c.site.Domain),
|
|
strings.ReplaceAll(c.root, `'`, `\'`), strings.ReplaceAll(c.root, `'`, `\'`))
|
|
if err := os.WriteFile(filepath.Join(c.root, "configuration.php"), []byte(cfg), 0o600); err != nil {
|
|
return err
|
|
}
|
|
c.note("Joomla: buka https://%s/installation untuk menyelesaikan instalasi web (database sudah terisi), lalu hapus folder installation", c.site.Domain)
|
|
return nil
|
|
}
|
|
|
|
// ---------- Nextcloud ----------
|
|
|
|
func writeNextcloud(c *configCtx) error {
|
|
dataDir := filepath.Join(c.root, "data")
|
|
// Coba instalasi penuh lewat occ — ini membuat admin + config.
|
|
occ := filepath.Join(c.root, "occ")
|
|
if _, err := os.Stat(occ); err == nil {
|
|
args := []string{occ, "maintenance:install",
|
|
"--database=mysql",
|
|
"--database-name=" + c.db.Name,
|
|
"--database-user=" + c.db.User,
|
|
"--database-pass=" + c.dbPassword,
|
|
"--database-host=localhost",
|
|
"--admin-user=" + c.adminUser,
|
|
"--admin-pass=" + c.adminPassword,
|
|
"--data-dir=" + dataDir}
|
|
if out, err := runCmd(commandTimeout, c.root, c.phpBin, args...); err == nil {
|
|
c.note("admin Nextcloud dibuat lewat occ maintenance:install")
|
|
return nil
|
|
} else {
|
|
c.note("occ maintenance:install gagal (%s) — config minimal ditulis, selesaikan di %s", firstLine(out), c.app.AdminURL(c.site.Domain))
|
|
}
|
|
}
|
|
// Fallback: config minimal, instalasi diselesaikan di web.
|
|
instanceID, _ := randomString(12, "abcdefghijklmnopqrstuvwxyz0123456789")
|
|
salt, _ := randomHex(16)
|
|
secret, _ := randomHex(24)
|
|
cfg := fmt.Sprintf(`<?php
|
|
// config/config.php — dibuat oleh Hostora App Installer (v0.3.0).
|
|
$CONFIG = array (
|
|
'instanceid' => 'oc%s',
|
|
'passwordsalt' => '%s',
|
|
'secret' => '%s',
|
|
'trusted_domains' => array (0 => '%s'),
|
|
'datadirectory' => '%s',
|
|
'dbtype' => 'mysql',
|
|
'version' => '35.0.3.0',
|
|
'dbname' => '%s',
|
|
'dbhost' => 'localhost',
|
|
'dbuser' => '%s',
|
|
'dbpassword' => '%s',
|
|
'dbtableprefix' => 'oc_',
|
|
'installed' => false,
|
|
);
|
|
`,
|
|
instanceID, salt, secret, phpQuote(c.site.Domain),
|
|
strings.ReplaceAll(dataDir, `'`, `\'`),
|
|
phpQuote(c.db.Name), phpQuote(c.db.User), phpQuote(c.dbPassword))
|
|
_ = os.MkdirAll(filepath.Join(c.root, "config"), 0o755)
|
|
if err := os.WriteFile(filepath.Join(c.root, "config", "config.php"), []byte(cfg), 0o600); err != nil {
|
|
return err
|
|
}
|
|
c.note("Nextcloud: buka %s dan selesaikan setup web (database sudah terisi)", c.app.AdminURL(c.site.Domain))
|
|
return nil
|
|
}
|
|
|
|
// ---------- Laravel ----------
|
|
|
|
func writeLaravel(c *configCtx) error {
|
|
keyBytes := make([]byte, 32)
|
|
if _, err := rand.Read(keyBytes); err != nil {
|
|
return err
|
|
}
|
|
// base64 standar dengan padding, format APP_KEY Laravel.
|
|
appKey := "base64:" + b64Encode(keyBytes)
|
|
env := fmt.Sprintf(`APP_NAME="%s"
|
|
APP_ENV=production
|
|
APP_DEBUG=false
|
|
APP_URL=https://%s
|
|
APP_KEY=%s
|
|
|
|
LOG_CHANNEL=stack
|
|
DB_CONNECTION=mysql
|
|
DB_HOST=127.0.0.1
|
|
DB_PORT=3306
|
|
DB_DATABASE=%s
|
|
DB_USERNAME=%s
|
|
DB_PASSWORD=%s
|
|
|
|
SESSION_DRIVER=database
|
|
CACHE_STORE=database
|
|
QUEUE_CONNECTION=database
|
|
`,
|
|
c.site.Domain, c.site.Domain, appKey,
|
|
c.dbOrEmpty("name"), c.dbOrEmpty("user"), c.dbPassword)
|
|
if err := os.WriteFile(filepath.Join(c.root, ".env"), []byte(env), 0o600); err != nil {
|
|
return err
|
|
}
|
|
// Composer install bila composer tersedia (vendor tidak ikut
|
|
// dalam skeleton zip).
|
|
if _, err := exec.LookPath("composer"); err == nil {
|
|
if out, err := runCmd(commandTimeout, c.root, "composer", "install", "--no-dev", "--no-interaction", "--prefer-dist"); err != nil {
|
|
c.note("composer install gagal (%s) — jalankan manual di document root: composer install --no-dev", firstLine(out))
|
|
} else if _, err := runCmd(commandTimeout, c.root, c.phpBin, "artisan", "migrate", "--force"); err != nil {
|
|
c.note("php artisan migrate gagal — jalankan manual bila perlu: php artisan migrate --force")
|
|
}
|
|
} else {
|
|
c.note("Composer tidak ditemukan — jalankan manual di document root: composer install --no-dev")
|
|
}
|
|
c.note("Laravel adalah framework tanpa panel admin bawaan — admin URL mengarah ke situs itu sendiri")
|
|
return nil
|
|
}
|
|
|
|
func (c *configCtx) dbOrEmpty(field string) string {
|
|
if c.db == nil {
|
|
return ""
|
|
}
|
|
if field == "name" {
|
|
return c.db.Name
|
|
}
|
|
return c.db.User
|
|
}
|
|
|
|
// ---------- Moodle ----------
|
|
|
|
func writeMoodle(c *configCtx) error {
|
|
// Data dir HARUS di luar web root.
|
|
dataDir := filepath.Join(filepath.Dir(c.root), c.site.Domain+"-moodledata")
|
|
if err := os.MkdirAll(dataDir, 0o755); err != nil {
|
|
return fmt.Errorf("tidak bisa membuat moodledata %s: %w", dataDir, err)
|
|
}
|
|
// Coba installer CLI resmi dulu — ia menulis config.php sendiri.
|
|
installer := filepath.Join(c.root, "admin", "cli", "install.php")
|
|
if _, err := os.Stat(installer); err == nil {
|
|
args := []string{installer,
|
|
"--non-interactive", "--agree-license", "--lang=id",
|
|
"--wwwroot=https://" + c.site.Domain,
|
|
"--dataroot=" + dataDir,
|
|
"--dbtype=mysqli", "--dbhost=localhost",
|
|
"--dbname=" + c.db.Name, "--dbuser=" + c.db.User, "--dbpass=" + c.dbPassword,
|
|
"--prefix=mdl_",
|
|
"--fullname=" + c.site.Domain, "--shortname=" + c.site.Domain,
|
|
"--adminuser=" + c.adminUser, "--adminpass=" + c.adminPassword,
|
|
"--adminemail=admin@" + c.site.Domain}
|
|
if out, err := runCmd(commandTimeout, c.root, c.phpBin, args...); err == nil {
|
|
c.note("admin Moodle dibuat lewat installer CLI (admin/cli/install.php)")
|
|
return nil
|
|
} else {
|
|
c.note("installer CLI Moodle gagal (%s) — config minimal ditulis, selesaikan di web", firstLine(out))
|
|
}
|
|
}
|
|
// Fallback: config.php minimal, instalasi diselesaikan di web.
|
|
cfg := fmt.Sprintf(`<?php
|
|
// config.php — dibuat oleh Hostora App Installer (v0.3.0).
|
|
unset($CFG);
|
|
global $CFG;
|
|
$CFG = new stdClass();
|
|
$CFG->dbtype = 'mysqli';
|
|
$CFG->dblibrary = 'native';
|
|
$CFG->dbhost = 'localhost';
|
|
$CFG->dbname = '%s';
|
|
$CFG->dbuser = '%s';
|
|
$CFG->dbpass = '%s';
|
|
$CFG->prefix = 'mdl_';
|
|
$CFG->dboptions = array('dbpersist' => 0, 'dbport' => 3306, 'dbsocket' => '', 'dbcollation' => 'utf8mb4_unicode_ci');
|
|
$CFG->wwwroot = 'https://%s';
|
|
$CFG->dataroot = '%s';
|
|
$CFG->admin = 'admin';
|
|
$CFG->directorypermissions = 0777;
|
|
require_once(__DIR__ . '/lib/setup.php');
|
|
`,
|
|
phpQuote(c.db.Name), phpQuote(c.db.User), phpQuote(c.dbPassword),
|
|
c.site.Domain, strings.ReplaceAll(dataDir, `'`, `\'`))
|
|
if err := os.WriteFile(filepath.Join(c.root, "config.php"), []byte(cfg), 0o600); err != nil {
|
|
return err
|
|
}
|
|
c.note("Moodle: buka https://%s dan selesaikan instalasi web (database sudah terisi)", c.site.Domain)
|
|
return nil
|
|
}
|
|
|
|
// ---------- CodeIgniter ----------
|
|
|
|
func writeCodeIgniter(c *configCtx) error {
|
|
// appstarter membawa file "env" contoh — salin ke .env.
|
|
envPath := filepath.Join(c.root, ".env")
|
|
if _, err := os.Stat(envPath); err != nil {
|
|
if src, err := os.ReadFile(filepath.Join(c.root, "env")); err == nil {
|
|
_ = os.WriteFile(envPath, src, 0o600)
|
|
}
|
|
}
|
|
raw, err := os.ReadFile(envPath)
|
|
if err != nil {
|
|
raw = []byte("CI_ENVIRONMENT = production\napp.baseURL = 'https://" + c.site.Domain + "/'\n")
|
|
}
|
|
env := string(raw)
|
|
env = setEnvLine(env, "CI_ENVIRONMENT", "production")
|
|
env = setEnvLine(env, "app.baseURL", "'https://"+c.site.Domain+"/'")
|
|
env = setEnvLine(env, "database.default.DBDriver", "MySQLi")
|
|
env = setEnvLine(env, "database.default.hostname", "localhost")
|
|
env = setEnvLine(env, "database.default.database", c.dbOrEmpty("name"))
|
|
env = setEnvLine(env, "database.default.username", c.dbOrEmpty("user"))
|
|
env = setEnvLine(env, "database.default.password", c.dbPassword)
|
|
if err := os.WriteFile(envPath, []byte(env), 0o600); err != nil {
|
|
return err
|
|
}
|
|
if _, err := exec.LookPath("composer"); err == nil {
|
|
if out, err := runCmd(commandTimeout, c.root, "composer", "install", "--no-dev", "--no-interaction", "--prefer-dist"); err != nil {
|
|
c.note("composer install gagal (%s) — jalankan manual di document root: composer install --no-dev", firstLine(out))
|
|
}
|
|
} else {
|
|
c.note("Composer tidak ditemukan — jalankan manual di document root: composer install --no-dev")
|
|
}
|
|
c.note("CodeIgniter adalah framework tanpa panel admin bawaan — admin URL mengarah ke situs itu sendiri")
|
|
return nil
|
|
}
|
|
|
|
// setEnvLine mengganti (atau menambah) satu baris "kunci = nilai"
|
|
// di file .env, termasuk baris yang masih dikomentari dengan "# ".
|
|
func setEnvLine(env, key, value string) string {
|
|
lines := strings.Split(env, "\n")
|
|
found := false
|
|
for i, ln := range lines {
|
|
trim := strings.TrimSpace(strings.TrimPrefix(strings.TrimSpace(ln), "# "))
|
|
if strings.HasPrefix(trim, key+" ") || strings.HasPrefix(trim, key+"=") {
|
|
lines[i] = key + " = " + value
|
|
found = true
|
|
}
|
|
}
|
|
if !found {
|
|
lines = append(lines, key+" = "+value)
|
|
}
|
|
return strings.Join(lines, "\n")
|
|
}
|
|
|
|
// ---------- permission & util ----------
|
|
|
|
// applyPermissions: direktori 0755, file 0644, file konfigurasi
|
|
// sensitif 0600. Bila berjalan sebagai root, coba chown ke
|
|
// www-data (best effort — gagal diabaikan).
|
|
func applyPermissions(root, slug string) {
|
|
sensitive := map[string]bool{
|
|
"wp-config.php": true, "configuration.php": true,
|
|
"config.php": true, ".env": true,
|
|
}
|
|
_ = filepath.Walk(root, func(p string, info os.FileInfo, err error) error {
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
if info.IsDir() {
|
|
_ = os.Chmod(p, 0o755)
|
|
return nil
|
|
}
|
|
if sensitive[info.Name()] || (filepath.Base(filepath.Dir(p)) == "config" && info.Name() == "config.php") {
|
|
_ = os.Chmod(p, 0o600)
|
|
} else {
|
|
_ = os.Chmod(p, 0o644)
|
|
}
|
|
return nil
|
|
})
|
|
if os.Geteuid() != 0 {
|
|
return
|
|
}
|
|
u, err := user.Lookup("www-data")
|
|
if err != nil {
|
|
return
|
|
}
|
|
uid, _ := strconv.Atoi(u.Uid)
|
|
gid, _ := strconv.Atoi(u.Gid)
|
|
_ = filepath.Walk(root, func(p string, info os.FileInfo, err error) error {
|
|
if err == nil {
|
|
_ = os.Chown(p, uid, gid)
|
|
}
|
|
return nil
|
|
})
|
|
}
|
|
|
|
// dropDatabaseBestEffort menghapus database + user-nya bila
|
|
// MariaDB/MySQL tersedia. Kegagalan diabaikan (best effort).
|
|
func dropDatabaseBestEffort(name, dbUser string) {
|
|
dbBin := ""
|
|
if _, err := exec.LookPath("mariadb"); err == nil {
|
|
dbBin = "mariadb"
|
|
} else if _, err := exec.LookPath("mysql"); err == nil {
|
|
dbBin = "mysql"
|
|
}
|
|
if dbBin == "" {
|
|
return
|
|
}
|
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
|
defer cancel()
|
|
_ = exec.CommandContext(ctx, dbBin, "-u", "root", "-e",
|
|
fmt.Sprintf("DROP DATABASE IF EXISTS `%s`; DROP USER IF EXISTS '%s'@'localhost'; FLUSH PRIVILEGES;", name, dbUser)).Run()
|
|
}
|
|
|
|
func firstLine(s string) string {
|
|
s = strings.TrimSpace(s)
|
|
if i := strings.Index(s, "\n"); i >= 0 {
|
|
s = s[:i]
|
|
}
|
|
if len(s) > 200 {
|
|
s = s[:200] + "…"
|
|
}
|
|
if s == "" {
|
|
return "tidak ada output"
|
|
}
|
|
return s
|
|
}
|
|
|
|
func b64Encode(b []byte) string {
|
|
const enc = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
|
|
var out strings.Builder
|
|
for i := 0; i < len(b); i += 3 {
|
|
var n int
|
|
rem := len(b) - i
|
|
n = int(b[i]) << 16
|
|
if rem > 1 {
|
|
n |= int(b[i+1]) << 8
|
|
}
|
|
if rem > 2 {
|
|
n |= int(b[i+2])
|
|
}
|
|
out.WriteByte(enc[(n>>18)&63])
|
|
out.WriteByte(enc[(n>>12)&63])
|
|
if rem > 1 {
|
|
out.WriteByte(enc[(n>>6)&63])
|
|
} else {
|
|
out.WriteByte('=')
|
|
}
|
|
if rem > 2 {
|
|
out.WriteByte(enc[n&63])
|
|
} else {
|
|
out.WriteByte('=')
|
|
}
|
|
}
|
|
return out.String()
|
|
}
|
|
|
|
// compareVersions membandingkan versi "a.b.c" secara numerik.
|
|
// Mengembalikan -1 / 0 / 1. Sufiks non-angka per komponen diabaikan
|
|
// (mis. "5.3.1+" == "5.3.1").
|
|
func compareVersions(a, b string) int {
|
|
pa := strings.Split(a, ".")
|
|
pb := strings.Split(b, ".")
|
|
n := len(pa)
|
|
if len(pb) > n {
|
|
n = len(pb)
|
|
}
|
|
for i := 0; i < n; i++ {
|
|
var va, vb int
|
|
if i < len(pa) {
|
|
va = leadingInt(pa[i])
|
|
}
|
|
if i < len(pb) {
|
|
vb = leadingInt(pb[i])
|
|
}
|
|
if va < vb {
|
|
return -1
|
|
}
|
|
if va > vb {
|
|
return 1
|
|
}
|
|
}
|
|
return 0
|
|
}
|
|
|
|
func leadingInt(s string) int {
|
|
digits := ""
|
|
for _, c := range s {
|
|
if c < '0' || c > '9' {
|
|
break
|
|
}
|
|
digits += string(c)
|
|
}
|
|
if digits == "" {
|
|
return 0
|
|
}
|
|
v, _ := strconv.Atoi(digits)
|
|
return v
|
|
}
|