2
0
mirror of https://github.com/acepanel/panel.git synced 2026-02-04 03:07:20 +08:00
Files
panel/internal/data/safe.go
2026-01-23 05:44:19 +08:00

74 lines
1.5 KiB
Go

package data
import (
"context"
"fmt"
"log/slog"
"strings"
"github.com/acepanel/panel/internal/biz"
"github.com/acepanel/panel/pkg/firewall"
"github.com/acepanel/panel/pkg/os"
"github.com/acepanel/panel/pkg/shell"
)
type safeRepo struct {
ssh string
log *slog.Logger
}
func NewSafeRepo(log *slog.Logger) biz.SafeRepo {
var ssh string
if os.IsRHEL() {
ssh = "sshd"
} else {
ssh = "ssh"
}
return &safeRepo{
ssh: ssh,
log: log,
}
}
func (r *safeRepo) GetPingStatus() (bool, error) {
out, err := shell.Execf(`firewall-cmd --list-rich-rules`)
if err != nil { // 可能防火墙已关闭等
return true, nil
}
if !strings.Contains(out, `rule protocol value="icmp" drop`) {
return true, nil
}
return false, nil
}
func (r *safeRepo) UpdatePingStatus(ctx context.Context, status bool) error {
fw, err := firewall.NewFirewall().Status()
if err != nil {
return err
}
if !fw {
return fmt.Errorf("failed to update ping status: firewalld is not running")
}
if status {
_, err = shell.Execf(`firewall-cmd --permanent --remove-rich-rule='rule protocol value=icmp drop'`)
} else {
_, err = shell.Execf(`firewall-cmd --permanent --add-rich-rule='rule protocol value=icmp drop'`)
}
if err != nil {
return err
}
_, err = shell.Execf(`firewall-cmd --reload`)
if err != nil {
return err
}
// 记录日志
r.log.Info("ping status updated", slog.String("type", biz.OperationTypeSafe), slog.Uint64("operator_id", getOperatorID(ctx)), slog.Bool("status", status))
return nil
}