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(),

View file

@ -5,6 +5,7 @@ import (
"net"
"net/http"
"net/http/httptest"
"sync"
"testing"
"time"
@ -118,3 +119,88 @@ func TestDNSAndCmdAndPingCheckers(t *testing.T) {
t.Fatalf("expected Ping check up, got %s (%s)", pingRes.State, pingRes.Message)
}
}
func TestConcurrentLoopbackPings(t *testing.T) {
def := config.DefaultsConfig{Timeout: config.NewDuration(2 * time.Second)}
const workers = 6
var wg sync.WaitGroup
errs := make(chan string, workers)
for i := 0; i < workers; i++ {
wg.Add(1)
go func() {
defer wg.Done()
mon := config.MonitorConfig{
ID: "ping-concurrent",
Method: "ping",
Host: "127.0.0.1",
Count: 2,
}
res := RunCheckWithRetries(context.Background(), mon, def)
if res.State != store.StateUp {
errs <- res.Message
}
}()
}
wg.Wait()
close(errs)
for msg := range errs {
t.Fatalf("concurrent ping failed: %s", msg)
}
}
func TestCmdBoundedOutputAndTimeoutCleanup(t *testing.T) {
// Command writing > 1.5 MiB should remain bounded and still check regex
def := config.DefaultsConfig{Timeout: config.NewDuration(3 * time.Second)}
bigCmd := config.MonitorConfig{
ID: "cmd-big",
Method: "cmd",
Command: "printf 'HEAD:'; head -c 1500000 /dev/zero | tr '\\0' 'A'",
Shell: true,
OutputRegex: `^HEAD:A+$`,
}
res := RunCheckWithRetries(context.Background(), bigCmd, def)
if res.State != store.StateUp {
t.Fatalf("expected bounded big output cmd to pass, got %s (%s)", res.State, res.Message)
}
// Command spawning a sleep child should terminate quickly on timeout without hanging pipes
start := time.Now()
timeoutDef := config.DefaultsConfig{Timeout: config.NewDuration(150 * time.Millisecond)}
sleepCmd := config.MonitorConfig{
ID: "cmd-timeout",
Method: "cmd",
Command: "sleep 10 & wait",
Shell: true,
}
resTimeout := RunCheckWithRetries(context.Background(), sleepCmd, timeoutDef)
elapsed := time.Since(start)
if resTimeout.State != store.StateDown {
t.Fatalf("expected timed out cmd to mark down, got %s", resTimeout.State)
}
if elapsed > 2*time.Second {
t.Fatalf("timed out cmd took too long to clean up process group: %v", elapsed)
}
}
func TestSubMsDegradedLatencyThreshold(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
time.Sleep(2 * time.Millisecond)
w.WriteHeader(http.StatusOK)
}))
defer ts.Close()
def := config.DefaultsConfig{
Timeout: config.NewDuration(2 * time.Second),
DegradedLatency: config.NewDuration(500 * time.Microsecond), // 0.5ms (< 1ms!)
}
mon := config.MonitorConfig{
ID: "http-subms",
Method: "http",
URL: ts.URL,
}
res := RunCheckWithRetries(context.Background(), mon, def)
if res.State != store.StateDegraded {
t.Fatalf("expected sub-ms degraded threshold (500us) to trigger degraded state, got %s (latency=%.3fms)", res.State, res.LatencyMs)
}
}

View file

@ -0,0 +1,7 @@
//go:build !unix
package checker
import "os/exec"
func configureCmdProcessGroup(cmd *exec.Cmd) {}

View file

@ -0,0 +1,20 @@
//go:build unix
package checker
import (
"os/exec"
"syscall"
"time"
)
func configureCmdProcessGroup(cmd *exec.Cmd) {
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
cmd.Cancel = func() error {
if cmd.Process != nil {
return syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
}
return nil
}
cmd.WaitDelay = 500 * time.Millisecond
}

View file

@ -0,0 +1,195 @@
//go:build linux
package checker
import (
"bytes"
"context"
"encoding/binary"
"errors"
"fmt"
"net"
"sync/atomic"
"syscall"
"time"
)
var icmpIDCounter uint32
func nativeICMPPing(ctx context.Context, host string, count int, timeout time.Duration, privilegedOnly bool) (float64, error) {
if count <= 0 {
count = 1
}
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, sockErr := syscall.Socket(syscall.AF_INET, st, syscall.IPPROTO_ICMP)
if sockErr == nil {
fd = s
usedType = st
break
}
}
if fd < 0 {
return 0, errICMPUnavailable
}
defer syscall.Close(fd)
id := uint16(atomic.AddUint32(&icmpIDCounter, 1) & 0xffff)
if id == 0 {
id = uint16(atomic.AddUint32(&icmpIDCounter, 1) & 0xffff)
}
var sa syscall.SockaddrInet4
copy(sa.Addr[:], ip4)
overallDeadline := time.Now().Add(timeout)
buf := make([]byte, 1500)
var rttSum float64
var received int
var lastErr error
for seq := 1; seq <= count; seq++ {
if ctx.Err() != nil {
if received > 0 {
break
}
return 0, ctx.Err()
}
remainingTotal := time.Until(overallDeadline)
if remainingTotal <= 0 {
break
}
pktsLeft := count - seq + 1
pktTimeout := remainingTotal / time.Duration(pktsLeft)
if pktTimeout < 50*time.Millisecond && remainingTotal > 50*time.Millisecond {
pktTimeout = 50 * time.Millisecond
}
pktDeadline := time.Now().Add(pktTimeout)
if pktDeadline.After(overallDeadline) {
pktDeadline = overallDeadline
}
// Construct ICMPv4 Echo Request (type 8, code 0)
pkt := make([]byte, 16)
pkt[0] = 8 // Echo Request
pkt[1] = 0
binary.BigEndian.PutUint16(pkt[4:6], id)
binary.BigEndian.PutUint16(pkt[6:8], uint16(seq))
copy(pkt[8:], []byte("RUD-PING"))
cs := icmpChecksum(pkt)
binary.BigEndian.PutUint16(pkt[2:4], cs)
sendTV := syscall.NsecToTimeval(pktTimeout.Nanoseconds())
_ = syscall.SetsockoptTimeval(fd, syscall.SOL_SOCKET, syscall.SO_SNDTIMEO, &sendTV)
sendStart := time.Now()
if err := syscall.Sendto(fd, pkt, 0, &sa); err != nil {
lastErr = err
continue
}
for {
if ctx.Err() != nil {
if received > 0 {
return rttSum / float64(received), nil
}
return 0, ctx.Err()
}
rem := time.Until(pktDeadline)
if rem <= 0 {
lastErr = errors.New("icmp echo timeout")
break
}
slice := rem
if slice > 200*time.Millisecond {
slice = 200 * time.Millisecond
}
rcvTV := syscall.NsecToTimeval(slice.Nanoseconds())
_ = syscall.SetsockoptTimeval(fd, syscall.SOL_SOCKET, syscall.SO_RCVTIMEO, &rcvTV)
n, from, rcvErr := syscall.Recvfrom(fd, buf, 0)
if rcvErr != nil {
if errors.Is(rcvErr, syscall.EINTR) || errors.Is(rcvErr, syscall.EAGAIN) || errors.Is(rcvErr, syscall.EWOULDBLOCK) {
continue
}
lastErr = rcvErr
break
}
if n < 8 {
continue
}
if from4, ok := from.(*syscall.SockaddrInet4); !ok || !bytes.Equal(from4.Addr[:], ip4) {
continue
}
payload := buf[:n]
if usedType == syscall.SOCK_RAW && len(payload) >= 20 && (payload[0]>>4) == 4 {
hdrLen := int(payload[0]&0x0f) * 4
if hdrLen < 20 || len(payload) < hdrLen+8 {
continue
}
payload = payload[hdrLen:]
}
// Ignore non-Echo-Reply packets (e.g. Echo Requests seen on loopback SOCK_RAW)
if payload[0] != 0 || payload[1] != 0 {
continue
}
replyID := binary.BigEndian.Uint16(payload[4:6])
replySeq := binary.BigEndian.Uint16(payload[6:8])
if usedType == syscall.SOCK_RAW && replyID != id {
continue
}
if replySeq != uint16(seq) {
continue
}
rttMs := float64(time.Since(sendStart).Microseconds()) / 1000.0
rttSum += rttMs
received++
break
}
}
if received > 0 {
return rttSum / float64(received), nil
}
if lastErr == nil {
lastErr = errors.New("icmp echo timeout")
}
return 0, lastErr
}
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)
}

View file

@ -0,0 +1,12 @@
//go:build !linux
package checker
import (
"context"
"time"
)
func nativeICMPPing(ctx context.Context, host string, count int, timeout time.Duration, privilegedOnly bool) (float64, error) {
return 0, errICMPUnavailable
}