Harden core packages and add interactive CLI config builder (rud config/validate/test)

This commit is contained in:
tyuXX 2026-11-19 13:05:26 +00:00
parent d37503c863
commit 99e24be6c9
29 changed files with 6763 additions and 165 deletions

View file

@ -4,7 +4,6 @@ import (
"bytes"
"context"
"crypto/tls"
"encoding/binary"
"errors"
"fmt"
"io"
@ -15,13 +14,42 @@ import (
"regexp"
"strings"
"sync"
"syscall"
"time"
"git.gsdistance.org/tyuXX/RUD/internal/config"
"git.gsdistance.org/tyuXX/RUD/internal/store"
)
const maxCmdOutputBytes = 1024 * 1024
var (
errICMPUnavailable = errors.New("icmp socket unavailable")
defaultHTTPTransport = &http.Transport{
DisableKeepAlives: true,
}
insecureHTTPTransport = &http.Transport{
DisableKeepAlives: true,
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
},
}
regexCache sync.Map // map[string]*regexp.Regexp
)
func getCompiledRegex(pattern string) (*regexp.Regexp, error) {
if v, ok := regexCache.Load(pattern); ok {
return v.(*regexp.Regexp), nil
}
re, err := regexp.Compile(pattern)
if err != nil {
return nil, err
}
regexCache.Store(pattern, re)
return re, nil
}
// Scheduler manages concurrent periodic health checks for all configured monitors.
type Scheduler struct {
cfg *config.Config
@ -109,10 +137,13 @@ func RunCheckWithRetries(ctx context.Context, m config.MonitorConfig, def config
lastRes = RunSingleCheck(ctx, m, def)
if lastRes.State != store.StateDown {
if degradedThreshold > 0 && lastRes.LatencyMs >= float64(degradedThreshold.Milliseconds()) {
lastRes.State = store.StateDegraded
if lastRes.Message == "" || lastRes.Message == "OK" {
lastRes.Message = fmt.Sprintf("High latency (%.0fms >= %dms)", lastRes.LatencyMs, degradedThreshold.Milliseconds())
if degradedThreshold > 0 {
threshMs := float64(degradedThreshold.Microseconds()) / 1000.0
if lastRes.LatencyMs >= threshMs {
lastRes.State = store.StateDegraded
if lastRes.Message == "" || lastRes.Message == "OK" {
lastRes.Message = fmt.Sprintf("High latency (%.1fms >= %.1fms)", lastRes.LatencyMs, threshMs)
}
}
}
return lastRes
@ -172,11 +203,9 @@ func checkHTTP(ctx context.Context, m config.MonitorConfig, timeout time.Duratio
req.Header.Set(k, v)
}
tr := &http.Transport{
DisableKeepAlives: true,
TLSClientConfig: &tls.Config{
InsecureSkipVerify: m.InsecureSkipVerify,
},
tr := defaultHTTPTransport
if m.InsecureSkipVerify {
tr = insecureHTTPTransport
}
client := &http.Client{
Transport: tr,
@ -230,7 +259,7 @@ func checkHTTP(ctx context.Context, m config.MonitorConfig, timeout time.Duratio
}
if m.BodyRegex != "" {
re, err := regexp.Compile(m.BodyRegex)
re, err := getCompiledRegex(m.BodyRegex)
if err != nil || !re.Match(bodyBytes) {
return store.CheckResult{
Timestamp: time.Now().UTC(),
@ -289,7 +318,8 @@ func checkPing(ctx context.Context, m config.MonitorConfig, timeout time.Duratio
}
// First attempt native ICMP echo (works with CAP_NET_RAW, root, or unprivileged ICMP sockets)
if latencyMs, err := nativeICMPPing(ctx, host, timeout, m.Privileged); err == nil {
latencyMs, err := nativeICMPPing(ctx, host, count, timeout, m.Privileged)
if err == nil {
return store.CheckResult{
Timestamp: time.Now().UTC(),
State: store.StateUp,
@ -297,8 +327,15 @@ func checkPing(ctx context.Context, m config.MonitorConfig, timeout time.Duratio
Message: "ICMP echo reply",
}
}
if !errors.Is(err, errICMPUnavailable) {
return store.CheckResult{
Timestamp: time.Now().UTC(),
State: store.StateDown,
Message: fmt.Sprintf("ping failed: %s", cleanErr(err)),
}
}
// Fallback to system ping utility if available
// Fallback to system ping utility only when native ICMP sockets are unavailable
waitSec := int(timeout.Seconds())
if waitSec < 1 {
waitSec = 1
@ -306,7 +343,7 @@ func checkPing(ctx context.Context, m config.MonitorConfig, timeout time.Duratio
start := time.Now()
cmd := exec.CommandContext(ctx, "ping", "-c", fmt.Sprintf("%d", count), "-W", fmt.Sprintf("%d", waitSec), host)
out, err := cmd.CombinedOutput()
latencyMs := float64(time.Since(start).Microseconds()) / 1000.0
latencyMs = float64(time.Since(start).Microseconds()) / 1000.0
if err == nil {
if parsed := parsePingRTT(string(out)); parsed > 0 {
latencyMs = parsed
@ -327,97 +364,6 @@ func checkPing(ctx context.Context, m config.MonitorConfig, timeout time.Duratio
}
}
func nativeICMPPing(ctx context.Context, host string, timeout time.Duration, privilegedOnly bool) (float64, error) {
ips, err := net.DefaultResolver.LookupIP(ctx, "ip4", host)
if err != nil || len(ips) == 0 {
return 0, fmt.Errorf("resolve %s: %w", host, err)
}
ip4 := ips[0].To4()
if ip4 == nil {
return 0, fmt.Errorf("no IPv4 address for %s", host)
}
// Try Linux unprivileged ICMP datagram socket (SOCK_DGRAM + IPPROTO_ICMP) first unless privilegedOnly is set,
// with fallback to raw ICMP socket (SOCK_RAW + IPPROTO_ICMP).
sockTypes := []int{syscall.SOCK_DGRAM, syscall.SOCK_RAW}
if privilegedOnly {
sockTypes = []int{syscall.SOCK_RAW, syscall.SOCK_DGRAM}
}
fd := -1
usedType := 0
for _, st := range sockTypes {
s, err := syscall.Socket(syscall.AF_INET, st, syscall.IPPROTO_ICMP)
if err == nil {
fd = s
usedType = st
break
}
}
if fd < 0 {
return 0, errors.New("icmp socket unavailable")
}
defer syscall.Close(fd)
tv := syscall.NsecToTimeval(timeout.Nanoseconds())
_ = syscall.SetsockoptTimeval(fd, syscall.SOL_SOCKET, syscall.SO_RCVTIMEO, &tv)
_ = syscall.SetsockoptTimeval(fd, syscall.SOL_SOCKET, syscall.SO_SNDTIMEO, &tv)
// Construct ICMPv4 Echo Request (type 8, code 0)
pkt := make([]byte, 16)
pkt[0] = 8 // Echo Request
pkt[1] = 0
id := uint16(os.Getpid() & 0xffff)
binary.BigEndian.PutUint16(pkt[4:6], id)
binary.BigEndian.PutUint16(pkt[6:8], 1) // Seq 1
copy(pkt[8:], []byte("RUD-PING"))
cs := icmpChecksum(pkt)
binary.BigEndian.PutUint16(pkt[2:4], cs)
var sa syscall.SockaddrInet4
copy(sa.Addr[:], ip4)
start := time.Now()
if err := syscall.Sendto(fd, pkt, 0, &sa); err != nil {
return 0, err
}
buf := make([]byte, 1500)
n, _, err := syscall.Recvfrom(fd, buf, 0)
latencyMs := float64(time.Since(start).Microseconds()) / 1000.0
if err != nil {
return 0, err
}
if n < 8 {
return 0, errors.New("short icmp reply")
}
payload := buf[:n]
if usedType == syscall.SOCK_RAW && len(payload) >= 28 && (payload[0]>>4) == 4 {
hdrLen := int(payload[0]&0x0f) * 4
if len(payload) >= hdrLen+8 {
payload = payload[hdrLen:]
}
}
if payload[0] != 0 { // 0 = Echo Reply
return 0, fmt.Errorf("unexpected icmp type %d", payload[0])
}
return latencyMs, nil
}
func icmpChecksum(b []byte) uint16 {
var sum uint32
for i := 0; i < len(b)-1; i += 2 {
sum += uint32(binary.BigEndian.Uint16(b[i : i+2]))
}
if len(b)%2 == 1 {
sum += uint32(b[len(b)-1]) << 8
}
for (sum >> 16) > 0 {
sum = (sum & 0xffff) + (sum >> 16)
}
return ^uint16(sum)
}
var pingRTTRe = regexp.MustCompile(`time[=<]([0-9.]+)\s*ms`)
func parsePingRTT(output string) float64 {
@ -517,7 +463,7 @@ func checkDNS(ctx context.Context, m config.MonitorConfig, timeout time.Duration
joined := strings.Join(records, ", ")
if m.ExpectedRegex != "" {
re, err := regexp.Compile(m.ExpectedRegex)
re, err := getCompiledRegex(m.ExpectedRegex)
if err != nil {
return store.CheckResult{
Timestamp: time.Now().UTC(),
@ -551,6 +497,31 @@ func checkDNS(ctx context.Context, m config.MonitorConfig, timeout time.Duration
}
}
type limitedBuffer struct {
buf bytes.Buffer
limit int
truncated bool
}
func (l *limitedBuffer) Write(p []byte) (int, error) {
if l.buf.Len() < l.limit {
rem := l.limit - l.buf.Len()
if len(p) > rem {
l.buf.Write(p[:rem])
l.truncated = true
} else {
l.buf.Write(p)
}
} else {
l.truncated = true
}
return len(p), nil
}
func (l *limitedBuffer) String() string {
return l.buf.String()
}
func checkCmd(ctx context.Context, m config.MonitorConfig) store.CheckResult {
var cmd *exec.Cmd
if m.Shell || (len(m.Args) == 0 && strings.ContainsAny(m.Command, " \t|&;<>()$`\"'")) {
@ -562,6 +533,7 @@ func checkCmd(ctx context.Context, m config.MonitorConfig) store.CheckResult {
} else {
cmd = exec.CommandContext(ctx, m.Command, m.Args...)
}
configureCmdProcessGroup(cmd)
if m.WorkingDir != "" {
cmd.Dir = m.WorkingDir
@ -574,7 +546,7 @@ func checkCmd(ctx context.Context, m config.MonitorConfig) store.CheckResult {
cmd.Env = env
}
var outBuf bytes.Buffer
outBuf := limitedBuffer{limit: maxCmdOutputBytes}
cmd.Stdout = &outBuf
cmd.Stderr = &outBuf
@ -619,7 +591,7 @@ func checkCmd(ctx context.Context, m config.MonitorConfig) store.CheckResult {
}
if m.OutputRegex != "" {
re, regErr := regexp.Compile(m.OutputRegex)
re, regErr := getCompiledRegex(m.OutputRegex)
if regErr != nil || !re.MatchString(output) {
return store.CheckResult{
Timestamp: time.Now().UTC(),