Import netquality 1.1.1
Initial import of the 1.1.1 source tree. Corresponds to Origin commit f9d97e368818acfe7dd44fa9fe5088b9629d0dff. Co-authored-by: yanjiu0721 <yanjiu0721@users.noreply.github.com>
This commit is contained in:
1 parent
948594e7c0
commit
f6ffbde518
93 files changed
+10570
-1
No files matched your search
@@ -0,0 +1 @@
|
||||
/netquality-reflector
|
||||
@@ -0,0 +1,10 @@
|
||||
.PHONY: build run test
|
||||
|
||||
build:
|
||||
go build -o netquality-reflector .
|
||||
|
||||
run: build
|
||||
./netquality-reflector
|
||||
|
||||
test:
|
||||
go test ./...
|
||||
@@ -0,0 +1,23 @@
|
||||
[Unit]
|
||||
Description=NetQuality probe node and reflector
|
||||
After=network-online.target
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
ExecStart=/usr/local/bin/netquality-reflector -mode both -bind 0.0.0.0 -tcp-port 19090 -udp-port 19091 -control-addr 127.0.0.1:8443
|
||||
Restart=on-failure
|
||||
RestartSec=2
|
||||
NoNewPrivileges=true
|
||||
ProtectSystem=strict
|
||||
ProtectHome=true
|
||||
PrivateTmp=true
|
||||
|
||||
# 二选一,不要把真实口令提交到仓库。
|
||||
# 留空或不设置 NQ_NODE_TOKEN:公开节点,任何人都能用,但有并发和时长上限。
|
||||
# Environment=NQ_NODE_TOKEN=replace-with-your-own-node-token
|
||||
# 下面这个是反射帧里的回显口令,和节点口令不是同一个。
|
||||
# Environment=NQ_TOKEN=replace-with-your-own-echo-token
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -0,0 +1,20 @@
|
||||
[Unit]
|
||||
Description=NetQuality UDP/TCP reflector
|
||||
After=network-online.target
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
ExecStart=/usr/local/bin/netquality-reflector -bind 0.0.0.0 -tcp-port 19090 -udp-port 19091
|
||||
Restart=on-failure
|
||||
RestartSec=2
|
||||
NoNewPrivileges=true
|
||||
ProtectSystem=strict
|
||||
ProtectHome=true
|
||||
PrivateTmp=true
|
||||
|
||||
# Optional shared token. Uncomment and set a short passphrase (max 32 bytes).
|
||||
# Environment=NQ_TOKEN=replace-me
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
+205
@@ -0,0 +1,205 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"errors"
|
||||
"io"
|
||||
"log"
|
||||
"net"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Server is a TCP and UDP echo reflector for probe frames.
|
||||
type Server struct {
|
||||
Token [tokenLen]byte
|
||||
Required bool
|
||||
Verbose bool
|
||||
|
||||
requests atomic.Uint64
|
||||
replies atomic.Uint64
|
||||
rejected atomic.Uint64
|
||||
|
||||
lisMu sync.Mutex
|
||||
tcpListener net.Listener
|
||||
udpConn *net.UDPConn
|
||||
|
||||
wg sync.WaitGroup
|
||||
}
|
||||
|
||||
// HandlePacket validates a request and returns the reply bytes.
|
||||
// Invalid packets return ok=false and are not answered.
|
||||
func (s *Server) HandlePacket(p Packet, now time.Time) ([]byte, bool) {
|
||||
s.requests.Add(1)
|
||||
if p.Type != typeRequest || p.Version != protocolVer {
|
||||
s.rejected.Add(1)
|
||||
return nil, false
|
||||
}
|
||||
if !tokenMatches(p.Token, s.Token, s.Required) {
|
||||
s.rejected.Add(1)
|
||||
if s.Verbose {
|
||||
log.Printf("reject seq=%d: token mismatch", p.Sequence)
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
p.Type = typeReply
|
||||
p.ServerUnixNano = uint64(now.UnixNano())
|
||||
buf, err := p.Marshal()
|
||||
if err != nil {
|
||||
s.rejected.Add(1)
|
||||
return nil, false
|
||||
}
|
||||
s.replies.Add(1)
|
||||
if s.Verbose {
|
||||
log.Printf("echo seq=%d bytes=%d", p.Sequence, len(buf))
|
||||
}
|
||||
return buf, true
|
||||
}
|
||||
|
||||
func (s *Server) Stats() (requests, replies, rejected uint64) {
|
||||
return s.requests.Load(), s.replies.Load(), s.rejected.Load()
|
||||
}
|
||||
|
||||
// ServeTCP accepts connections until the listener is closed.
|
||||
func (s *Server) ServeTCP(ln net.Listener) {
|
||||
s.lisMu.Lock()
|
||||
s.tcpListener = ln
|
||||
s.lisMu.Unlock()
|
||||
for {
|
||||
conn, err := ln.Accept()
|
||||
if err != nil {
|
||||
if errors.Is(err, net.ErrClosed) {
|
||||
return
|
||||
}
|
||||
log.Printf("tcp accept: %v", err)
|
||||
continue
|
||||
}
|
||||
s.wg.Add(1)
|
||||
go func() {
|
||||
defer s.wg.Done()
|
||||
s.handleTCPConn(conn)
|
||||
}()
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) handleTCPConn(conn net.Conn) {
|
||||
defer conn.Close()
|
||||
if tc, ok := conn.(*net.TCPConn); ok {
|
||||
// Go already defaults NoDelay to true; keep it explicit so echoes are
|
||||
// not held by Nagle and RTT stays honest.
|
||||
_ = tc.SetNoDelay(true)
|
||||
_ = tc.SetKeepAlive(true)
|
||||
_ = tc.SetKeepAlivePeriod(30 * time.Second)
|
||||
}
|
||||
remote := conn.RemoteAddr().String()
|
||||
if s.Verbose {
|
||||
log.Printf("tcp connected %s", remote)
|
||||
}
|
||||
r := bufio.NewReaderSize(conn, headerSize+maxPayloadSize)
|
||||
for {
|
||||
_ = conn.SetReadDeadline(time.Now().Add(2 * time.Minute))
|
||||
pkt, err := readFrame(r)
|
||||
if err != nil {
|
||||
if !errors.Is(err, io.EOF) && !errors.Is(err, net.ErrClosed) && s.Verbose {
|
||||
log.Printf("tcp %s read: %v", remote, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
reply, ok := s.HandlePacket(pkt, time.Now())
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
_ = conn.SetWriteDeadline(time.Now().Add(5 * time.Second))
|
||||
if _, err := conn.Write(reply); err != nil {
|
||||
if s.Verbose {
|
||||
log.Printf("tcp %s write: %v", remote, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// readFrame reads exactly one frame from a TCP stream.
|
||||
func readFrame(r *bufio.Reader) (Packet, error) {
|
||||
hdr := make([]byte, headerSize)
|
||||
if _, err := io.ReadFull(r, hdr); err != nil {
|
||||
return Packet{}, err
|
||||
}
|
||||
if string(hdr[0:4]) != magic {
|
||||
return Packet{}, errBadMagic
|
||||
}
|
||||
if hdr[4] != protocolVer {
|
||||
return Packet{}, errBadVersion
|
||||
}
|
||||
payloadLen := int(binaryUint16(hdr[payloadLenOff : payloadLenOff+2]))
|
||||
if payloadLen > maxPayloadSize {
|
||||
return Packet{}, errBadPayloadLen
|
||||
}
|
||||
buf := make([]byte, headerSize+payloadLen)
|
||||
copy(buf, hdr)
|
||||
if payloadLen > 0 {
|
||||
if _, err := io.ReadFull(r, buf[headerSize:]); err != nil {
|
||||
return Packet{}, err
|
||||
}
|
||||
}
|
||||
return ParsePacket(buf)
|
||||
}
|
||||
|
||||
func binaryUint16(b []byte) uint16 {
|
||||
return uint16(b[0]) | uint16(b[1])<<8
|
||||
}
|
||||
|
||||
// ServeUDP reads datagrams until the socket is closed.
|
||||
func (s *Server) ServeUDP(conn *net.UDPConn) {
|
||||
s.lisMu.Lock()
|
||||
s.udpConn = conn
|
||||
s.lisMu.Unlock()
|
||||
buf := make([]byte, headerSize+maxPayloadSize+64)
|
||||
for {
|
||||
_ = conn.SetReadDeadline(time.Now().Add(2 * time.Minute))
|
||||
n, addr, err := conn.ReadFromUDP(buf)
|
||||
if err != nil {
|
||||
if errors.Is(err, net.ErrClosed) {
|
||||
return
|
||||
}
|
||||
var ne net.Error
|
||||
if errors.As(err, &ne) && ne.Timeout() {
|
||||
continue
|
||||
}
|
||||
log.Printf("udp read: %v", err)
|
||||
continue
|
||||
}
|
||||
pkt, err := ParsePacket(buf[:n])
|
||||
if err != nil {
|
||||
s.requests.Add(1)
|
||||
s.rejected.Add(1)
|
||||
if s.Verbose {
|
||||
log.Printf("udp %s bad packet: %v", addr, err)
|
||||
}
|
||||
continue
|
||||
}
|
||||
reply, ok := s.HandlePacket(pkt, time.Now())
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
_ = conn.SetWriteDeadline(time.Now().Add(5 * time.Second))
|
||||
if _, err := conn.WriteToUDP(reply, addr); err != nil && s.Verbose {
|
||||
log.Printf("udp %s write: %v", addr, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Close stops listeners. Existing TCP handlers exit on their next I/O error.
|
||||
func (s *Server) Close() {
|
||||
s.lisMu.Lock()
|
||||
tcp := s.tcpListener
|
||||
udp := s.udpConn
|
||||
s.lisMu.Unlock()
|
||||
if tcp != nil {
|
||||
_ = tcp.Close()
|
||||
}
|
||||
if udp != nil {
|
||||
_ = udp.Close()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
module netquality/server
|
||||
|
||||
go 1.22
|
||||
+250
@@ -0,0 +1,250 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"flag"
|
||||
"fmt"
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"strconv"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
func main() {
|
||||
bind := flag.String("bind", envStr("NQ_BIND", "0.0.0.0"), "reflector bind address")
|
||||
tcpPort := flag.Int("tcp-port", envInt("NQ_TCP_PORT", 19090), "TCP echo port (0 disables)")
|
||||
udpPort := flag.Int("udp-port", envInt("NQ_UDP_PORT", 19091), "UDP echo port (0 disables)")
|
||||
tokenFlag := flag.String("token", envStr("NQ_TOKEN", ""), "optional echo token written into NQ frames, max 32 bytes; empty accepts any echo token")
|
||||
nodeToken := flag.String("node-token", envStr("NQ_NODE_TOKEN", ""), "optional control-plane token; empty makes the node public")
|
||||
mode := flag.String("mode", envStr("NQ_MODE", "reflector"), "reflector, node, or both")
|
||||
controlAddr := flag.String("control-addr", envStr("NQ_CONTROL_ADDR", "127.0.0.1:8443"), "node control listen address")
|
||||
allowPrivate := flag.Bool("allow-private", envBool("NQ_ALLOW_PRIVATE", false), "let the node probe loopback and private addresses (metadata stays blocked)")
|
||||
allowNets := flag.String("allow-nets", envStr("NQ_ALLOW_NETS", ""), "comma-separated extra CIDRs the node may probe")
|
||||
tlsCert := flag.String("tls-cert", envStr("NQ_TLS_CERT", ""), "TLS certificate for the control API")
|
||||
tlsKey := flag.String("tls-key", envStr("NQ_TLS_KEY", ""), "TLS private key for the control API")
|
||||
verbose := flag.Bool("v", false, "log each echoed packet")
|
||||
flag.Parse()
|
||||
|
||||
switch *mode {
|
||||
case "reflector", "node", "both":
|
||||
default:
|
||||
log.Fatal("-mode must be reflector, node, or both")
|
||||
}
|
||||
if *tcpPort < 0 || *tcpPort > 65535 || *udpPort < 0 || *udpPort > 65535 {
|
||||
log.Fatal("ports must be between 0 and 65535")
|
||||
}
|
||||
if (*mode == "reflector" || *mode == "both") && *tcpPort == 0 && *udpPort == 0 {
|
||||
log.Fatal("reflector mode needs -tcp-port and/or -udp-port")
|
||||
}
|
||||
if (*tlsCert == "") != (*tlsKey == "") {
|
||||
log.Fatal("-tls-cert and -tls-key must be set together")
|
||||
}
|
||||
|
||||
tok, err := tokenBytes(*tokenFlag)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
extra, err := parseNets(*allowNets)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
errCh := make(chan error, 4)
|
||||
var srv *Server
|
||||
if *mode == "reflector" || *mode == "both" {
|
||||
srv = &Server{Token: tok, Required: *tokenFlag != "", Verbose: *verbose}
|
||||
startReflector(srv, *bind, *tcpPort, *udpPort, errCh)
|
||||
if srv.Required {
|
||||
log.Printf("echo token check enabled")
|
||||
} else {
|
||||
log.Printf("echo token check disabled")
|
||||
}
|
||||
}
|
||||
|
||||
var httpSrv *http.Server
|
||||
if *mode == "node" || *mode == "both" {
|
||||
node := newNode(*nodeToken, *allowPrivate, extra, defaultLimits())
|
||||
httpSrv = &http.Server{
|
||||
Addr: *controlAddr,
|
||||
Handler: node.Handler(),
|
||||
ReadHeaderTimeout: 5 * time.Second,
|
||||
IdleTimeout: 2 * time.Minute,
|
||||
}
|
||||
ln, err := net.Listen("tcp", *controlAddr)
|
||||
if err != nil {
|
||||
log.Fatalf("control listen %s: %v", *controlAddr, err)
|
||||
}
|
||||
go func() {
|
||||
var serveErr error
|
||||
if *tlsCert != "" {
|
||||
log.Printf("node control listening with TLS on %s", ln.Addr())
|
||||
serveErr = httpSrv.ServeTLS(ln, *tlsCert, *tlsKey)
|
||||
} else {
|
||||
log.Printf("node control listening on %s (no TLS; put an HTTPS reverse proxy in front if this is reachable from the internet)", ln.Addr())
|
||||
serveErr = httpSrv.Serve(ln)
|
||||
}
|
||||
if serveErr != nil && serveErr != http.ErrServerClosed {
|
||||
errCh <- serveErr
|
||||
}
|
||||
}()
|
||||
if node.Public() && !loopbackHost(*controlAddr) {
|
||||
log.Printf("WARNING: this node is PUBLIC. Anyone who can reach %s can start bounded probes. Set -node-token to require a control token. Caps stay on: jobs=%d duration=%s interval>=%s probes/s=%d bandwidth=%dB/s",
|
||||
*controlAddr, node.Limits.MaxJobs, node.Limits.MaxDuration, node.Limits.MinInterval, node.Limits.MaxProbePerSec, node.Limits.MaxBytesPerSec)
|
||||
} else if node.Public() {
|
||||
log.Printf("node is public and bound to loopback; no control token is required")
|
||||
} else {
|
||||
log.Printf("node is private; a control token is required and is not logged")
|
||||
}
|
||||
if *allowPrivate {
|
||||
log.Printf("private and loopback targets are allowed; metadata addresses stay blocked")
|
||||
}
|
||||
}
|
||||
|
||||
sig := make(chan os.Signal, 1)
|
||||
signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
|
||||
ticker := time.NewTicker(60 * time.Second)
|
||||
defer ticker.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-sig:
|
||||
log.Printf("shutting down")
|
||||
if srv != nil {
|
||||
srv.Close()
|
||||
}
|
||||
if httpSrv != nil {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
_ = httpSrv.Shutdown(ctx)
|
||||
cancel()
|
||||
}
|
||||
return
|
||||
case err := <-errCh:
|
||||
log.Printf("listener stopped: %v", err)
|
||||
if srv != nil {
|
||||
srv.Close()
|
||||
}
|
||||
if httpSrv != nil {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
_ = httpSrv.Shutdown(ctx)
|
||||
cancel()
|
||||
}
|
||||
os.Exit(1)
|
||||
case <-ticker.C:
|
||||
if srv != nil {
|
||||
req, rep, rej := srv.Stats()
|
||||
log.Printf("stats requests=%d replies=%d rejected=%d", req, rep, rej)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func startReflector(srv *Server, bind string, tcpPort, udpPort int, errCh chan error) {
|
||||
if tcpPort > 0 {
|
||||
addr := net.JoinHostPort(bind, strconv.Itoa(tcpPort))
|
||||
ln, err := net.Listen("tcp", addr)
|
||||
if err != nil {
|
||||
log.Fatalf("tcp listen %s: %v", addr, err)
|
||||
}
|
||||
log.Printf("TCP reflector listening on %s", ln.Addr())
|
||||
go func() {
|
||||
srv.ServeTCP(ln)
|
||||
errCh <- fmt.Errorf("tcp listener closed")
|
||||
}()
|
||||
}
|
||||
if udpPort > 0 {
|
||||
addr := net.JoinHostPort(bind, strconv.Itoa(udpPort))
|
||||
udpAddr, err := net.ResolveUDPAddr("udp", addr)
|
||||
if err != nil {
|
||||
log.Fatalf("udp resolve %s: %v", addr, err)
|
||||
}
|
||||
conn, err := net.ListenUDP("udp", udpAddr)
|
||||
if err != nil {
|
||||
log.Fatalf("udp listen %s: %v", addr, err)
|
||||
}
|
||||
log.Printf("UDP reflector listening on %s", conn.LocalAddr())
|
||||
go func() {
|
||||
srv.ServeUDP(conn)
|
||||
errCh <- fmt.Errorf("udp listener closed")
|
||||
}()
|
||||
}
|
||||
}
|
||||
|
||||
func parseNets(s string) ([]*net.IPNet, error) {
|
||||
s = strings.TrimSpace(s)
|
||||
if s == "" {
|
||||
return nil, nil
|
||||
}
|
||||
var out []*net.IPNet
|
||||
for _, part := range strings.Split(s, ",") {
|
||||
part = strings.TrimSpace(part)
|
||||
if part == "" {
|
||||
continue
|
||||
}
|
||||
if !strings.Contains(part, "/") {
|
||||
ip := net.ParseIP(part)
|
||||
if ip == nil {
|
||||
return nil, fmt.Errorf("bad allow entry %q", part)
|
||||
}
|
||||
bits := 32
|
||||
if ip.To4() == nil {
|
||||
bits = 128
|
||||
}
|
||||
part = ip.String() + "/" + strconv.Itoa(bits)
|
||||
}
|
||||
_, n, err := net.ParseCIDR(part)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("bad allow entry %q: %w", part, err)
|
||||
}
|
||||
out = append(out, n)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func loopbackHost(addr string) bool {
|
||||
host, _, err := net.SplitHostPort(addr)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
host = strings.Trim(host, "[]")
|
||||
ip := net.ParseIP(host)
|
||||
return ip != nil && ip.IsLoopback()
|
||||
}
|
||||
|
||||
func envStr(key, fallback string) string {
|
||||
if v, ok := os.LookupEnv(key); ok && v != "" {
|
||||
return v
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
func envInt(key string, fallback int) int {
|
||||
v, ok := os.LookupEnv(key)
|
||||
if !ok || v == "" {
|
||||
return fallback
|
||||
}
|
||||
n, err := strconv.Atoi(v)
|
||||
if err != nil {
|
||||
return fallback
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func envBool(key string, fallback bool) bool {
|
||||
v, ok := os.LookupEnv(key)
|
||||
if !ok || v == "" {
|
||||
return fallback
|
||||
}
|
||||
switch strings.ToLower(v) {
|
||||
case "1", "true", "yes", "on":
|
||||
return true
|
||||
case "0", "false", "no", "off":
|
||||
return false
|
||||
default:
|
||||
return fallback
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
package main
|
||||
|
||||
import "time"
|
||||
|
||||
const (
|
||||
statusOK = "ok"
|
||||
statusTimeout = "timeout"
|
||||
statusUnknown = "unknown"
|
||||
statusRefused = "refused"
|
||||
statusDNS = "dns"
|
||||
statusProtocol = "protocol"
|
||||
statusError = "error"
|
||||
|
||||
kindConnect = "connect"
|
||||
kindProbe = "probe"
|
||||
kindQuery = "query"
|
||||
)
|
||||
|
||||
// Outcome is one finished attempt. Pending attempts are never turned into
|
||||
// a sample, so a chart cannot show a fake 100% before the probe completes.
|
||||
type Outcome struct {
|
||||
Status string
|
||||
Kind string
|
||||
Rtt time.Duration
|
||||
HasRtt bool
|
||||
Note string
|
||||
Detail map[string]string
|
||||
Reconnect bool
|
||||
}
|
||||
|
||||
type jitter struct {
|
||||
has bool
|
||||
last float64
|
||||
value float64
|
||||
}
|
||||
|
||||
func (j *jitter) push(rttMs float64) float64 {
|
||||
if j.has {
|
||||
d := rttMs - j.last
|
||||
if d < 0 {
|
||||
d = -d
|
||||
}
|
||||
j.value += (d - j.value) / 16
|
||||
}
|
||||
j.last = rttMs
|
||||
j.has = true
|
||||
return j.value
|
||||
}
|
||||
|
||||
// sampleBook folds finished outcomes. Rates use only completed attempts.
|
||||
// "unknown" (no protocol reply) is not counted as proven packet loss.
|
||||
type sampleBook struct {
|
||||
profile string
|
||||
|
||||
sent int
|
||||
completed int
|
||||
ok int
|
||||
timeout int
|
||||
unknown int
|
||||
refused int
|
||||
dns int
|
||||
protocol int
|
||||
other int
|
||||
reconnect int
|
||||
consecutive int
|
||||
|
||||
lastRttMs *float64
|
||||
jitter jitter
|
||||
lastNote string
|
||||
detail map[string]string
|
||||
}
|
||||
|
||||
func (b *sampleBook) add(o Outcome) {
|
||||
b.sent++
|
||||
b.completed++
|
||||
if o.Reconnect {
|
||||
b.reconnect++
|
||||
}
|
||||
if o.Note != "" {
|
||||
b.lastNote = o.Note
|
||||
}
|
||||
if len(o.Detail) > 0 {
|
||||
if b.detail == nil {
|
||||
b.detail = map[string]string{}
|
||||
}
|
||||
for k, v := range o.Detail {
|
||||
b.detail[k] = v
|
||||
}
|
||||
}
|
||||
switch o.Status {
|
||||
case statusOK:
|
||||
b.ok++
|
||||
b.consecutive = 0
|
||||
if o.HasRtt {
|
||||
ms := float64(o.Rtt) / float64(time.Millisecond)
|
||||
b.lastRttMs = &ms
|
||||
b.jitter.push(ms)
|
||||
}
|
||||
case statusTimeout:
|
||||
// Only a written NQ probe that never returned is probe-response loss.
|
||||
// A TCP connect timeout is a failed attempt, not a lost echo.
|
||||
if o.Kind == kindProbe {
|
||||
b.timeout++
|
||||
} else {
|
||||
b.other++
|
||||
}
|
||||
b.consecutive++
|
||||
case statusUnknown:
|
||||
b.unknown++
|
||||
case statusRefused:
|
||||
b.refused++
|
||||
b.consecutive++
|
||||
case statusDNS:
|
||||
b.dns++
|
||||
b.consecutive++
|
||||
case statusProtocol:
|
||||
b.protocol++
|
||||
b.consecutive++
|
||||
default:
|
||||
b.other++
|
||||
b.consecutive++
|
||||
}
|
||||
}
|
||||
|
||||
func (b *sampleBook) summary() summaryMsg {
|
||||
s := summaryMsg{
|
||||
Sent: b.sent,
|
||||
Pending: 0,
|
||||
Completed: b.completed,
|
||||
OK: b.ok,
|
||||
Timeout: b.timeout,
|
||||
Unknown: b.unknown,
|
||||
Refused: b.refused,
|
||||
DNS: b.dns,
|
||||
Protocol: b.protocol,
|
||||
Other: b.other,
|
||||
Reconnects: b.reconnect,
|
||||
ConsecutiveFailures: b.consecutive,
|
||||
LastNote: b.lastNote,
|
||||
Detail: b.detail,
|
||||
}
|
||||
if b.lastRttMs != nil {
|
||||
v := *b.lastRttMs
|
||||
s.RttMs = &v
|
||||
}
|
||||
if b.jitter.has {
|
||||
v := b.jitter.value
|
||||
s.JitterMs = &v
|
||||
}
|
||||
if b.completed == 0 {
|
||||
return s
|
||||
}
|
||||
switch b.profile {
|
||||
case "nq-tcp", "nq-udp":
|
||||
// Echo was requested and did not come back. This is probe-response
|
||||
// loss, not a NIC packet-loss counter. TCP timeouts still land here
|
||||
// only after a frame was written; connect failures use other statuses.
|
||||
if b.timeout+b.ok > 0 {
|
||||
v := float64(b.timeout) * 100 / float64(b.timeout+b.ok)
|
||||
s.ProbeLossPct = &v
|
||||
}
|
||||
case "tcp-connect", "minecraft-java":
|
||||
denom := b.ok + b.timeout + b.refused + b.dns + b.protocol + b.other
|
||||
if denom > 0 {
|
||||
v := float64(denom-b.ok) * 100 / float64(denom)
|
||||
s.FailurePct = &v
|
||||
}
|
||||
default:
|
||||
denom := b.ok + b.protocol + b.refused + b.dns + b.other
|
||||
if denom > 0 {
|
||||
v := float64(denom-b.ok) * 100 / float64(denom)
|
||||
s.FailurePct = &v
|
||||
}
|
||||
if b.unknown+b.ok+b.protocol > 0 {
|
||||
v := float64(b.unknown) * 100 / float64(b.completed)
|
||||
s.UnknownPct = &v
|
||||
}
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
type summaryMsg struct {
|
||||
Sent int `json:"sent"`
|
||||
Pending int `json:"pending"`
|
||||
Completed int `json:"completed"`
|
||||
OK int `json:"ok"`
|
||||
Timeout int `json:"timeout"`
|
||||
Unknown int `json:"unknown"`
|
||||
Refused int `json:"refused"`
|
||||
DNS int `json:"dns"`
|
||||
Protocol int `json:"protocol"`
|
||||
Other int `json:"other"`
|
||||
Reconnects int `json:"reconnects"`
|
||||
ConsecutiveFailures int `json:"consecutiveFailures"`
|
||||
RttMs *float64 `json:"rttMs,omitempty"`
|
||||
JitterMs *float64 `json:"jitterMs,omitempty"`
|
||||
ProbeLossPct *float64 `json:"probeLossPct,omitempty"`
|
||||
FailurePct *float64 `json:"failurePct,omitempty"`
|
||||
UnknownPct *float64 `json:"unknownPct,omitempty"`
|
||||
LastNote string `json:"lastNote,omitempty"`
|
||||
Detail map[string]string `json:"detail,omitempty"`
|
||||
}
|
||||
+568
@@ -0,0 +1,568 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
type jobSpec struct {
|
||||
Host string
|
||||
Port int
|
||||
Profile string
|
||||
IP net.IP
|
||||
Interval time.Duration
|
||||
Timeout time.Duration
|
||||
Duration time.Duration
|
||||
PacketSize int
|
||||
Echo [tokenLen]byte
|
||||
DNSName string
|
||||
Payload []byte
|
||||
Expect []byte
|
||||
}
|
||||
|
||||
type Limits struct {
|
||||
MaxJobs int
|
||||
MaxDuration time.Duration
|
||||
MinInterval time.Duration
|
||||
MaxProbePerSec int
|
||||
MaxBytesPerSec int
|
||||
MaxPacket int
|
||||
}
|
||||
|
||||
func defaultLimits() Limits {
|
||||
return Limits{
|
||||
MaxJobs: 4,
|
||||
MaxDuration: 120 * time.Second,
|
||||
MinInterval: 200 * time.Millisecond,
|
||||
MaxProbePerSec: 20,
|
||||
MaxBytesPerSec: 256 * 1024,
|
||||
MaxPacket: 1400,
|
||||
}
|
||||
}
|
||||
|
||||
type sampleMsg struct {
|
||||
Seq int `json:"seq"`
|
||||
Status string `json:"status"`
|
||||
Kind string `json:"kind"`
|
||||
RttMs *float64 `json:"rttMs,omitempty"`
|
||||
JitterMs *float64 `json:"jitterMs,omitempty"`
|
||||
Note string `json:"note,omitempty"`
|
||||
Detail map[string]string `json:"detail,omitempty"`
|
||||
Summary summaryMsg `json:"summary"`
|
||||
}
|
||||
|
||||
type Node struct {
|
||||
Token string
|
||||
AllowPrivate bool
|
||||
ExtraNets []*net.IPNet
|
||||
Limits Limits
|
||||
Resolver resolver
|
||||
|
||||
mu sync.Mutex
|
||||
jobs map[string]*probeJob
|
||||
sem chan struct{}
|
||||
pace *paced
|
||||
}
|
||||
|
||||
func newNode(token string, allowPrivate bool, extra []*net.IPNet, limits Limits) *Node {
|
||||
if limits.MaxJobs <= 0 {
|
||||
limits = defaultLimits()
|
||||
}
|
||||
n := &Node{
|
||||
Token: token,
|
||||
AllowPrivate: allowPrivate,
|
||||
ExtraNets: extra,
|
||||
Limits: limits,
|
||||
jobs: map[string]*probeJob{},
|
||||
sem: make(chan struct{}, limits.MaxJobs),
|
||||
pace: newPaced(limits.MaxProbePerSec, limits.MaxBytesPerSec),
|
||||
}
|
||||
go n.reap()
|
||||
return n
|
||||
}
|
||||
|
||||
func (n *Node) Public() bool { return n.Token == "" }
|
||||
|
||||
func (n *Node) Handler() http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("GET /v1/info", n.info)
|
||||
mux.HandleFunc("POST /v1/jobs", n.auth(n.create))
|
||||
mux.HandleFunc("GET /v1/jobs/{id}", n.auth(n.snapshot))
|
||||
mux.HandleFunc("GET /v1/jobs/{id}/stream", n.auth(n.stream))
|
||||
mux.HandleFunc("DELETE /v1/jobs/{id}", n.auth(n.remove))
|
||||
return mux
|
||||
}
|
||||
|
||||
func (n *Node) info(w http.ResponseWriter, _ *http.Request) {
|
||||
vis := "private"
|
||||
if n.Public() {
|
||||
vis = "public"
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"visibility": vis,
|
||||
"authRequired": !n.Public(),
|
||||
"profiles": []string{
|
||||
"nq-tcp", "nq-udp", "tcp-connect", "udp-generic", "dns",
|
||||
"minecraft-java", "minecraft-bedrock", "custom-udp",
|
||||
},
|
||||
"limits": map[string]int{
|
||||
"maxJobs": n.Limits.MaxJobs,
|
||||
"maxDurationSec": int(n.Limits.MaxDuration / time.Second),
|
||||
"minIntervalMs": int(n.Limits.MinInterval / time.Millisecond),
|
||||
"maxPacketBytes": n.Limits.MaxPacket,
|
||||
"maxBytesPerSec": n.Limits.MaxBytesPerSec,
|
||||
"maxProbePerSec": n.Limits.MaxProbePerSec,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (n *Node) auth(next http.HandlerFunc) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
if n.Token == "" {
|
||||
next(w, r)
|
||||
return
|
||||
}
|
||||
got := bearer(r.Header.Get("Authorization"))
|
||||
if got == "" || subtle.ConstantTimeCompare([]byte(got), []byte(n.Token)) != 1 {
|
||||
writeErr(w, http.StatusUnauthorized, "unauthorized", "节点口令不正确或未提供")
|
||||
return
|
||||
}
|
||||
next(w, r)
|
||||
}
|
||||
}
|
||||
|
||||
type createReq struct {
|
||||
Target string `json:"target"`
|
||||
Port int `json:"port"`
|
||||
Profile string `json:"profile"`
|
||||
IntervalMs int `json:"intervalMs"`
|
||||
TimeoutMs int `json:"timeoutMs"`
|
||||
DurationSec int `json:"durationSec"`
|
||||
PacketSize int `json:"packetSize"`
|
||||
EchoToken string `json:"echoToken"`
|
||||
DNSName string `json:"dnsName"`
|
||||
PayloadHex string `json:"payloadHex"`
|
||||
ExpectHex string `json:"expectHex"`
|
||||
}
|
||||
|
||||
func (n *Node) create(w http.ResponseWriter, r *http.Request) {
|
||||
var req createReq
|
||||
dec := json.NewDecoder(io.LimitReader(r.Body, 1<<16))
|
||||
if err := dec.Decode(&req); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "bad_request", "请求内容无法解析")
|
||||
return
|
||||
}
|
||||
spec, err := n.prepare(r.Context(), req)
|
||||
if err != nil {
|
||||
var ae *apiError
|
||||
if errors.As(err, &ae) {
|
||||
writeErr(w, ae.status, ae.code, ae.msg)
|
||||
return
|
||||
}
|
||||
writeErr(w, http.StatusBadRequest, "bad_request", "无法创建探测任务")
|
||||
return
|
||||
}
|
||||
select {
|
||||
case n.sem <- struct{}{}:
|
||||
default:
|
||||
writeErr(w, http.StatusTooManyRequests, "busy", "节点同时探测的任务已达上限")
|
||||
return
|
||||
}
|
||||
job, err := n.start(spec)
|
||||
if err != nil {
|
||||
<-n.sem
|
||||
writeErr(w, http.StatusInternalServerError, "error", "任务没有启动")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, map[string]any{
|
||||
"jobId": job.id,
|
||||
"expiresAt": job.expires.UTC().Format(time.RFC3339),
|
||||
"visibility": map[bool]string{true: "public", false: "private"}[n.Public()],
|
||||
})
|
||||
}
|
||||
|
||||
func (n *Node) prepare(ctx context.Context, req createReq) (jobSpec, error) {
|
||||
switch req.Profile {
|
||||
case "nq-tcp", "nq-udp", "tcp-connect", "udp-generic", "dns", "minecraft-java", "minecraft-bedrock", "custom-udp":
|
||||
default:
|
||||
return jobSpec{}, &apiError{http.StatusBadRequest, "bad_profile", "不支持的探测类型"}
|
||||
}
|
||||
if req.Port < 1 || req.Port > 65535 {
|
||||
return jobSpec{}, &apiError{http.StatusBadRequest, "bad_port", "端口需要在 1 到 65535 之间"}
|
||||
}
|
||||
interval := time.Duration(req.IntervalMs) * time.Millisecond
|
||||
if req.IntervalMs == 0 {
|
||||
interval = 500 * time.Millisecond
|
||||
}
|
||||
if interval < n.Limits.MinInterval || interval > 30*time.Second {
|
||||
return jobSpec{}, &apiError{http.StatusBadRequest, "bad_interval", "发送间隔超出节点允许的范围"}
|
||||
}
|
||||
timeout := time.Duration(req.TimeoutMs) * time.Millisecond
|
||||
if req.TimeoutMs == 0 {
|
||||
timeout = 1500 * time.Millisecond
|
||||
}
|
||||
if timeout < 100*time.Millisecond || timeout > 15*time.Second {
|
||||
return jobSpec{}, &apiError{http.StatusBadRequest, "bad_timeout", "超时超出节点允许的范围"}
|
||||
}
|
||||
duration := time.Duration(req.DurationSec) * time.Second
|
||||
if req.DurationSec == 0 {
|
||||
duration = 60 * time.Second
|
||||
}
|
||||
if duration < time.Second || duration > n.Limits.MaxDuration {
|
||||
return jobSpec{}, &apiError{http.StatusBadRequest, "bad_duration", "探测时长超出节点允许的范围"}
|
||||
}
|
||||
size := req.PacketSize
|
||||
if size == 0 {
|
||||
size = 128
|
||||
}
|
||||
if size > n.Limits.MaxPacket {
|
||||
return jobSpec{}, &apiError{http.StatusBadRequest, "bad_size", "报文超过节点允许的大小"}
|
||||
}
|
||||
echo, err := tokenBytes(req.EchoToken)
|
||||
if err != nil {
|
||||
return jobSpec{}, &apiError{http.StatusBadRequest, "bad_token", "目标回显口令最长 32 字节"}
|
||||
}
|
||||
var payload, expect []byte
|
||||
if req.Profile == "custom-udp" {
|
||||
payload, err = decodeHex(req.PayloadHex)
|
||||
if err != nil || len(payload) == 0 || len(payload) > n.Limits.MaxPacket {
|
||||
return jobSpec{}, &apiError{http.StatusBadRequest, "bad_payload", "自定义载荷需要是不超过上限的十六进制"}
|
||||
}
|
||||
if req.ExpectHex != "" {
|
||||
expect, err = decodeHex(req.ExpectHex)
|
||||
if err != nil {
|
||||
return jobSpec{}, &apiError{http.StatusBadRequest, "bad_payload", "预期响应需要是十六进制"}
|
||||
}
|
||||
}
|
||||
}
|
||||
ip, err := targetOK(ctx, n.Resolver, req.Target, n.AllowPrivate, n.ExtraNets)
|
||||
if err != nil {
|
||||
var dnsErr *net.DNSError
|
||||
if errors.As(err, &dnsErr) {
|
||||
return jobSpec{}, &apiError{http.StatusBadRequest, "dns", "域名无法解析"}
|
||||
}
|
||||
if errors.Is(err, errForbiddenTarget) {
|
||||
return jobSpec{}, &apiError{http.StatusForbidden, "forbidden_target", "远程节点默认不探测本机、内网、链路本地或云元数据地址。管理员开放局域网后才能测这些地址"}
|
||||
}
|
||||
return jobSpec{}, &apiError{http.StatusBadRequest, "bad_target", "目标地址无效"}
|
||||
}
|
||||
return jobSpec{
|
||||
Host: req.Target, Port: req.Port, Profile: req.Profile, IP: ip,
|
||||
Interval: interval, Timeout: timeout, Duration: duration, PacketSize: size,
|
||||
Echo: echo, DNSName: req.DNSName, Payload: payload, Expect: expect,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (n *Node) start(spec jobSpec) (*probeJob, error) {
|
||||
p, err := newProber(spec)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
id, err := newID()
|
||||
if err != nil {
|
||||
_ = p.Close()
|
||||
return nil, err
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), spec.Duration)
|
||||
job := &probeJob{
|
||||
id: id,
|
||||
expires: time.Now().Add(spec.Duration),
|
||||
cancel: cancel,
|
||||
events: make(chan sampleMsg, 64),
|
||||
attach: make(chan struct{}),
|
||||
done: make(chan struct{}),
|
||||
}
|
||||
n.mu.Lock()
|
||||
n.jobs[id] = job
|
||||
n.mu.Unlock()
|
||||
go n.run(ctx, job, spec, p)
|
||||
go n.attachDeadline(job)
|
||||
return job, nil
|
||||
}
|
||||
|
||||
func (n *Node) attachDeadline(job *probeJob) {
|
||||
select {
|
||||
case <-job.attach:
|
||||
case <-job.done:
|
||||
case <-time.After(15 * time.Second):
|
||||
n.Stop(job.id)
|
||||
}
|
||||
}
|
||||
|
||||
func (n *Node) run(ctx context.Context, job *probeJob, spec jobSpec, p prober) {
|
||||
defer func() {
|
||||
_ = p.Close()
|
||||
job.finish()
|
||||
n.mu.Lock()
|
||||
delete(n.jobs, job.id)
|
||||
n.mu.Unlock()
|
||||
<-n.sem
|
||||
}()
|
||||
book := &sampleBook{profile: spec.Profile}
|
||||
seq := 0
|
||||
emit := func(o Outcome) {
|
||||
book.add(o)
|
||||
seq++
|
||||
msg := sampleMsg{
|
||||
Seq: seq, Status: o.Status, Kind: o.Kind, Note: o.Note,
|
||||
Detail: o.Detail, Summary: book.summary(),
|
||||
}
|
||||
if o.HasRtt {
|
||||
ms := float64(o.Rtt) / float64(time.Millisecond)
|
||||
msg.RttMs = &ms
|
||||
}
|
||||
if book.jitter.has && o.Status == statusOK {
|
||||
v := book.jitter.value
|
||||
msg.JitterMs = &v
|
||||
}
|
||||
job.mu.Lock()
|
||||
job.last = msg
|
||||
job.mu.Unlock()
|
||||
select {
|
||||
case job.events <- msg:
|
||||
case <-ctx.Done():
|
||||
}
|
||||
}
|
||||
for {
|
||||
if err := n.pace.wait(ctx, spec.PacketSize); err != nil {
|
||||
return
|
||||
}
|
||||
started := time.Now()
|
||||
pctx, cancel := context.WithTimeout(ctx, spec.Timeout)
|
||||
out := p.Probe(pctx)
|
||||
cancel()
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
emit(out)
|
||||
wait := spec.Interval - time.Since(started)
|
||||
if wait < 0 {
|
||||
wait = 0
|
||||
}
|
||||
timer := time.NewTimer(wait)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
timer.Stop()
|
||||
return
|
||||
case <-timer.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (n *Node) snapshot(w http.ResponseWriter, r *http.Request) {
|
||||
job := n.get(r.PathValue("id"))
|
||||
if job == nil {
|
||||
writeErr(w, http.StatusNotFound, "not_found", "任务不存在或已结束")
|
||||
return
|
||||
}
|
||||
job.mu.Lock()
|
||||
last := job.last
|
||||
job.mu.Unlock()
|
||||
if last.Seq == 0 && last.Status == "" {
|
||||
last = sampleMsg{Status: "pending", Summary: summaryMsg{Pending: 1}}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, last)
|
||||
}
|
||||
|
||||
func (n *Node) stream(w http.ResponseWriter, r *http.Request) {
|
||||
job := n.get(r.PathValue("id"))
|
||||
if job == nil {
|
||||
writeErr(w, http.StatusNotFound, "not_found", "任务不存在或已结束")
|
||||
return
|
||||
}
|
||||
flusher, ok := w.(http.Flusher)
|
||||
if !ok {
|
||||
writeErr(w, http.StatusInternalServerError, "error", "服务器不支持流式输出")
|
||||
return
|
||||
}
|
||||
job.attachOnce.Do(func() { close(job.attach) })
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
w.Header().Set("Cache-Control", "no-cache")
|
||||
w.Header().Set("X-Accel-Buffering", "no")
|
||||
defer n.Stop(job.id)
|
||||
for {
|
||||
select {
|
||||
case <-r.Context().Done():
|
||||
return
|
||||
case msg, open := <-job.events:
|
||||
if !open {
|
||||
fmt.Fprintf(w, "event: end\ndata: {}\n\n")
|
||||
flusher.Flush()
|
||||
return
|
||||
}
|
||||
raw, _ := json.Marshal(msg)
|
||||
fmt.Fprintf(w, "event: sample\ndata: %s\n\n", raw)
|
||||
flusher.Flush()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (n *Node) remove(w http.ResponseWriter, r *http.Request) {
|
||||
if !n.Stop(r.PathValue("id")) {
|
||||
writeErr(w, http.StatusNotFound, "not_found", "任务不存在或已结束")
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (n *Node) get(id string) *probeJob {
|
||||
n.mu.Lock()
|
||||
defer n.mu.Unlock()
|
||||
return n.jobs[id]
|
||||
}
|
||||
|
||||
func (n *Node) Stop(id string) bool {
|
||||
n.mu.Lock()
|
||||
job := n.jobs[id]
|
||||
n.mu.Unlock()
|
||||
if job == nil {
|
||||
return false
|
||||
}
|
||||
job.cancel()
|
||||
return true
|
||||
}
|
||||
|
||||
func (n *Node) reap() {
|
||||
t := time.NewTicker(time.Second)
|
||||
defer t.Stop()
|
||||
for range t.C {
|
||||
now := time.Now()
|
||||
n.mu.Lock()
|
||||
var expired []string
|
||||
for id, job := range n.jobs {
|
||||
if now.After(job.expires) {
|
||||
expired = append(expired, id)
|
||||
}
|
||||
}
|
||||
n.mu.Unlock()
|
||||
for _, id := range expired {
|
||||
n.Stop(id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (n *Node) jobCount() int {
|
||||
n.mu.Lock()
|
||||
defer n.mu.Unlock()
|
||||
return len(n.jobs)
|
||||
}
|
||||
|
||||
type probeJob struct {
|
||||
id string
|
||||
expires time.Time
|
||||
cancel context.CancelFunc
|
||||
events chan sampleMsg
|
||||
attach chan struct{}
|
||||
attachOnce sync.Once
|
||||
mu sync.Mutex
|
||||
last sampleMsg
|
||||
once sync.Once
|
||||
done chan struct{}
|
||||
}
|
||||
|
||||
func (j *probeJob) finish() {
|
||||
j.once.Do(func() {
|
||||
close(j.events)
|
||||
close(j.done)
|
||||
})
|
||||
}
|
||||
|
||||
func newID() (string, error) {
|
||||
var b [16]byte
|
||||
if _, err := rand.Read(b[:]); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return hex.EncodeToString(b[:]), nil
|
||||
}
|
||||
|
||||
func bearer(h string) string {
|
||||
const p = "Bearer "
|
||||
if len(h) < len(p) || !strings.EqualFold(h[:len(p)], p) {
|
||||
return ""
|
||||
}
|
||||
return strings.TrimSpace(h[len(p):])
|
||||
}
|
||||
|
||||
func decodeHex(s string) ([]byte, error) {
|
||||
s = strings.TrimSpace(s)
|
||||
s = strings.ReplaceAll(s, " ", "")
|
||||
if len(s)%2 == 1 {
|
||||
return nil, errors.New("odd hex")
|
||||
}
|
||||
return hex.DecodeString(s)
|
||||
}
|
||||
|
||||
type apiError struct {
|
||||
status int
|
||||
code string
|
||||
msg string
|
||||
}
|
||||
|
||||
func (e *apiError) Error() string { return e.msg }
|
||||
|
||||
func writeErr(w http.ResponseWriter, status int, code, msg string) {
|
||||
writeJSON(w, status, map[string]string{"error": code, "message": msg})
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, status int, body any) {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(body)
|
||||
}
|
||||
|
||||
type paced struct {
|
||||
mu sync.Mutex
|
||||
probes int
|
||||
bytes int
|
||||
window time.Time
|
||||
maxProbe int
|
||||
maxBytes int
|
||||
}
|
||||
|
||||
func newPaced(maxProbe, maxBytes int) *paced {
|
||||
return &paced{maxProbe: maxProbe, maxBytes: maxBytes, window: time.Now()}
|
||||
}
|
||||
|
||||
func (p *paced) wait(ctx context.Context, packet int) error {
|
||||
if packet < 1 {
|
||||
packet = 1
|
||||
}
|
||||
for {
|
||||
p.mu.Lock()
|
||||
now := time.Now()
|
||||
if now.Sub(p.window) >= time.Second {
|
||||
p.window = now
|
||||
p.probes = 0
|
||||
p.bytes = 0
|
||||
}
|
||||
if p.probes < p.maxProbe && p.bytes+packet <= p.maxBytes {
|
||||
p.probes++
|
||||
p.bytes += packet
|
||||
p.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
wait := time.Second - now.Sub(p.window)
|
||||
p.mu.Unlock()
|
||||
if wait < 10*time.Millisecond {
|
||||
wait = 10 * time.Millisecond
|
||||
}
|
||||
timer := time.NewTimer(wait)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
timer.Stop()
|
||||
return ctx.Err()
|
||||
case <-timer.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,587 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestSafetyBlocksPrivateAndMetadata(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
cases := []string{"127.0.0.1", "10.1.2.3", "192.168.1.1", "169.254.169.254", "169.254.1.1", "::1", "metadata.google.internal", "localhost"}
|
||||
for _, host := range cases {
|
||||
if _, err := targetOK(ctx, nil, host, false, nil); !errors.Is(err, errForbiddenTarget) {
|
||||
t.Fatalf("%s: got %v", host, err)
|
||||
}
|
||||
}
|
||||
if _, err := targetOK(ctx, nil, "169.254.169.254", true, nil); !errors.Is(err, errForbiddenTarget) {
|
||||
t.Fatalf("metadata must stay blocked with allow-private: %v", err)
|
||||
}
|
||||
if _, err := targetOK(ctx, nil, "127.0.0.1", true, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, n, _ := net.ParseCIDR("10.1.2.0/24")
|
||||
ip, err := targetOK(ctx, nil, "10.1.2.9", false, []*net.IPNet{n})
|
||||
if err != nil || !ip.Equal(net.ParseIP("10.1.2.9")) {
|
||||
t.Fatalf("allow net: %v %v", ip, err)
|
||||
}
|
||||
_, err = targetOK(ctx, nil, "10.9.9.9", false, []*net.IPNet{n})
|
||||
if !errors.Is(err, errForbiddenTarget) {
|
||||
t.Fatalf("outside allow net: %v", err)
|
||||
}
|
||||
if _, err := targetOK(ctx, nil, "1.1.1.1", false, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rebinding := stubResolver{[]net.IP{net.ParseIP("1.1.1.1"), net.ParseIP("10.0.0.1")}}
|
||||
if _, err := targetOK(ctx, rebinding, "example.com", false, nil); !errors.Is(err, errForbiddenTarget) {
|
||||
t.Fatalf("rebinding: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
type stubResolver struct{ ips []net.IP }
|
||||
|
||||
func (s stubResolver) LookupIPAddr(context.Context, string) ([]net.IPAddr, error) {
|
||||
out := make([]net.IPAddr, len(s.ips))
|
||||
for i, ip := range s.ips {
|
||||
out[i] = net.IPAddr{IP: ip}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func TestPublicAndPrivateAuth(t *testing.T) {
|
||||
public := httptest.NewServer(newNode("", true, nil, testLimits()).Handler())
|
||||
defer public.Close()
|
||||
res, err := http.Post(public.URL+"/v1/jobs", "application/json", strings.NewReader(`{"target":"127.0.0.1","port":1,"profile":"tcp-connect","durationSec":1,"intervalMs":200,"timeoutMs":200}`))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
res.Body.Close()
|
||||
if res.StatusCode != http.StatusCreated {
|
||||
t.Fatalf("public status %d", res.StatusCode)
|
||||
}
|
||||
info, err := http.Get(public.URL + "/v1/info")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer info.Body.Close()
|
||||
var body map[string]any
|
||||
if err := json.NewDecoder(info.Body).Decode(&body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if body["visibility"] != "public" || body["authRequired"] != false {
|
||||
t.Fatalf("info %+v", body)
|
||||
}
|
||||
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer ln.Close()
|
||||
var accepted atomic.Int32
|
||||
go func() {
|
||||
for {
|
||||
c, err := ln.Accept()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
accepted.Add(1)
|
||||
c.Close()
|
||||
}
|
||||
}()
|
||||
port := ln.Addr().(*net.TCPAddr).Port
|
||||
private := httptest.NewServer(newNode("secret-token", true, nil, testLimits()).Handler())
|
||||
defer private.Close()
|
||||
payload := `{"target":"127.0.0.1","port":` + itoa(port) + `,"profile":"tcp-connect","durationSec":2,"intervalMs":200,"timeoutMs":300}`
|
||||
post := func(token string) *http.Response {
|
||||
t.Helper()
|
||||
req, err := http.NewRequest(http.MethodPost, private.URL+"/v1/jobs", strings.NewReader(payload))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
if token != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
}
|
||||
res, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
res.Body.Close()
|
||||
return res
|
||||
}
|
||||
if post("").StatusCode != http.StatusUnauthorized {
|
||||
t.Fatal("missing token was accepted")
|
||||
}
|
||||
if post("wrong").StatusCode != http.StatusUnauthorized {
|
||||
t.Fatal("wrong token was accepted")
|
||||
}
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
if accepted.Load() != 0 {
|
||||
t.Fatalf("auth failure dialed the target %d times", accepted.Load())
|
||||
}
|
||||
if post("secret-token").StatusCode != http.StatusCreated {
|
||||
t.Fatal("good token was rejected")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNodeNQAndTCPAndUDP(t *testing.T) {
|
||||
tcpLn, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
udpConn, err := net.ListenUDP("udp", &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1)})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
echo := &Server{}
|
||||
go echo.ServeTCP(tcpLn)
|
||||
go echo.ServeUDP(udpConn)
|
||||
defer echo.Close()
|
||||
|
||||
node := newNode("", true, nil, testLimits())
|
||||
srv := httptest.NewServer(node.Handler())
|
||||
defer srv.Close()
|
||||
|
||||
tcpPort := tcpLn.Addr().(*net.TCPAddr).Port
|
||||
udpPort := udpConn.LocalAddr().(*net.UDPAddr).Port
|
||||
tcpJob := createJob(t, srv.URL, "", map[string]any{
|
||||
"target": "127.0.0.1", "port": tcpPort, "profile": "nq-tcp",
|
||||
"intervalMs": 200, "timeoutMs": 800, "durationSec": 3, "packetSize": 80,
|
||||
})
|
||||
sample := readOneSample(t, srv.URL, "", tcpJob)
|
||||
if sample.Status != statusOK || sample.RttMs == nil || *sample.RttMs <= 0 {
|
||||
t.Fatalf("nq tcp %+v", sample)
|
||||
}
|
||||
if sample.Summary.ProbeLossPct == nil || *sample.Summary.ProbeLossPct != 0 {
|
||||
t.Fatalf("loss %+v", sample.Summary)
|
||||
}
|
||||
|
||||
udpJob := createJob(t, srv.URL, "", map[string]any{
|
||||
"target": "127.0.0.1", "port": udpPort, "profile": "nq-udp",
|
||||
"intervalMs": 200, "timeoutMs": 800, "durationSec": 3, "packetSize": 80,
|
||||
})
|
||||
sample = readOneSample(t, srv.URL, "", udpJob)
|
||||
if sample.Status != statusOK || sample.RttMs == nil || *sample.RttMs <= 0 {
|
||||
t.Fatalf("nq udp %+v", sample)
|
||||
}
|
||||
|
||||
okJob := createJob(t, srv.URL, "", map[string]any{
|
||||
"target": "127.0.0.1", "port": tcpPort, "profile": "tcp-connect",
|
||||
"intervalMs": 200, "timeoutMs": 800, "durationSec": 2,
|
||||
})
|
||||
sample = readOneSample(t, srv.URL, "", okJob)
|
||||
if sample.Status != statusOK || sample.Kind != kindConnect {
|
||||
t.Fatalf("tcp connect %+v", sample)
|
||||
}
|
||||
|
||||
refused := createJob(t, srv.URL, "", map[string]any{
|
||||
"target": "127.0.0.1", "port": 1, "profile": "tcp-connect",
|
||||
"intervalMs": 200, "timeoutMs": 400, "durationSec": 2,
|
||||
})
|
||||
sample = readOneSample(t, srv.URL, "", refused)
|
||||
if sample.Status != statusRefused || sample.Summary.FailurePct == nil || *sample.Summary.FailurePct != 100 {
|
||||
t.Fatalf("refused %+v", sample)
|
||||
}
|
||||
if sample.Summary.ProbeLossPct != nil {
|
||||
t.Fatalf("tcp connect must not report probe loss %+v", sample.Summary)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenericUDPUnknownAndEcho(t *testing.T) {
|
||||
blackhole, err := net.ListenUDP("udp", &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1)})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer blackhole.Close()
|
||||
go func() {
|
||||
buf := make([]byte, 64)
|
||||
for {
|
||||
_, _, err := blackhole.ReadFromUDP(buf)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
node := httptest.NewServer(newNode("", true, nil, testLimits()).Handler())
|
||||
defer node.Close()
|
||||
id := createJob(t, node.URL, "", map[string]any{
|
||||
"target": "127.0.0.1", "port": blackhole.LocalAddr().(*net.UDPAddr).Port,
|
||||
"profile": "udp-generic", "intervalMs": 200, "timeoutMs": 250, "durationSec": 2, "packetSize": 16,
|
||||
})
|
||||
sample := readOneSample(t, node.URL, "", id)
|
||||
if sample.Status != statusUnknown || sample.Summary.ProbeLossPct != nil {
|
||||
t.Fatalf("unknown %+v", sample)
|
||||
}
|
||||
if sample.Summary.UnknownPct == nil || *sample.Summary.UnknownPct != 100 {
|
||||
t.Fatalf("unknown pct %+v", sample.Summary)
|
||||
}
|
||||
|
||||
echo, err := net.ListenUDP("udp", &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1)})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer echo.Close()
|
||||
go func() {
|
||||
buf := make([]byte, 256)
|
||||
for {
|
||||
n, addr, err := echo.ReadFromUDP(buf)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
_, _ = echo.WriteToUDP(append([]byte(nil), buf[:n]...), addr)
|
||||
}
|
||||
}()
|
||||
id = createJob(t, node.URL, "", map[string]any{
|
||||
"target": "127.0.0.1", "port": echo.LocalAddr().(*net.UDPAddr).Port,
|
||||
"profile": "custom-udp", "intervalMs": 200, "timeoutMs": 800, "durationSec": 2,
|
||||
"payloadHex": "0102", "expectHex": "0102",
|
||||
})
|
||||
sample = readOneSample(t, node.URL, "", id)
|
||||
if sample.Status != statusOK || sample.RttMs == nil {
|
||||
t.Fatalf("custom echo %+v", sample)
|
||||
}
|
||||
id = createJob(t, node.URL, "", map[string]any{
|
||||
"target": "127.0.0.1", "port": echo.LocalAddr().(*net.UDPAddr).Port,
|
||||
"profile": "custom-udp", "intervalMs": 200, "timeoutMs": 400, "durationSec": 2,
|
||||
"payloadHex": "0102", "expectHex": "ffff",
|
||||
})
|
||||
sample = readOneSample(t, node.URL, "", id)
|
||||
if sample.Status != statusProtocol {
|
||||
t.Fatalf("mismatch %+v", sample)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMinecraftJavaAndBedrockFixtures(t *testing.T) {
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer ln.Close()
|
||||
go serveFakeJava(ln)
|
||||
udp, err := net.ListenUDP("udp", &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1)})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer udp.Close()
|
||||
go serveFakeBedrock(udp, true)
|
||||
|
||||
node := httptest.NewServer(newNode("", true, nil, testLimits()).Handler())
|
||||
defer node.Close()
|
||||
id := createJob(t, node.URL, "", map[string]any{
|
||||
"target": "127.0.0.1", "port": ln.Addr().(*net.TCPAddr).Port,
|
||||
"profile": "minecraft-java", "intervalMs": 200, "timeoutMs": 1000, "durationSec": 3,
|
||||
})
|
||||
sample := readOneSample(t, node.URL, "", id)
|
||||
if sample.Status != statusOK || sample.Detail["motd"] != "Hello" || sample.Detail["version"] != "1.21.1" || sample.Detail["players"] != "3/20" {
|
||||
t.Fatalf("java %+v", sample)
|
||||
}
|
||||
if sample.RttMs == nil || *sample.RttMs < 0 || sample.Summary.FailurePct == nil || *sample.Summary.FailurePct != 0 {
|
||||
t.Fatalf("java rtt %+v", sample)
|
||||
}
|
||||
|
||||
id = createJob(t, node.URL, "", map[string]any{
|
||||
"target": "127.0.0.1", "port": udp.LocalAddr().(*net.UDPAddr).Port,
|
||||
"profile": "minecraft-bedrock", "intervalMs": 200, "timeoutMs": 1000, "durationSec": 3,
|
||||
})
|
||||
sample = readOneSample(t, node.URL, "", id)
|
||||
if sample.Status != statusOK || sample.Detail["motd"] != "Bed" || sample.RttMs == nil {
|
||||
t.Fatalf("bedrock %+v", sample)
|
||||
}
|
||||
|
||||
bad, err := net.ListenUDP("udp", &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1)})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer bad.Close()
|
||||
go serveFakeBedrock(bad, false)
|
||||
id = createJob(t, node.URL, "", map[string]any{
|
||||
"target": "127.0.0.1", "port": bad.LocalAddr().(*net.UDPAddr).Port,
|
||||
"profile": "minecraft-bedrock", "intervalMs": 200, "timeoutMs": 400, "durationSec": 2,
|
||||
})
|
||||
sample = readOneSample(t, node.URL, "", id)
|
||||
if sample.Status != statusProtocol {
|
||||
t.Fatalf("bad magic %+v", sample)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDNSAndDeleteAndLimits(t *testing.T) {
|
||||
dns, err := net.ListenUDP("udp", &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1)})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer dns.Close()
|
||||
go func() {
|
||||
buf := make([]byte, 512)
|
||||
for {
|
||||
n, addr, err := dns.ReadFromUDP(buf)
|
||||
if err != nil || n < 2 {
|
||||
return
|
||||
}
|
||||
reply := []byte{buf[0], buf[1], 0x81, 0x80, 0, 1, 0, 0, 0, 0, 0, 0}
|
||||
_, _ = dns.WriteToUDP(reply, addr)
|
||||
}
|
||||
}()
|
||||
limits := testLimits()
|
||||
limits.MaxJobs = 1
|
||||
node := newNode("", true, nil, limits)
|
||||
srv := httptest.NewServer(node.Handler())
|
||||
defer srv.Close()
|
||||
id := createJob(t, srv.URL, "", map[string]any{
|
||||
"target": "127.0.0.1", "port": dns.LocalAddr().(*net.UDPAddr).Port,
|
||||
"profile": "dns", "dnsName": "example.com", "intervalMs": 200, "timeoutMs": 800, "durationSec": 5,
|
||||
})
|
||||
res, err := http.Post(srv.URL+"/v1/jobs", "application/json", strings.NewReader(`{"target":"127.0.0.1","port":9,"profile":"tcp-connect","durationSec":5,"intervalMs":200,"timeoutMs":200}`))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
res.Body.Close()
|
||||
if res.StatusCode != http.StatusTooManyRequests {
|
||||
t.Fatalf("limit status %d", res.StatusCode)
|
||||
}
|
||||
del, err := http.NewRequest(http.MethodDelete, srv.URL+"/v1/jobs/"+id, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
res, err = http.DefaultClient.Do(del)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
res.Body.Close()
|
||||
if res.StatusCode != http.StatusNoContent {
|
||||
t.Fatalf("delete %d", res.StatusCode)
|
||||
}
|
||||
deadline := time.Now().Add(2 * time.Second)
|
||||
for node.jobCount() != 0 && time.Now().Before(deadline) {
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
}
|
||||
if node.jobCount() != 0 {
|
||||
t.Fatalf("job still running: %d", node.jobCount())
|
||||
}
|
||||
again := createJob(t, srv.URL, "", map[string]any{
|
||||
"target": "127.0.0.1", "port": dns.LocalAddr().(*net.UDPAddr).Port,
|
||||
"profile": "dns", "dnsName": "example.com", "intervalMs": 200, "timeoutMs": 800, "durationSec": 3,
|
||||
})
|
||||
sample := readOneSample(t, srv.URL, "", again)
|
||||
if sample.Status != statusOK || sample.RttMs == nil {
|
||||
t.Fatalf("dns %+v", sample)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBookIgnoresPendingAndNQConnectFailure(t *testing.T) {
|
||||
b := &sampleBook{profile: "nq-tcp"}
|
||||
s := b.summary()
|
||||
if s.ProbeLossPct != nil || s.Completed != 0 {
|
||||
t.Fatalf("empty book %+v", s)
|
||||
}
|
||||
b.add(Outcome{Status: statusRefused, Kind: kindConnect, Reconnect: true})
|
||||
s = b.summary()
|
||||
if s.ProbeLossPct != nil || s.Reconnects != 1 {
|
||||
t.Fatalf("connect failure counted as loss %+v", s)
|
||||
}
|
||||
b.add(Outcome{Status: statusTimeout, Kind: kindProbe})
|
||||
b.add(Outcome{Status: statusOK, Kind: kindProbe, HasRtt: true, Rtt: time.Millisecond})
|
||||
s = b.summary()
|
||||
if s.ProbeLossPct == nil || *s.ProbeLossPct != 50 {
|
||||
t.Fatalf("probe loss %+v", s)
|
||||
}
|
||||
u := &sampleBook{profile: "udp-generic"}
|
||||
u.add(Outcome{Status: statusUnknown, Kind: kindQuery})
|
||||
if u.summary().ProbeLossPct != nil || u.summary().UnknownPct == nil {
|
||||
t.Fatalf("unknown %+v", u.summary())
|
||||
}
|
||||
}
|
||||
|
||||
func TestLateUDPReplyIgnored(t *testing.T) {
|
||||
echo, err := net.ListenUDP("udp", &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1)})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer echo.Close()
|
||||
go func() {
|
||||
buf := make([]byte, 2048)
|
||||
for {
|
||||
n, addr, err := echo.ReadFromUDP(buf)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
pkt, err := ParsePacket(append([]byte(nil), buf[:n]...))
|
||||
if err != nil || pkt.Type != typeRequest {
|
||||
continue
|
||||
}
|
||||
pkt.Type = typeReply
|
||||
pkt.ServerUnixNano = uint64(time.Now().UnixNano())
|
||||
raw, err := pkt.Marshal()
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
seq := pkt.Sequence
|
||||
dest := &net.UDPAddr{IP: append(net.IP(nil), addr.IP...), Port: addr.Port}
|
||||
go func(seq uint32, raw []byte, dest *net.UDPAddr) {
|
||||
if seq == 1 {
|
||||
time.Sleep(400 * time.Millisecond)
|
||||
}
|
||||
_, _ = echo.WriteToUDP(raw, dest)
|
||||
}(seq, raw, dest)
|
||||
}
|
||||
}()
|
||||
p := &nqUDP{spec: jobSpec{
|
||||
IP: net.IPv4(127, 0, 0, 1), Port: echo.LocalAddr().(*net.UDPAddr).Port,
|
||||
Timeout: 150 * time.Millisecond, PacketSize: 80,
|
||||
}}
|
||||
defer p.Close()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
|
||||
defer cancel()
|
||||
first := p.Probe(ctx)
|
||||
if first.Status != statusTimeout {
|
||||
t.Fatalf("first %+v", first)
|
||||
}
|
||||
second := p.Probe(ctx)
|
||||
if second.Status != statusOK {
|
||||
t.Fatalf("second %+v", second)
|
||||
}
|
||||
}
|
||||
|
||||
func testLimits() Limits {
|
||||
l := defaultLimits()
|
||||
l.MaxJobs = 4
|
||||
l.MinInterval = 200 * time.Millisecond
|
||||
l.MaxDuration = 10 * time.Second
|
||||
return l
|
||||
}
|
||||
|
||||
func createJob(t *testing.T, base, token string, body map[string]any) string {
|
||||
t.Helper()
|
||||
raw, _ := json.Marshal(body)
|
||||
req, err := http.NewRequest(http.MethodPost, base+"/v1/jobs", strings.NewReader(string(raw)))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
if token != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
}
|
||||
res, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer res.Body.Close()
|
||||
if res.StatusCode != http.StatusCreated {
|
||||
b, _ := io.ReadAll(res.Body)
|
||||
t.Fatalf("create %d %s", res.StatusCode, b)
|
||||
}
|
||||
var out struct {
|
||||
JobID string `json:"jobId"`
|
||||
}
|
||||
if err := json.NewDecoder(res.Body).Decode(&out); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if out.JobID == "" {
|
||||
t.Fatal("empty job id")
|
||||
}
|
||||
return out.JobID
|
||||
}
|
||||
|
||||
func readOneSample(t *testing.T, base, token, id string) sampleMsg {
|
||||
t.Helper()
|
||||
req, err := http.NewRequest(http.MethodGet, base+"/v1/jobs/"+id+"/stream", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if token != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 4*time.Second)
|
||||
defer cancel()
|
||||
req = req.WithContext(ctx)
|
||||
res, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer res.Body.Close()
|
||||
if res.StatusCode != http.StatusOK {
|
||||
b, _ := io.ReadAll(res.Body)
|
||||
t.Fatalf("stream %d %s", res.StatusCode, b)
|
||||
}
|
||||
sc := bufio.NewScanner(res.Body)
|
||||
for sc.Scan() {
|
||||
line := sc.Text()
|
||||
if !strings.HasPrefix(line, "data: ") {
|
||||
continue
|
||||
}
|
||||
var msg sampleMsg
|
||||
if err := json.Unmarshal([]byte(strings.TrimPrefix(line, "data: ")), &msg); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if msg.Status == "" || msg.Status == "pending" {
|
||||
continue
|
||||
}
|
||||
return msg
|
||||
}
|
||||
t.Fatal(sc.Err())
|
||||
return sampleMsg{}
|
||||
}
|
||||
|
||||
func serveFakeJava(ln net.Listener) {
|
||||
for {
|
||||
c, err := ln.Accept()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
go func(conn net.Conn) {
|
||||
defer conn.Close()
|
||||
r := bufio.NewReader(conn)
|
||||
if _, err := readMC(r); err != nil {
|
||||
return
|
||||
}
|
||||
if _, err := readMC(r); err != nil {
|
||||
return
|
||||
}
|
||||
status := []byte(`{"version":{"name":"1.21.1","protocol":767},"players":{"online":3,"max":20},"description":{"text":"Hello"}}`)
|
||||
payload := appendMCString([]byte{0x00}, string(status))
|
||||
if err := writeMC(conn, payload); err != nil {
|
||||
return
|
||||
}
|
||||
ping, err := readMC(r)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
_ = writeMC(conn, ping)
|
||||
}(c)
|
||||
}
|
||||
}
|
||||
|
||||
func serveFakeBedrock(conn *net.UDPConn, good bool) {
|
||||
buf := make([]byte, 1500)
|
||||
for {
|
||||
n, addr, err := conn.ReadFromUDP(buf)
|
||||
if err != nil || n < 33 {
|
||||
return
|
||||
}
|
||||
ts := binary.BigEndian.Uint64(buf[1:9])
|
||||
motd := "MCPE;Bed;844;1.21.50;1;10;0;world;Survival;1;19132;0;"
|
||||
body := make([]byte, 1+8+8+16+2+len(motd))
|
||||
body[0] = 0x1c
|
||||
binary.BigEndian.PutUint64(body[1:9], ts)
|
||||
binary.BigEndian.PutUint64(body[9:17], 99)
|
||||
copy(body[17:33], rakMagic)
|
||||
if !good {
|
||||
body[17] = 0x11
|
||||
}
|
||||
binary.BigEndian.PutUint16(body[33:35], uint16(len(motd)))
|
||||
copy(body[35:], motd)
|
||||
_, _ = conn.WriteToUDP(body, addr)
|
||||
}
|
||||
}
|
||||
|
||||
func itoa(n int) string { return strconv.Itoa(n) }
|
||||
@@ -0,0 +1,721 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"strconv"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
type prober interface {
|
||||
Probe(ctx context.Context) Outcome
|
||||
Close() error
|
||||
}
|
||||
|
||||
func newProber(spec jobSpec) (prober, error) {
|
||||
switch spec.Profile {
|
||||
case "nq-tcp":
|
||||
return &nqTCP{spec: spec}, nil
|
||||
case "nq-udp":
|
||||
return &nqUDP{spec: spec}, nil
|
||||
case "tcp-connect":
|
||||
return &tcpConnect{spec: spec}, nil
|
||||
case "udp-generic":
|
||||
return &udpQuery{spec: spec, generic: true}, nil
|
||||
case "custom-udp":
|
||||
return &udpQuery{spec: spec}, nil
|
||||
case "dns":
|
||||
return &dnsQuery{spec: spec}, nil
|
||||
case "minecraft-java":
|
||||
return &mcJava{spec: spec}, nil
|
||||
case "minecraft-bedrock":
|
||||
return &mcBedrock{spec: spec}, nil
|
||||
default:
|
||||
return nil, fmt.Errorf("unknown profile %q", spec.Profile)
|
||||
}
|
||||
}
|
||||
|
||||
func dialTCP(ctx context.Context, ip net.IP, port int) (net.Conn, error) {
|
||||
network := "tcp4"
|
||||
if ip.To4() == nil {
|
||||
network = "tcp6"
|
||||
}
|
||||
var d net.Dialer
|
||||
return d.DialContext(ctx, network, net.JoinHostPort(ip.String(), strconv.Itoa(port)))
|
||||
}
|
||||
|
||||
func dialUDP(ip net.IP, port int) (*net.UDPConn, error) {
|
||||
network := "udp4"
|
||||
if ip.To4() == nil {
|
||||
network = "udp6"
|
||||
}
|
||||
raddr, err := net.ResolveUDPAddr(network, net.JoinHostPort(ip.String(), strconv.Itoa(port)))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var laddr *net.UDPAddr
|
||||
if ip.To4() != nil {
|
||||
laddr = &net.UDPAddr{IP: net.IPv4zero, Port: 0}
|
||||
} else {
|
||||
laddr = &net.UDPAddr{IP: net.IPv6zero, Port: 0}
|
||||
}
|
||||
return net.DialUDP(network, laddr, raddr)
|
||||
}
|
||||
|
||||
func classifyDial(err error) Outcome {
|
||||
if err == nil {
|
||||
return Outcome{Status: statusOK, Kind: kindConnect}
|
||||
}
|
||||
if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) {
|
||||
return Outcome{Status: statusTimeout, Kind: kindConnect, Note: "连接超时"}
|
||||
}
|
||||
var dnsErr *net.DNSError
|
||||
if errors.As(err, &dnsErr) {
|
||||
return Outcome{Status: statusDNS, Kind: kindConnect, Note: "域名无法解析"}
|
||||
}
|
||||
if errors.Is(err, syscall.ECONNREFUSED) {
|
||||
return Outcome{Status: statusRefused, Kind: kindConnect, Note: "连接被拒绝"}
|
||||
}
|
||||
var ne net.Error
|
||||
if errors.As(err, &ne) && ne.Timeout() {
|
||||
return Outcome{Status: statusTimeout, Kind: kindConnect, Note: "连接超时"}
|
||||
}
|
||||
return Outcome{Status: statusError, Kind: kindConnect, Note: "连接失败"}
|
||||
}
|
||||
|
||||
func nqPacket(seq uint32, token [tokenLen]byte, size int) ([]byte, error) {
|
||||
if size < headerSize {
|
||||
size = headerSize
|
||||
}
|
||||
if size > 1400 {
|
||||
size = 1400
|
||||
}
|
||||
p := Packet{
|
||||
Version: protocolVer,
|
||||
Type: typeRequest,
|
||||
Sequence: seq,
|
||||
ClientSendUnixNano: uint64(time.Now().UnixNano()),
|
||||
Token: token,
|
||||
Payload: make([]byte, size-headerSize),
|
||||
}
|
||||
return p.Marshal()
|
||||
}
|
||||
|
||||
type nqTCP struct {
|
||||
spec jobSpec
|
||||
conn net.Conn
|
||||
reader *bufio.Reader
|
||||
seq uint32
|
||||
}
|
||||
|
||||
func (p *nqTCP) Close() error {
|
||||
if p.conn != nil {
|
||||
err := p.conn.Close()
|
||||
p.conn = nil
|
||||
p.reader = nil
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *nqTCP) dial(ctx context.Context) error {
|
||||
conn, err := dialTCP(ctx, p.spec.IP, p.spec.Port)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if tc, ok := conn.(*net.TCPConn); ok {
|
||||
_ = tc.SetNoDelay(true)
|
||||
}
|
||||
p.conn = conn
|
||||
p.reader = bufio.NewReaderSize(conn, headerSize+maxPayloadSize)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *nqTCP) Probe(ctx context.Context) Outcome {
|
||||
if p.conn == nil {
|
||||
if err := p.dial(ctx); err != nil {
|
||||
out := classifyDial(err)
|
||||
out.Reconnect = true
|
||||
if out.Note == "" {
|
||||
out.Note = "TCP 反射连接失败,将重试"
|
||||
}
|
||||
return out
|
||||
}
|
||||
}
|
||||
p.seq++
|
||||
raw, err := nqPacket(p.seq, p.spec.Echo, p.spec.PacketSize)
|
||||
if err != nil {
|
||||
return Outcome{Status: statusError, Kind: kindProbe, Note: "无法构造探测包"}
|
||||
}
|
||||
_ = p.conn.SetWriteDeadline(time.Now().Add(p.spec.Timeout))
|
||||
if _, err := p.conn.Write(raw); err != nil {
|
||||
_ = p.Close()
|
||||
return Outcome{Status: statusError, Kind: kindConnect, Reconnect: true, Note: "发送失败,连接将重连"}
|
||||
}
|
||||
start := time.Now()
|
||||
deadline := start.Add(p.spec.Timeout)
|
||||
for {
|
||||
if ctx.Err() != nil {
|
||||
return Outcome{Status: statusTimeout, Kind: kindConnect, Note: "已停止"}
|
||||
}
|
||||
_ = p.conn.SetReadDeadline(deadline)
|
||||
pkt, err := readFrame(p.reader)
|
||||
if err != nil {
|
||||
_ = p.Close()
|
||||
if ne, ok := err.(net.Error); ok && ne.Timeout() || errors.Is(err, context.DeadlineExceeded) {
|
||||
return Outcome{
|
||||
Status: statusTimeout,
|
||||
Kind: kindProbe,
|
||||
Note: "已发出探测,超时前没有收到回显。TCP 会重传,这不是已证实的物理丢包",
|
||||
}
|
||||
}
|
||||
return Outcome{Status: statusError, Kind: kindConnect, Reconnect: true, Note: "连接中断,将重连"}
|
||||
}
|
||||
if pkt.Type != typeReply || pkt.Sequence != p.seq {
|
||||
continue
|
||||
}
|
||||
return Outcome{
|
||||
Status: statusOK,
|
||||
Kind: kindProbe,
|
||||
HasRtt: true,
|
||||
Rtt: time.Since(start),
|
||||
Note: "收到回显",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type nqUDP struct {
|
||||
spec jobSpec
|
||||
conn *net.UDPConn
|
||||
seq uint32
|
||||
}
|
||||
|
||||
func (p *nqUDP) Close() error {
|
||||
if p.conn != nil {
|
||||
err := p.conn.Close()
|
||||
p.conn = nil
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *nqUDP) ensure() error {
|
||||
if p.conn != nil {
|
||||
return nil
|
||||
}
|
||||
c, err := dialUDP(p.spec.IP, p.spec.Port)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
p.conn = c
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *nqUDP) Probe(ctx context.Context) Outcome {
|
||||
if err := p.ensure(); err != nil {
|
||||
return classifyDial(err)
|
||||
}
|
||||
p.seq++
|
||||
raw, err := nqPacket(p.seq, p.spec.Echo, p.spec.PacketSize)
|
||||
if err != nil {
|
||||
return Outcome{Status: statusError, Kind: kindProbe, Note: "无法构造探测包"}
|
||||
}
|
||||
start := time.Now()
|
||||
deadline := start.Add(p.spec.Timeout)
|
||||
_ = p.conn.SetWriteDeadline(deadline)
|
||||
if _, err := p.conn.Write(raw); err != nil {
|
||||
return classifyDial(err)
|
||||
}
|
||||
buf := make([]byte, 2048)
|
||||
sawInvalid := false
|
||||
for {
|
||||
if ctx.Err() != nil {
|
||||
return Outcome{Status: statusUnknown, Kind: kindQuery, Note: "已停止"}
|
||||
}
|
||||
_ = p.conn.SetReadDeadline(deadline)
|
||||
n, err := p.conn.Read(buf)
|
||||
if err != nil {
|
||||
if errors.Is(err, syscall.ECONNREFUSED) {
|
||||
return Outcome{Status: statusRefused, Kind: kindQuery, Note: "目标端口不可达"}
|
||||
}
|
||||
if sawInvalid {
|
||||
return Outcome{Status: statusProtocol, Kind: kindProbe, Note: "收到的 UDP 包不是有效回显"}
|
||||
}
|
||||
return Outcome{
|
||||
Status: statusTimeout,
|
||||
Kind: kindProbe,
|
||||
Note: "未收到回显。这是探测没有应答,不是网卡上的物理丢包计数",
|
||||
}
|
||||
}
|
||||
pkt, err := ParsePacket(buf[:n])
|
||||
if err != nil || pkt.Type != typeReply {
|
||||
sawInvalid = true
|
||||
continue
|
||||
}
|
||||
if pkt.Sequence != p.seq {
|
||||
continue
|
||||
}
|
||||
return Outcome{Status: statusOK, Kind: kindProbe, HasRtt: true, Rtt: time.Since(start), Note: "收到回显"}
|
||||
}
|
||||
}
|
||||
|
||||
type tcpConnect struct{ spec jobSpec }
|
||||
|
||||
func (p *tcpConnect) Close() error { return nil }
|
||||
|
||||
func (p *tcpConnect) Probe(ctx context.Context) Outcome {
|
||||
start := time.Now()
|
||||
conn, err := dialTCP(ctx, p.spec.IP, p.spec.Port)
|
||||
if err != nil {
|
||||
return classifyDial(err)
|
||||
}
|
||||
_ = conn.Close()
|
||||
return Outcome{Status: statusOK, Kind: kindConnect, HasRtt: true, Rtt: time.Since(start), Note: "TCP 已连通"}
|
||||
}
|
||||
|
||||
type udpQuery struct {
|
||||
spec jobSpec
|
||||
generic bool
|
||||
conn *net.UDPConn
|
||||
}
|
||||
|
||||
func (p *udpQuery) Close() error {
|
||||
if p.conn != nil {
|
||||
err := p.conn.Close()
|
||||
p.conn = nil
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *udpQuery) Probe(ctx context.Context) Outcome {
|
||||
if p.conn == nil {
|
||||
c, err := dialUDP(p.spec.IP, p.spec.Port)
|
||||
if err != nil {
|
||||
return classifyDial(err)
|
||||
}
|
||||
p.conn = c
|
||||
}
|
||||
payload := p.spec.Payload
|
||||
if p.generic {
|
||||
n := p.spec.PacketSize
|
||||
if n < 1 {
|
||||
n = 16
|
||||
}
|
||||
if n > 1400 {
|
||||
n = 1400
|
||||
}
|
||||
payload = make([]byte, n)
|
||||
}
|
||||
start := time.Now()
|
||||
deadline := start.Add(p.spec.Timeout)
|
||||
_ = p.conn.SetWriteDeadline(deadline)
|
||||
if _, err := p.conn.Write(payload); err != nil {
|
||||
return classifyDial(err)
|
||||
}
|
||||
buf := make([]byte, 2048)
|
||||
_ = p.conn.SetReadDeadline(deadline)
|
||||
n, err := p.conn.Read(buf)
|
||||
if err != nil {
|
||||
if errors.Is(err, syscall.ECONNREFUSED) {
|
||||
return Outcome{Status: statusRefused, Kind: kindQuery, Note: "目标端口不可达"}
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
return Outcome{Status: statusUnknown, Kind: kindQuery, Note: "已停止"}
|
||||
}
|
||||
return Outcome{Status: statusUnknown, Kind: kindQuery, Note: "没有收到 UDP 应答,不能据此断定物理丢包"}
|
||||
}
|
||||
got := buf[:n]
|
||||
if len(p.spec.Expect) > 0 {
|
||||
if len(got) < len(p.spec.Expect) || string(got[:len(p.spec.Expect)]) != string(p.spec.Expect) {
|
||||
return Outcome{Status: statusProtocol, Kind: kindQuery, Note: "收到了数据,但和预期的响应不一致"}
|
||||
}
|
||||
}
|
||||
return Outcome{Status: statusOK, Kind: kindQuery, HasRtt: true, Rtt: time.Since(start), Note: "收到 UDP 响应"}
|
||||
}
|
||||
|
||||
type dnsQuery struct {
|
||||
spec jobSpec
|
||||
conn *net.UDPConn
|
||||
id uint16
|
||||
}
|
||||
|
||||
func (p *dnsQuery) Close() error {
|
||||
if p.conn != nil {
|
||||
err := p.conn.Close()
|
||||
p.conn = nil
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *dnsQuery) Probe(ctx context.Context) Outcome {
|
||||
if p.conn == nil {
|
||||
c, err := dialUDP(p.spec.IP, p.spec.Port)
|
||||
if err != nil {
|
||||
return classifyDial(err)
|
||||
}
|
||||
p.conn = c
|
||||
}
|
||||
p.id++
|
||||
if p.id == 0 {
|
||||
p.id = 1
|
||||
}
|
||||
name := p.spec.DNSName
|
||||
if name == "" {
|
||||
name = "example.com"
|
||||
}
|
||||
query, err := dnsQueryMessage(p.id, name)
|
||||
if err != nil {
|
||||
return Outcome{Status: statusError, Kind: kindQuery, Note: "无法构造 DNS 查询"}
|
||||
}
|
||||
start := time.Now()
|
||||
deadline := start.Add(p.spec.Timeout)
|
||||
_ = p.conn.SetWriteDeadline(deadline)
|
||||
if _, err := p.conn.Write(query); err != nil {
|
||||
return classifyDial(err)
|
||||
}
|
||||
buf := make([]byte, 1500)
|
||||
for {
|
||||
if ctx.Err() != nil {
|
||||
return Outcome{Status: statusUnknown, Kind: kindQuery, Note: "已停止"}
|
||||
}
|
||||
_ = p.conn.SetReadDeadline(deadline)
|
||||
n, err := p.conn.Read(buf)
|
||||
if err != nil {
|
||||
if errors.Is(err, syscall.ECONNREFUSED) {
|
||||
return Outcome{Status: statusRefused, Kind: kindQuery, Note: "DNS 端口不可达"}
|
||||
}
|
||||
return Outcome{Status: statusUnknown, Kind: kindQuery, Note: "没有收到 DNS 应答,不能据此断定物理丢包"}
|
||||
}
|
||||
if n < 12 {
|
||||
return Outcome{Status: statusProtocol, Kind: kindQuery, Note: "DNS 应答太短"}
|
||||
}
|
||||
id := binary.BigEndian.Uint16(buf[:2])
|
||||
if id != p.id {
|
||||
continue
|
||||
}
|
||||
if buf[2]&0x80 == 0 {
|
||||
return Outcome{Status: statusProtocol, Kind: kindQuery, Note: "收到的包不是 DNS 应答"}
|
||||
}
|
||||
return Outcome{Status: statusOK, Kind: kindQuery, HasRtt: true, Rtt: time.Since(start), Note: "收到 DNS 应答"}
|
||||
}
|
||||
}
|
||||
|
||||
func dnsQueryMessage(id uint16, name string) ([]byte, error) {
|
||||
var q []byte
|
||||
for _, label := range strings.Split(name, ".") {
|
||||
if label == "" {
|
||||
continue
|
||||
}
|
||||
if len(label) > 63 {
|
||||
return nil, errors.New("label too long")
|
||||
}
|
||||
q = append(q, byte(len(label)))
|
||||
q = append(q, label...)
|
||||
}
|
||||
q = append(q, 0, 0, 1, 0, 1)
|
||||
msg := make([]byte, 12+len(q))
|
||||
binary.BigEndian.PutUint16(msg[0:2], id)
|
||||
binary.BigEndian.PutUint16(msg[2:4], 0x0100)
|
||||
binary.BigEndian.PutUint16(msg[4:6], 1)
|
||||
copy(msg[12:], q)
|
||||
return msg, nil
|
||||
}
|
||||
|
||||
var rakMagic = []byte{0x00, 0xFF, 0xFF, 0x00, 0xFE, 0xFE, 0xFE, 0xFE, 0xFD, 0xFD, 0xFD, 0xFD, 0x12, 0x34, 0x56, 0x78}
|
||||
|
||||
type mcBedrock struct {
|
||||
spec jobSpec
|
||||
conn *net.UDPConn
|
||||
guid uint64
|
||||
}
|
||||
|
||||
func (p *mcBedrock) Close() error {
|
||||
if p.conn != nil {
|
||||
err := p.conn.Close()
|
||||
p.conn = nil
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *mcBedrock) Probe(ctx context.Context) Outcome {
|
||||
if p.conn == nil {
|
||||
c, err := dialUDP(p.spec.IP, p.spec.Port)
|
||||
if err != nil {
|
||||
return classifyDial(err)
|
||||
}
|
||||
p.conn = c
|
||||
p.guid = uint64(time.Now().UnixNano())
|
||||
}
|
||||
ts := uint64(time.Now().UnixNano())
|
||||
pkt := make([]byte, 1+8+16+8)
|
||||
pkt[0] = 0x01
|
||||
binary.BigEndian.PutUint64(pkt[1:9], ts)
|
||||
copy(pkt[9:25], rakMagic)
|
||||
binary.BigEndian.PutUint64(pkt[25:33], p.guid)
|
||||
start := time.Now()
|
||||
deadline := start.Add(p.spec.Timeout)
|
||||
_ = p.conn.SetWriteDeadline(deadline)
|
||||
if _, err := p.conn.Write(pkt); err != nil {
|
||||
return classifyDial(err)
|
||||
}
|
||||
buf := make([]byte, 1500)
|
||||
sawInvalid := false
|
||||
for {
|
||||
if ctx.Err() != nil {
|
||||
return Outcome{Status: statusUnknown, Kind: kindQuery, Note: "已停止"}
|
||||
}
|
||||
_ = p.conn.SetReadDeadline(deadline)
|
||||
n, err := p.conn.Read(buf)
|
||||
if err != nil {
|
||||
if sawInvalid {
|
||||
return Outcome{Status: statusProtocol, Kind: kindQuery, Note: "收到的包不是有效的 RakNet Pong"}
|
||||
}
|
||||
if errors.Is(err, syscall.ECONNREFUSED) {
|
||||
return Outcome{Status: statusRefused, Kind: kindQuery, Note: "目标端口不可达"}
|
||||
}
|
||||
return Outcome{Status: statusUnknown, Kind: kindQuery, Note: "未收到 RakNet 应答,不能据此断定物理丢包"}
|
||||
}
|
||||
detail, ok := parseRakPong(buf[:n], ts)
|
||||
if !ok {
|
||||
sawInvalid = true
|
||||
continue
|
||||
}
|
||||
return Outcome{Status: statusOK, Kind: kindQuery, HasRtt: true, Rtt: time.Since(start), Note: "收到 Bedrock 应答", Detail: detail}
|
||||
}
|
||||
}
|
||||
|
||||
func parseRakPong(b []byte, ts uint64) (map[string]string, bool) {
|
||||
if len(b) < 1+8+8+16+2 || b[0] != 0x1c {
|
||||
return nil, false
|
||||
}
|
||||
if binary.BigEndian.Uint64(b[1:9]) != ts {
|
||||
return nil, false
|
||||
}
|
||||
if string(b[17:33]) != string(rakMagic) {
|
||||
return nil, false
|
||||
}
|
||||
strlen := int(binary.BigEndian.Uint16(b[33:35]))
|
||||
if 35+strlen > len(b) {
|
||||
return nil, false
|
||||
}
|
||||
text := string(b[35 : 35+strlen])
|
||||
parts := strings.Split(text, ";")
|
||||
detail := map[string]string{}
|
||||
if len(parts) > 1 {
|
||||
detail["motd"] = parts[1]
|
||||
}
|
||||
if len(parts) > 3 {
|
||||
detail["version"] = parts[3]
|
||||
}
|
||||
if len(parts) > 5 {
|
||||
detail["players"] = parts[4] + "/" + parts[5]
|
||||
}
|
||||
return detail, true
|
||||
}
|
||||
|
||||
type mcJava struct{ spec jobSpec }
|
||||
|
||||
func (p *mcJava) Close() error { return nil }
|
||||
|
||||
func (p *mcJava) Probe(ctx context.Context) Outcome {
|
||||
conn, err := dialTCP(ctx, p.spec.IP, p.spec.Port)
|
||||
if err != nil {
|
||||
return classifyDial(err)
|
||||
}
|
||||
defer conn.Close()
|
||||
deadline, ok := ctx.Deadline()
|
||||
if !ok {
|
||||
deadline = time.Now().Add(p.spec.Timeout)
|
||||
}
|
||||
_ = conn.SetDeadline(deadline)
|
||||
r := bufio.NewReader(conn)
|
||||
host := p.spec.Host
|
||||
if err := writeMC(conn, mcHandshake(host, p.spec.Port)); err != nil {
|
||||
return Outcome{Status: statusError, Kind: kindConnect, Note: "无法发送 Minecraft 握手"}
|
||||
}
|
||||
if err := writeMC(conn, []byte{0x00}); err != nil {
|
||||
return Outcome{Status: statusError, Kind: kindConnect, Note: "无法发送状态请求"}
|
||||
}
|
||||
payload, err := readMC(r)
|
||||
if err != nil || len(payload) < 2 || payload[0] != 0x00 {
|
||||
return Outcome{Status: statusProtocol, Kind: kindQuery, Note: "Minecraft 状态响应无效"}
|
||||
}
|
||||
jsonText, _, err := readMCString(payload[1:])
|
||||
if err != nil {
|
||||
return Outcome{Status: statusProtocol, Kind: kindQuery, Note: "Minecraft 状态内容无法解析"}
|
||||
}
|
||||
detail := minecraftStatusDetail(jsonText)
|
||||
nonce := time.Now().UnixNano()
|
||||
ping := []byte{0x01}
|
||||
var num [8]byte
|
||||
binary.BigEndian.PutUint64(num[:], uint64(nonce))
|
||||
ping = append(ping, num[:]...)
|
||||
start := time.Now()
|
||||
if err := writeMC(conn, ping); err != nil {
|
||||
return Outcome{Status: statusError, Kind: kindQuery, Note: "无法发送 Minecraft ping", Detail: detail}
|
||||
}
|
||||
pong, err := readMC(r)
|
||||
if err != nil || len(pong) != 9 || pong[0] != 0x01 {
|
||||
return Outcome{Status: statusProtocol, Kind: kindQuery, Note: "没有收到有效的 Minecraft pong", Detail: detail}
|
||||
}
|
||||
if int64(binary.BigEndian.Uint64(pong[1:])) != nonce {
|
||||
return Outcome{Status: statusProtocol, Kind: kindQuery, Note: "Minecraft pong 的时间戳不匹配", Detail: detail}
|
||||
}
|
||||
return Outcome{
|
||||
Status: statusOK,
|
||||
Kind: kindQuery,
|
||||
HasRtt: true,
|
||||
Rtt: time.Since(start),
|
||||
Note: "收到 Minecraft 状态和 ping 应答",
|
||||
Detail: detail,
|
||||
}
|
||||
}
|
||||
|
||||
func mcHandshake(host string, port int) []byte {
|
||||
var p []byte
|
||||
p = append(p, 0x00)
|
||||
p = appendVarInt(p, 767)
|
||||
p = appendMCString(p, host)
|
||||
var pb [2]byte
|
||||
binary.BigEndian.PutUint16(pb[:], uint16(port))
|
||||
p = append(p, pb[:]...)
|
||||
p = appendVarInt(p, 1)
|
||||
return p
|
||||
}
|
||||
|
||||
func minecraftStatusDetail(raw string) map[string]string {
|
||||
var body map[string]any
|
||||
if err := json.Unmarshal([]byte(raw), &body); err != nil {
|
||||
return map[string]string{}
|
||||
}
|
||||
out := map[string]string{}
|
||||
if v, ok := body["version"].(map[string]any); ok {
|
||||
if name, ok := v["name"].(string); ok {
|
||||
out["version"] = name
|
||||
}
|
||||
}
|
||||
if p, ok := body["players"].(map[string]any); ok {
|
||||
online, _ := asInt(p["online"])
|
||||
max, _ := asInt(p["max"])
|
||||
out["players"] = fmt.Sprintf("%d/%d", online, max)
|
||||
}
|
||||
if desc, ok := body["description"]; ok {
|
||||
if text := motdText(desc); text != "" {
|
||||
out["motd"] = text
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func asInt(v any) (int, bool) {
|
||||
switch n := v.(type) {
|
||||
case float64:
|
||||
return int(n), true
|
||||
case int:
|
||||
return n, true
|
||||
default:
|
||||
return 0, false
|
||||
}
|
||||
}
|
||||
|
||||
func motdText(v any) string {
|
||||
switch t := v.(type) {
|
||||
case string:
|
||||
return t
|
||||
case map[string]any:
|
||||
var b strings.Builder
|
||||
if s, ok := t["text"].(string); ok {
|
||||
b.WriteString(s)
|
||||
}
|
||||
if extra, ok := t["extra"].([]any); ok {
|
||||
for _, e := range extra {
|
||||
b.WriteString(motdText(e))
|
||||
}
|
||||
}
|
||||
return b.String()
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
func appendVarInt(dst []byte, v int) []byte {
|
||||
u := uint32(v)
|
||||
for {
|
||||
if u&^0x7f == 0 {
|
||||
return append(dst, byte(u))
|
||||
}
|
||||
dst = append(dst, byte(u)|0x80)
|
||||
u >>= 7
|
||||
}
|
||||
}
|
||||
|
||||
func readVarInt(r *bufio.Reader) (int, error) {
|
||||
var n uint32
|
||||
for i := 0; i < 5; i++ {
|
||||
b, err := r.ReadByte()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
n |= uint32(b&0x7f) << (7 * i)
|
||||
if b&0x80 == 0 {
|
||||
return int(n), nil
|
||||
}
|
||||
}
|
||||
return 0, errors.New("varint too long")
|
||||
}
|
||||
|
||||
func appendMCString(dst []byte, s string) []byte {
|
||||
dst = appendVarInt(dst, len(s))
|
||||
return append(dst, s...)
|
||||
}
|
||||
|
||||
func readMCString(b []byte) (string, []byte, error) {
|
||||
n, rest, err := readVarIntBytes(b)
|
||||
if err != nil || n < 0 || n > len(rest) {
|
||||
return "", nil, errors.New("bad string")
|
||||
}
|
||||
return string(rest[:n]), rest[n:], nil
|
||||
}
|
||||
|
||||
func readVarIntBytes(b []byte) (int, []byte, error) {
|
||||
var n uint32
|
||||
for i := 0; i < 5 && i < len(b); i++ {
|
||||
by := b[i]
|
||||
n |= uint32(by&0x7f) << (7 * i)
|
||||
if by&0x80 == 0 {
|
||||
return int(n), b[i+1:], nil
|
||||
}
|
||||
}
|
||||
return 0, nil, errors.New("varint")
|
||||
}
|
||||
|
||||
func writeMC(w io.Writer, payload []byte) error {
|
||||
frame := appendVarInt(nil, len(payload))
|
||||
frame = append(frame, payload...)
|
||||
_, err := w.Write(frame)
|
||||
return err
|
||||
}
|
||||
|
||||
func readMC(r *bufio.Reader) ([]byte, error) {
|
||||
n, err := readVarInt(r)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if n < 1 || n > 1<<20 {
|
||||
return nil, errors.New("bad packet length")
|
||||
}
|
||||
buf := make([]byte, n)
|
||||
_, err = io.ReadFull(r, buf)
|
||||
return buf, err
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
// Package main implements the NetQuality reflector.
|
||||
//
|
||||
// Wire format (version 1), little-endian. The same layout is used for one
|
||||
// UDP datagram and for one TCP frame. TCP frames are concatenated on the
|
||||
// stream and split using PayloadLen; there is no extra length prefix.
|
||||
//
|
||||
// Offset Size Field
|
||||
// 0 4 Magic "NQ01"
|
||||
// 4 1 Version (1)
|
||||
// 5 1 Type (1 request, 2 reply)
|
||||
// 6 1 Flags (reserved, send 0)
|
||||
// 7 1 Reserved (0)
|
||||
// 8 4 Sequence uint32
|
||||
// 12 8 ClientSendUnixNano uint64
|
||||
// 20 8 ServerUnixNano uint64 (0 on request)
|
||||
// 28 32 Token (UTF-8, zero padded; zeros if unused)
|
||||
// 60 2 PayloadLen uint16
|
||||
// 62 N Payload (opaque, echoed unchanged)
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
const (
|
||||
magic = "NQ01"
|
||||
protocolVer = 1
|
||||
headerSize = 62
|
||||
tokenOffset = 28
|
||||
tokenLen = 32
|
||||
payloadLenOff = 60
|
||||
maxPayloadSize = 2048
|
||||
|
||||
typeRequest byte = 1
|
||||
typeReply byte = 2
|
||||
)
|
||||
|
||||
var (
|
||||
errShortPacket = errors.New("packet shorter than header")
|
||||
errBadMagic = errors.New("bad magic")
|
||||
errBadVersion = errors.New("unsupported version")
|
||||
errBadType = errors.New("unsupported type")
|
||||
errBadPayloadLen = errors.New("payload length out of range")
|
||||
errTrailingBytes = errors.New("trailing bytes after payload")
|
||||
errBadToken = errors.New("token mismatch")
|
||||
)
|
||||
|
||||
// Packet is a decoded probe frame.
|
||||
type Packet struct {
|
||||
Version byte
|
||||
Type byte
|
||||
Flags byte
|
||||
Sequence uint32
|
||||
ClientSendUnixNano uint64
|
||||
ServerUnixNano uint64
|
||||
Token [tokenLen]byte
|
||||
Payload []byte
|
||||
}
|
||||
|
||||
func (p Packet) Marshal() ([]byte, error) {
|
||||
if len(p.Payload) > maxPayloadSize {
|
||||
return nil, errBadPayloadLen
|
||||
}
|
||||
buf := make([]byte, headerSize+len(p.Payload))
|
||||
copy(buf[0:4], magic)
|
||||
buf[4] = p.Version
|
||||
buf[5] = p.Type
|
||||
buf[6] = p.Flags
|
||||
buf[7] = 0
|
||||
binary.LittleEndian.PutUint32(buf[8:12], p.Sequence)
|
||||
binary.LittleEndian.PutUint64(buf[12:20], p.ClientSendUnixNano)
|
||||
binary.LittleEndian.PutUint64(buf[20:28], p.ServerUnixNano)
|
||||
copy(buf[tokenOffset:tokenOffset+tokenLen], p.Token[:])
|
||||
binary.LittleEndian.PutUint16(buf[payloadLenOff:payloadLenOff+2], uint16(len(p.Payload)))
|
||||
copy(buf[headerSize:], p.Payload)
|
||||
return buf, nil
|
||||
}
|
||||
|
||||
// ParsePacket decodes a single frame. n is the number of bytes consumed,
|
||||
// which equals the full frame size. Extra bytes are rejected so a UDP
|
||||
// datagram must contain exactly one frame.
|
||||
func ParsePacket(b []byte) (Packet, error) {
|
||||
if len(b) < headerSize {
|
||||
return Packet{}, errShortPacket
|
||||
}
|
||||
if string(b[0:4]) != magic {
|
||||
return Packet{}, errBadMagic
|
||||
}
|
||||
if b[4] != protocolVer {
|
||||
return Packet{}, errBadVersion
|
||||
}
|
||||
typ := b[5]
|
||||
if typ != typeRequest && typ != typeReply {
|
||||
return Packet{}, errBadType
|
||||
}
|
||||
payloadLen := int(binary.LittleEndian.Uint16(b[payloadLenOff : payloadLenOff+2]))
|
||||
if payloadLen > maxPayloadSize {
|
||||
return Packet{}, errBadPayloadLen
|
||||
}
|
||||
total := headerSize + payloadLen
|
||||
if len(b) < total {
|
||||
return Packet{}, fmt.Errorf("%w: need %d bytes, have %d", errShortPacket, total, len(b))
|
||||
}
|
||||
if len(b) != total {
|
||||
return Packet{}, errTrailingBytes
|
||||
}
|
||||
var p Packet
|
||||
p.Version = b[4]
|
||||
p.Type = typ
|
||||
p.Flags = b[6]
|
||||
p.Sequence = binary.LittleEndian.Uint32(b[8:12])
|
||||
p.ClientSendUnixNano = binary.LittleEndian.Uint64(b[12:20])
|
||||
p.ServerUnixNano = binary.LittleEndian.Uint64(b[20:28])
|
||||
copy(p.Token[:], b[tokenOffset:tokenOffset+tokenLen])
|
||||
if payloadLen > 0 {
|
||||
p.Payload = append([]byte(nil), b[headerSize:total]...)
|
||||
} else {
|
||||
p.Payload = []byte{}
|
||||
}
|
||||
return p, nil
|
||||
}
|
||||
|
||||
// tokenBytes normalizes a configured shared token into the 32-byte field.
|
||||
// Empty means "no token required".
|
||||
func tokenBytes(s string) ([tokenLen]byte, error) {
|
||||
var out [tokenLen]byte
|
||||
if s == "" {
|
||||
return out, nil
|
||||
}
|
||||
b := []byte(s)
|
||||
if len(b) > tokenLen {
|
||||
return out, fmt.Errorf("token longer than %d bytes", tokenLen)
|
||||
}
|
||||
copy(out[:], b)
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func tokenMatches(got [tokenLen]byte, want [tokenLen]byte, required bool) bool {
|
||||
if !required {
|
||||
return true
|
||||
}
|
||||
return got == want
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"net"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestGoldenRequest(t *testing.T) {
|
||||
var p Packet
|
||||
p.Version = protocolVer
|
||||
p.Type = typeRequest
|
||||
p.Sequence = 1
|
||||
p.ClientSendUnixNano = 1000
|
||||
p.Payload = []byte{0x01, 0x02, 0x03, 0x04}
|
||||
|
||||
got, err := p.Marshal()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
want := goldenRequest()
|
||||
if !bytes.Equal(got, want) {
|
||||
t.Fatalf("golden mismatch\n got %x\nwant %x", got, want)
|
||||
}
|
||||
|
||||
back, err := ParsePacket(got)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if back.Sequence != 1 || back.ClientSendUnixNano != 1000 || back.Type != typeRequest {
|
||||
t.Fatalf("round trip fields: %+v", back)
|
||||
}
|
||||
if !bytes.Equal(back.Payload, p.Payload) {
|
||||
t.Fatalf("payload %x", back.Payload)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRejects(t *testing.T) {
|
||||
good := goldenRequest()
|
||||
if _, err := ParsePacket(good[:10]); err == nil {
|
||||
t.Fatal("expected short packet error")
|
||||
}
|
||||
badMagic := append([]byte(nil), good...)
|
||||
badMagic[0] = 'X'
|
||||
if _, err := ParsePacket(badMagic); err != errBadMagic {
|
||||
t.Fatalf("magic: %v", err)
|
||||
}
|
||||
badVer := append([]byte(nil), good...)
|
||||
badVer[4] = 9
|
||||
if _, err := ParsePacket(badVer); err != errBadVersion {
|
||||
t.Fatalf("version: %v", err)
|
||||
}
|
||||
trailing := append(append([]byte(nil), good...), 0xFF)
|
||||
if _, err := ParsePacket(trailing); err != errTrailingBytes {
|
||||
t.Fatalf("trailing: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTokenRequired(t *testing.T) {
|
||||
tok, err := tokenBytes("secret")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s := &Server{Token: tok, Required: true}
|
||||
var p Packet
|
||||
p.Version = protocolVer
|
||||
p.Type = typeRequest
|
||||
p.Sequence = 7
|
||||
p.ClientSendUnixNano = 42
|
||||
p.Payload = []byte("hi")
|
||||
if _, ok := s.HandlePacket(p, time.Unix(0, 99)); ok {
|
||||
t.Fatal("expected token rejection")
|
||||
}
|
||||
p.Token = tok
|
||||
reply, ok := s.HandlePacket(p, time.Unix(0, 99))
|
||||
if !ok {
|
||||
t.Fatal("expected accept")
|
||||
}
|
||||
back, err := ParsePacket(reply)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if back.Type != typeReply || back.Sequence != 7 || back.ClientSendUnixNano != 42 || back.ServerUnixNano != 99 {
|
||||
t.Fatalf("reply %+v", back)
|
||||
}
|
||||
if string(back.Payload) != "hi" || back.Token != tok {
|
||||
t.Fatalf("echo mismatch")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTokenTooLong(t *testing.T) {
|
||||
if _, err := tokenBytes("0123456789abcdef0123456789abcdefX"); err == nil {
|
||||
t.Fatal("expected error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestUDPAndTCPEcho(t *testing.T) {
|
||||
s := &Server{}
|
||||
|
||||
udpAddr, err := net.ResolveUDPAddr("udp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
udpConn, err := net.ListenUDP("udp", udpAddr)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer udpConn.Close()
|
||||
go s.ServeUDP(udpConn)
|
||||
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer ln.Close()
|
||||
go s.ServeTCP(ln)
|
||||
|
||||
payload := bytes.Repeat([]byte{0xAB}, 16)
|
||||
req := Packet{
|
||||
Version: protocolVer,
|
||||
Type: typeRequest,
|
||||
Sequence: 3,
|
||||
ClientSendUnixNano: uint64(time.Now().UnixNano()),
|
||||
Payload: payload,
|
||||
}
|
||||
raw, err := req.Marshal()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
clientUDP, err := net.DialUDP("udp", nil, udpConn.LocalAddr().(*net.UDPAddr))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer clientUDP.Close()
|
||||
if _, err := clientUDP.Write(raw); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = clientUDP.SetReadDeadline(time.Now().Add(2 * time.Second))
|
||||
buf := make([]byte, 2048)
|
||||
n, err := clientUDP.Read(buf)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertReply(t, buf[:n], req)
|
||||
|
||||
tcpClient, err := net.Dial("tcp", ln.Addr().String())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer tcpClient.Close()
|
||||
req.Sequence = 4
|
||||
raw, _ = req.Marshal()
|
||||
// Two frames back-to-back to prove TCP framing.
|
||||
if _, err := tcpClient.Write(append(append([]byte{}, raw...), raw...)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = tcpClient.SetReadDeadline(time.Now().Add(2 * time.Second))
|
||||
got := make([]byte, len(raw)*2)
|
||||
if _, err := ioReadFull(tcpClient, got); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertReply(t, got[:len(raw)], req)
|
||||
assertReply(t, got[len(raw):], req)
|
||||
}
|
||||
|
||||
func assertReply(t *testing.T, raw []byte, req Packet) {
|
||||
t.Helper()
|
||||
p, err := ParsePacket(raw)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if p.Type != typeReply {
|
||||
t.Fatalf("type %d", p.Type)
|
||||
}
|
||||
if p.Sequence != req.Sequence || p.ClientSendUnixNano != req.ClientSendUnixNano {
|
||||
t.Fatalf("identity not preserved: %+v", p)
|
||||
}
|
||||
if !bytes.Equal(p.Payload, req.Payload) {
|
||||
t.Fatalf("payload changed")
|
||||
}
|
||||
if p.ServerUnixNano == 0 {
|
||||
t.Fatal("server timestamp not set")
|
||||
}
|
||||
}
|
||||
|
||||
func ioReadFull(c net.Conn, buf []byte) (int, error) {
|
||||
n := 0
|
||||
for n < len(buf) {
|
||||
r, err := c.Read(buf[n:])
|
||||
n += r
|
||||
if err != nil {
|
||||
return n, err
|
||||
}
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func goldenRequest() []byte {
|
||||
buf := make([]byte, headerSize+4)
|
||||
copy(buf[0:4], "NQ01")
|
||||
buf[4] = 1
|
||||
buf[5] = 1
|
||||
binary.LittleEndian.PutUint32(buf[8:12], 1)
|
||||
binary.LittleEndian.PutUint64(buf[12:20], 1000)
|
||||
binary.LittleEndian.PutUint16(buf[payloadLenOff:payloadLenOff+2], 4)
|
||||
copy(buf[headerSize:], []byte{1, 2, 3, 4})
|
||||
return buf
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
var errForbiddenTarget = errors.New("forbidden target")
|
||||
|
||||
// metadataNames are never probed, even when the operator allows LAN targets.
|
||||
var metadataNames = map[string]struct{}{
|
||||
"localhost": {},
|
||||
"metadata": {},
|
||||
"metadata.google.internal": {},
|
||||
"metadata.google.com": {},
|
||||
}
|
||||
|
||||
var metadataIP = net.ParseIP("169.254.169.254")
|
||||
|
||||
// targetOK decides whether a remote node may dial this address.
|
||||
// Loopback, private, link-local and cloud metadata are rejected unless
|
||||
// allowPrivate is set. Metadata addresses stay blocked either way.
|
||||
// Every resolved address is checked so a later DNS answer cannot rebind
|
||||
// the dial onto a forbidden IP; the caller dials only the returned IP.
|
||||
func targetOK(ctx context.Context, resolver resolver, host string, allowPrivate bool, extra []*net.IPNet) (net.IP, error) {
|
||||
host = strings.TrimSpace(host)
|
||||
host = strings.Trim(host, "[]")
|
||||
if host == "" {
|
||||
return nil, errors.New("empty host")
|
||||
}
|
||||
if _, banned := metadataNames[strings.ToLower(host)]; banned {
|
||||
return nil, fmt.Errorf("%w: metadata or localhost name", errForbiddenTarget)
|
||||
}
|
||||
if ip := net.ParseIP(host); ip != nil {
|
||||
if !ipAllowed(ip, allowPrivate, extra) {
|
||||
return nil, fmt.Errorf("%w: %s", errForbiddenTarget, ip.String())
|
||||
}
|
||||
return ip, nil
|
||||
}
|
||||
if resolver == nil {
|
||||
resolver = net.DefaultResolver
|
||||
}
|
||||
lookupCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
defer cancel()
|
||||
addrs, err := resolver.LookupIPAddr(lookupCtx, host)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(addrs) == 0 {
|
||||
return nil, &net.DNSError{Err: "no addresses", Name: host, IsNotFound: true}
|
||||
}
|
||||
var allowed []net.IP
|
||||
for _, addr := range addrs {
|
||||
if ipAllowed(addr.IP, allowPrivate, extra) {
|
||||
allowed = append(allowed, addr.IP)
|
||||
}
|
||||
}
|
||||
if len(allowed) == 0 {
|
||||
return nil, fmt.Errorf("%w: %s resolved only to blocked addresses", errForbiddenTarget, host)
|
||||
}
|
||||
if len(allowed) != len(addrs) {
|
||||
return nil, fmt.Errorf("%w: %s resolved to a mix of public and blocked addresses", errForbiddenTarget, host)
|
||||
}
|
||||
return allowed[0], nil
|
||||
}
|
||||
|
||||
func ipAllowed(ip net.IP, allowPrivate bool, extra []*net.IPNet) bool {
|
||||
if ip == nil {
|
||||
return false
|
||||
}
|
||||
if ip.Equal(metadataIP) || ip.Equal(net.ParseIP("fd00:ec2::254")) {
|
||||
return false
|
||||
}
|
||||
for _, n := range extra {
|
||||
if n.Contains(ip) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
if ip.IsMulticast() || ip.IsUnspecified() || ip.IsLinkLocalMulticast() {
|
||||
return false
|
||||
}
|
||||
if allowPrivate {
|
||||
return true
|
||||
}
|
||||
if ip.IsLoopback() || ip.IsPrivate() || ip.IsLinkLocalUnicast() {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
type resolver interface {
|
||||
LookupIPAddr(context.Context, string) ([]net.IPAddr, error)
|
||||
}
|
||||
Reference in new issue
Block a user