网络质量探测 1.1.3:自更新、HTTP/3 与中心节点
版本名 1.1.3,构建号 6。应用标识和签名未改。包含自动更新、覆盖安装、目标历史、IPv4/IPv6 开关、HTTP(含 HTTP/3)以及中心服务端一键添加节点。
This commit is contained in:
1 parent
943259774f
commit
8cdc0f436f
66 files changed
+5489
-78
No files matched your search
+15
-1
@@ -24,10 +24,12 @@ NQ_UDP_PORT=19091
|
||||
# 这和下面的节点口令不是同一个东西。
|
||||
NQ_TOKEN=
|
||||
|
||||
# 工作模式,三选一:
|
||||
# 工作模式:
|
||||
# reflector 只做反射:把收到的探测包原样送回去。这是默认。
|
||||
# node 只做检测节点:按手机的指令去测别的地址。
|
||||
# both 反射和节点一起开。
|
||||
# center 只做中心:按配置目录里的分组和口令分发节点。需要下面的 NQ_CENTER_DIR。
|
||||
# helper 给本机客户端做 HTTP 探测,不监听端口。
|
||||
NQ_MODE=reflector
|
||||
|
||||
# 节点控制地址。手机「管理节点」里填的就是这个地址。
|
||||
@@ -58,3 +60,15 @@ NQ_TLS_KEY=
|
||||
# 是否把每一个收发的包都写进日志。只能写 true 或 false。
|
||||
# 平常保持 false。排查问题时再改成 true。
|
||||
NQ_VERBOSE=false
|
||||
|
||||
# 中心配置目录。模式是 center 时必填。节点模式也可以同时填写,控制端口会一并提供中心接口。
|
||||
# 留空表示不做中心。目录里放 groups.json、tokens.json、servers/*.json,密钥放 center.key。
|
||||
NQ_CENTER_DIR=
|
||||
|
||||
# 中心用来签发短期凭证的密钥。节点要核对这些凭证时也填同一串。
|
||||
# 留空时,如果填写了中心目录,会改读该目录里的 center.key。
|
||||
# 不要把真实密钥写进仓库,也不要出现在日志里。
|
||||
NQ_CENTER_KEY=
|
||||
|
||||
# 这台节点在中心服务器文件里的编号。要接受中心签发的短期凭证时必填,并且要和服务器文件的 id 一致。
|
||||
NQ_SERVER_ID=
|
||||
+15
-1
@@ -24,10 +24,12 @@ NQ_UDP_PORT=19091
|
||||
# 这和下面的节点口令不是同一个东西。
|
||||
NQ_TOKEN=
|
||||
|
||||
# 工作模式,三选一:
|
||||
# 工作模式:
|
||||
# reflector 只做反射:把收到的探测包原样送回去。这是默认。
|
||||
# node 只做检测节点:按手机的指令去测别的地址。
|
||||
# both 反射和节点一起开。
|
||||
# center 只做中心:按配置目录里的分组和口令分发节点。需要下面的 NQ_CENTER_DIR。
|
||||
# helper 给本机客户端做 HTTP 探测,不监听端口。
|
||||
NQ_MODE=reflector
|
||||
|
||||
# 节点控制地址。手机「管理节点」里填的就是这个地址。
|
||||
@@ -58,3 +60,15 @@ NQ_TLS_KEY=
|
||||
# 是否把每一个收发的包都写进日志。只能写 true 或 false。
|
||||
# 平常保持 false。排查问题时再改成 true。
|
||||
NQ_VERBOSE=false
|
||||
|
||||
# 中心配置目录。模式是 center 时必填。节点模式也可以同时填写,控制端口会一并提供中心接口。
|
||||
# 留空表示不做中心。目录里放 groups.json、tokens.json、servers/*.json,密钥放 center.key。
|
||||
NQ_CENTER_DIR=
|
||||
|
||||
# 中心用来签发短期凭证的密钥。节点要核对这些凭证时也填同一串。
|
||||
# 留空时,如果填写了中心目录,会改读该目录里的 center.key。
|
||||
# 不要把真实密钥写进仓库,也不要出现在日志里。
|
||||
NQ_CENTER_KEY=
|
||||
|
||||
# 这台节点在中心服务器文件里的编号。要接受中心签发的短期凭证时必填,并且要和服务器文件的 id 一致。
|
||||
NQ_SERVER_ID=
|
||||
+2
-1
@@ -6,6 +6,7 @@
|
||||
|
||||
- **反射**:把探测包原样送回去。手机直接测到这台机器的延迟。
|
||||
- **节点**:手机只下指令。这台机器替手机去测别的地址,例如游戏服务器。
|
||||
- **中心**:一个配置目录里放用户组、口令哈希和探测节点。手机填一次中心口令,就能加入这个口令能用的全部节点。说明和示例在仓库的 `example-center/`,以及 `docs/server-linux.md`。
|
||||
|
||||
压缩包里已经有一份能直接用的 `.env`,默认端口和以前一样:TCP `19090`、UDP `19091`。不改也能用。
|
||||
|
||||
@@ -110,7 +111,7 @@ sudo firewall-cmd --reload
|
||||
|
||||
```bash
|
||||
sudo mkdir -p /opt/netquality
|
||||
sudo tar -C /opt/netquality --strip-components=1 -xzf netquality-server-1.1.2-linux-amd64.tar.gz
|
||||
sudo tar -C /opt/netquality --strip-components=1 -xzf netquality-server-1.1.3-linux-amd64.tar.gz
|
||||
sudo chmod 755 /opt/netquality/netquality-reflector
|
||||
sudo cp /opt/netquality/netquality.service /etc/systemd/system/netquality.service
|
||||
sudo systemctl daemon-reload
|
||||
|
||||
@@ -0,0 +1,474 @@
|
||||
// Copyright (C) 2026 言灸
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
centerSessionTTL = 12 * time.Hour
|
||||
centerCredTTL = 15 * time.Minute
|
||||
)
|
||||
|
||||
type centerGroup struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
type centerToken struct {
|
||||
ID string `json:"id"`
|
||||
Group string `json:"group"`
|
||||
Account string `json:"account"`
|
||||
TokenHash string `json:"tokenHash"`
|
||||
PasswordHash string `json:"passwordHash"`
|
||||
}
|
||||
|
||||
type centerServer struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
ControlURL string `json:"controlUrl"`
|
||||
Groups []string `json:"groups"`
|
||||
Confidential bool `json:"confidential"`
|
||||
NodeToken string `json:"nodeToken"`
|
||||
}
|
||||
|
||||
type centerConfig struct {
|
||||
groups []centerGroup
|
||||
tokens []centerToken
|
||||
servers []centerServer
|
||||
}
|
||||
|
||||
type centerSession struct {
|
||||
group string
|
||||
account string
|
||||
exp time.Time
|
||||
}
|
||||
|
||||
// Center is the same process as the probe node, serving a directory of
|
||||
// groups, token hashes and servers. Confidential nodes are proxied.
|
||||
// Their addresses are not included in catalog responses.
|
||||
type Center struct {
|
||||
Dir string
|
||||
Key []byte
|
||||
|
||||
mu sync.Mutex
|
||||
sessions map[string]centerSession
|
||||
client *http.Client
|
||||
}
|
||||
|
||||
func newCenter(dir string, key string) *Center {
|
||||
c := &Center{
|
||||
Dir: dir,
|
||||
sessions: map[string]centerSession{},
|
||||
client: &http.Client{
|
||||
CheckRedirect: func(*http.Request, []*http.Request) error {
|
||||
return http.ErrUseLastResponse
|
||||
},
|
||||
},
|
||||
}
|
||||
if strings.TrimSpace(key) != "" {
|
||||
c.Key = []byte(strings.TrimSpace(key))
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
func (c *Center) Handler() http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("POST /v1/center/login", c.login)
|
||||
mux.HandleFunc("GET /v1/center/catalog", c.catalog)
|
||||
mux.HandleFunc("POST /v1/center/servers/{id}/jobs", c.proxyCreate)
|
||||
mux.HandleFunc("GET /v1/center/servers/{id}/jobs/{jobId}", c.proxySnapshot)
|
||||
mux.HandleFunc("GET /v1/center/servers/{id}/jobs/{jobId}/stream", c.proxyStream)
|
||||
mux.HandleFunc("DELETE /v1/center/servers/{id}/jobs/{jobId}", c.proxyDelete)
|
||||
return mux
|
||||
}
|
||||
|
||||
type catalogServer struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Confidential bool `json:"confidential"`
|
||||
ControlURL string `json:"controlUrl,omitempty"`
|
||||
Credential string `json:"credential,omitempty"`
|
||||
CredentialExpiresAt string `json:"credentialExpiresAt,omitempty"`
|
||||
}
|
||||
|
||||
func (c *Center) login(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
Account string `json:"account"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
dec := json.NewDecoder(io.LimitReader(r.Body, 1<<16))
|
||||
if err := dec.Decode(&req); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "bad_request", "请求内容无法解析")
|
||||
return
|
||||
}
|
||||
cfg, err := c.load()
|
||||
if err != nil {
|
||||
log.Printf("center config: %v", err)
|
||||
writeErr(w, http.StatusInternalServerError, "config", "中心配置无法读取")
|
||||
return
|
||||
}
|
||||
account := strings.TrimSpace(req.Account)
|
||||
var matched *centerToken
|
||||
for i := range cfg.tokens {
|
||||
tok := &cfg.tokens[i]
|
||||
if tok.Account != account || tok.PasswordHash == "" {
|
||||
continue
|
||||
}
|
||||
if hashEqual(tok.PasswordHash, req.Password) && c.groupKnown(cfg, tok.Group) {
|
||||
matched = tok
|
||||
break
|
||||
}
|
||||
}
|
||||
if matched == nil {
|
||||
log.Printf("center login failed")
|
||||
writeErr(w, http.StatusUnauthorized, "unauthorized", "账号或密码不正确")
|
||||
return
|
||||
}
|
||||
raw, err := randomToken()
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "error", "暂时无法登录")
|
||||
return
|
||||
}
|
||||
exp := time.Now().Add(centerSessionTTL)
|
||||
c.mu.Lock()
|
||||
c.sessions[hashSecret(raw)] = centerSession{group: matched.Group, account: matched.Account, exp: exp}
|
||||
c.mu.Unlock()
|
||||
writeJSON(w, http.StatusOK, map[string]string{
|
||||
"token": raw,
|
||||
"account": matched.Account,
|
||||
"group": matched.Group,
|
||||
"expiresAt": exp.UTC().Format(time.RFC3339),
|
||||
})
|
||||
}
|
||||
|
||||
func (c *Center) catalog(w http.ResponseWriter, r *http.Request) {
|
||||
group, account, ok := c.who(r)
|
||||
if !ok {
|
||||
writeErr(w, http.StatusUnauthorized, "unauthorized", "中心口令不正确或未提供")
|
||||
return
|
||||
}
|
||||
cfg, err := c.load()
|
||||
if err != nil {
|
||||
log.Printf("center config: %v", err)
|
||||
writeErr(w, http.StatusInternalServerError, "config", "中心配置无法读取")
|
||||
return
|
||||
}
|
||||
items := make([]catalogServer, 0)
|
||||
for _, srv := range cfg.servers {
|
||||
if !containsString(srv.Groups, group) {
|
||||
continue
|
||||
}
|
||||
item := catalogServer{ID: srv.ID, Name: srv.Name, Confidential: srv.Confidential}
|
||||
if srv.Confidential {
|
||||
items = append(items, item)
|
||||
continue
|
||||
}
|
||||
if len(c.Key) == 0 {
|
||||
writeErr(w, http.StatusInternalServerError, "config", "中心没有 center.key,不能给非保密节点签发短期凭证")
|
||||
return
|
||||
}
|
||||
exp := time.Now().Add(centerCredTTL)
|
||||
cred, err := mintCredential(srv.ID, exp, c.Key)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "config", "无法签发短期凭证")
|
||||
return
|
||||
}
|
||||
item.ControlURL = srv.ControlURL
|
||||
item.Credential = cred
|
||||
item.CredentialExpiresAt = exp.UTC().Format(time.RFC3339)
|
||||
items = append(items, item)
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"account": account,
|
||||
"group": group,
|
||||
"servers": items,
|
||||
})
|
||||
}
|
||||
|
||||
func (c *Center) proxyCreate(w http.ResponseWriter, r *http.Request) {
|
||||
c.proxy(w, r, "/v1/jobs")
|
||||
}
|
||||
|
||||
func (c *Center) proxySnapshot(w http.ResponseWriter, r *http.Request) {
|
||||
c.proxy(w, r, "/v1/jobs/"+url.PathEscape(r.PathValue("jobId")))
|
||||
}
|
||||
|
||||
func (c *Center) proxyStream(w http.ResponseWriter, r *http.Request) {
|
||||
c.proxy(w, r, "/v1/jobs/"+url.PathEscape(r.PathValue("jobId"))+"/stream")
|
||||
}
|
||||
|
||||
func (c *Center) proxyDelete(w http.ResponseWriter, r *http.Request) {
|
||||
c.proxy(w, r, "/v1/jobs/"+url.PathEscape(r.PathValue("jobId")))
|
||||
}
|
||||
|
||||
func (c *Center) proxy(w http.ResponseWriter, r *http.Request, path string) {
|
||||
srv, ok := c.authorizedServer(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
base, err := url.Parse(srv.ControlURL)
|
||||
if err != nil || base.Host == "" {
|
||||
writeErr(w, http.StatusBadGateway, "node", "连不上节点")
|
||||
return
|
||||
}
|
||||
target := base.ResolveReference(&url.URL{Path: path})
|
||||
body := io.Reader(nil)
|
||||
if r.Body != nil && r.Method != http.MethodGet && r.Method != http.MethodDelete {
|
||||
body = io.LimitReader(r.Body, 1<<16)
|
||||
}
|
||||
req, err := http.NewRequestWithContext(r.Context(), r.Method, target.String(), body)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusBadGateway, "node", "连不上节点")
|
||||
return
|
||||
}
|
||||
if srv.NodeToken != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+srv.NodeToken)
|
||||
}
|
||||
if r.Header.Get("Content-Type") != "" {
|
||||
req.Header.Set("Content-Type", r.Header.Get("Content-Type"))
|
||||
}
|
||||
resp, err := c.client.Do(req)
|
||||
if err != nil {
|
||||
log.Printf("center proxy failed server=%s", srv.ID)
|
||||
writeErr(w, http.StatusBadGateway, "node", "连不上节点")
|
||||
return
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode >= 300 && resp.StatusCode < 400 {
|
||||
writeErr(w, http.StatusBadGateway, "node", "节点地址发生了跳转")
|
||||
return
|
||||
}
|
||||
if ct := resp.Header.Get("Content-Type"); ct != "" {
|
||||
w.Header().Set("Content-Type", ct)
|
||||
}
|
||||
if strings.Contains(resp.Header.Get("Content-Type"), "event-stream") {
|
||||
w.Header().Set("Cache-Control", "no-cache")
|
||||
w.Header().Set("X-Accel-Buffering", "no")
|
||||
w.WriteHeader(resp.StatusCode)
|
||||
flusher, _ := w.(http.Flusher)
|
||||
buf := make([]byte, 32*1024)
|
||||
for {
|
||||
n, readErr := resp.Body.Read(buf)
|
||||
if n > 0 {
|
||||
if _, err := w.Write(buf[:n]); err != nil {
|
||||
return
|
||||
}
|
||||
if flusher != nil {
|
||||
flusher.Flush()
|
||||
}
|
||||
}
|
||||
if readErr != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
w.WriteHeader(resp.StatusCode)
|
||||
_, _ = io.Copy(w, resp.Body)
|
||||
}
|
||||
|
||||
func (c *Center) authorizedServer(w http.ResponseWriter, r *http.Request) (centerServer, bool) {
|
||||
group, _, ok := c.who(r)
|
||||
if !ok {
|
||||
writeErr(w, http.StatusUnauthorized, "unauthorized", "中心口令不正确或未提供")
|
||||
return centerServer{}, false
|
||||
}
|
||||
cfg, err := c.load()
|
||||
if err != nil {
|
||||
log.Printf("center config: %v", err)
|
||||
writeErr(w, http.StatusInternalServerError, "config", "中心配置无法读取")
|
||||
return centerServer{}, false
|
||||
}
|
||||
id := r.PathValue("id")
|
||||
for _, srv := range cfg.servers {
|
||||
if srv.ID != id {
|
||||
continue
|
||||
}
|
||||
if !containsString(srv.Groups, group) {
|
||||
writeErr(w, http.StatusForbidden, "forbidden", "这个口令不能使用该服务器")
|
||||
return centerServer{}, false
|
||||
}
|
||||
return srv, true
|
||||
}
|
||||
writeErr(w, http.StatusNotFound, "not_found", "没有这台服务器")
|
||||
return centerServer{}, false
|
||||
}
|
||||
|
||||
func (c *Center) who(r *http.Request) (string, string, bool) {
|
||||
raw := bearer(r.Header.Get("Authorization"))
|
||||
if raw == "" {
|
||||
return "", "", false
|
||||
}
|
||||
sum := hashSecret(raw)
|
||||
now := time.Now()
|
||||
c.mu.Lock()
|
||||
if s, ok := c.sessions[sum]; ok {
|
||||
if now.Before(s.exp) {
|
||||
c.mu.Unlock()
|
||||
return s.group, s.account, true
|
||||
}
|
||||
delete(c.sessions, sum)
|
||||
}
|
||||
c.mu.Unlock()
|
||||
cfg, err := c.load()
|
||||
if err != nil {
|
||||
log.Printf("center config: %v", err)
|
||||
return "", "", false
|
||||
}
|
||||
for _, tok := range cfg.tokens {
|
||||
if tok.TokenHash == "" || !c.groupKnown(cfg, tok.Group) {
|
||||
continue
|
||||
}
|
||||
if hashEqual(tok.TokenHash, raw) {
|
||||
return tok.Group, tok.Account, true
|
||||
}
|
||||
}
|
||||
return "", "", false
|
||||
}
|
||||
|
||||
func (c *Center) groupKnown(cfg centerConfig, id string) bool {
|
||||
for _, g := range cfg.groups {
|
||||
if g.ID == id {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (c *Center) load() (centerConfig, error) {
|
||||
var cfg centerConfig
|
||||
var groups struct {
|
||||
Groups []centerGroup `json:"groups"`
|
||||
}
|
||||
if err := readJSONFile(filepath.Join(c.Dir, "groups.json"), &groups); err != nil {
|
||||
return cfg, err
|
||||
}
|
||||
var tokens struct {
|
||||
Tokens []centerToken `json:"tokens"`
|
||||
}
|
||||
if err := readJSONFile(filepath.Join(c.Dir, "tokens.json"), &tokens); err != nil {
|
||||
return cfg, err
|
||||
}
|
||||
entries, err := os.ReadDir(filepath.Join(c.Dir, "servers"))
|
||||
if err != nil {
|
||||
return cfg, err
|
||||
}
|
||||
seen := map[string]struct{}{}
|
||||
var servers []centerServer
|
||||
for _, entry := range entries {
|
||||
if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".json") {
|
||||
continue
|
||||
}
|
||||
var srv centerServer
|
||||
if err := readJSONFile(filepath.Join(c.Dir, "servers", entry.Name()), &srv); err != nil {
|
||||
return cfg, err
|
||||
}
|
||||
if err := validateCenterServer(srv); err != nil {
|
||||
return cfg, err
|
||||
}
|
||||
if _, ok := seen[srv.ID]; ok {
|
||||
return cfg, fmt.Errorf("duplicate server id")
|
||||
}
|
||||
seen[srv.ID] = struct{}{}
|
||||
servers = append(servers, srv)
|
||||
}
|
||||
groupIDs := map[string]struct{}{}
|
||||
for _, g := range groups.Groups {
|
||||
if !validServerID(g.ID) {
|
||||
return cfg, fmt.Errorf("bad group id")
|
||||
}
|
||||
if _, ok := groupIDs[g.ID]; ok {
|
||||
return cfg, fmt.Errorf("duplicate group")
|
||||
}
|
||||
groupIDs[g.ID] = struct{}{}
|
||||
}
|
||||
for _, tok := range tokens.Tokens {
|
||||
if _, ok := groupIDs[tok.Group]; !ok {
|
||||
return cfg, fmt.Errorf("token group missing")
|
||||
}
|
||||
if !strings.HasPrefix(strings.TrimSpace(tok.TokenHash), "sha256:") {
|
||||
return cfg, fmt.Errorf("token hash missing")
|
||||
}
|
||||
}
|
||||
for _, srv := range servers {
|
||||
for _, g := range srv.Groups {
|
||||
if _, ok := groupIDs[g]; !ok {
|
||||
return cfg, fmt.Errorf("server group missing")
|
||||
}
|
||||
}
|
||||
}
|
||||
cfg.groups = groups.Groups
|
||||
cfg.tokens = tokens.Tokens
|
||||
cfg.servers = servers
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
func validateCenterServer(srv centerServer) error {
|
||||
if !validServerID(srv.ID) || strings.TrimSpace(srv.Name) == "" {
|
||||
return fmt.Errorf("bad server")
|
||||
}
|
||||
u, err := url.Parse(strings.TrimSpace(srv.ControlURL))
|
||||
if err != nil || u.Host == "" || (u.Scheme != "https" && u.Scheme != "http") || u.User != nil {
|
||||
return fmt.Errorf("bad control url")
|
||||
}
|
||||
if len(srv.Groups) == 0 {
|
||||
return fmt.Errorf("server has no group")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func readJSONFile(path string, dest any) error {
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
dec := json.NewDecoder(io.LimitReader(f, 1<<20))
|
||||
if err := dec.Decode(dest); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func containsString(list []string, want string) bool {
|
||||
for _, item := range list {
|
||||
if item == want {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func loadCenterKeyFile(dir string) (string, error) {
|
||||
if strings.TrimSpace(dir) == "" {
|
||||
return "", nil
|
||||
}
|
||||
b, err := os.ReadFile(filepath.Join(dir, "center.key"))
|
||||
if err != nil {
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return "", nil
|
||||
}
|
||||
return "", err
|
||||
}
|
||||
for _, line := range strings.Split(string(b), "\n") {
|
||||
line = strings.TrimSpace(strings.TrimRight(line, "\r"))
|
||||
if line == "" || strings.HasPrefix(line, "#") {
|
||||
continue
|
||||
}
|
||||
return line, nil
|
||||
}
|
||||
return "", nil
|
||||
}
|
||||
@@ -0,0 +1,306 @@
|
||||
// Copyright (C) 2026 言灸
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestCredentialRoundTrip(t *testing.T) {
|
||||
key := []byte("example-center-key")
|
||||
exp := time.Now().Add(time.Minute)
|
||||
token, err := mintCredential("lab-node", exp, key)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !verifyCredential(token, key, "lab-node", time.Now()) {
|
||||
t.Fatal("fresh credential rejected")
|
||||
}
|
||||
if verifyCredential(token, key, "other", time.Now()) {
|
||||
t.Fatal("wrong server accepted")
|
||||
}
|
||||
if verifyCredential(token, []byte("other-key"), "lab-node", time.Now()) {
|
||||
t.Fatal("wrong key accepted")
|
||||
}
|
||||
old, err := mintCredential("lab-node", time.Now().Add(-time.Second), key)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if verifyCredential(old, key, "lab-node", time.Now()) {
|
||||
t.Fatal("expired credential accepted")
|
||||
}
|
||||
if hashEqual("example-token", "example-token") {
|
||||
t.Fatal("raw secret was accepted as a stored hash")
|
||||
}
|
||||
if !hashEqual(hashSecret("example-token"), "example-token") {
|
||||
t.Fatal("hash mismatch")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCenterGroupsAndConfidentialProxy(t *testing.T) {
|
||||
const nodeToken = "super-secret-node-token"
|
||||
const hiddenHost = "secret-node.internal"
|
||||
node := newNode(nodeToken, true, nil, testLimits())
|
||||
node.ServerID = "lab-node"
|
||||
node.CenterKey = []byte("center-key")
|
||||
nodeSrv := httptest.NewServer(node.Handler())
|
||||
defer nodeSrv.Close()
|
||||
page := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
}))
|
||||
defer page.Close()
|
||||
|
||||
dir := t.TempDir()
|
||||
writeCenterFixture(t, dir, nodeSrv.URL, "https://"+hiddenHost+":8443", nodeToken, "center-key")
|
||||
mustWrite(t, filepath.Join(dir, "servers", "addr.json"), `{
|
||||
"id":"addr-node","name":"带地址的保密节点","controlUrl":"https://203.0.113.55:8443","groups":["lab"],"confidential":true,"nodeToken":"`+nodeToken+`"
|
||||
}`)
|
||||
center := newCenter(dir, "center-key")
|
||||
api := httptest.NewServer(center.Handler())
|
||||
defer api.Close()
|
||||
|
||||
catalog := centerGET(t, api.URL+"/v1/center/catalog", "lab-token")
|
||||
raw, _ := io.ReadAll(catalog.Body)
|
||||
catalog.Body.Close()
|
||||
if catalog.StatusCode != http.StatusOK {
|
||||
t.Fatalf("catalog %d %s", catalog.StatusCode, raw)
|
||||
}
|
||||
body := string(raw)
|
||||
if strings.Contains(body, hiddenHost) || strings.Contains(body, nodeToken) || strings.Contains(body, "203.0.113.55") {
|
||||
t.Fatalf("catalog leaked a hidden address or token: %s", body)
|
||||
}
|
||||
var parsed struct {
|
||||
Group string `json:"group"`
|
||||
Servers []struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Confidential bool `json:"confidential"`
|
||||
ControlURL string `json:"controlUrl"`
|
||||
Credential string `json:"credential"`
|
||||
} `json:"servers"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &parsed); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if parsed.Group != "lab" || len(parsed.Servers) != 4 {
|
||||
t.Fatalf("parsed %+v", parsed)
|
||||
}
|
||||
var publicCred, secretName string
|
||||
for _, srv := range parsed.Servers {
|
||||
if srv.Confidential {
|
||||
secretName = srv.Name
|
||||
if srv.ControlURL != "" || srv.Credential != "" {
|
||||
t.Fatalf("confidential item %+v", srv)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if srv.ControlURL != nodeSrv.URL || srv.Credential == "" || srv.Credential == nodeToken {
|
||||
t.Fatalf("public item %+v", srv)
|
||||
}
|
||||
publicCred = srv.Credential
|
||||
}
|
||||
if secretName != "保密节点" || publicCred == "" {
|
||||
t.Fatalf("names %+v", parsed.Servers)
|
||||
}
|
||||
if !verifyCredential(publicCred, node.CenterKey, "lab-node", time.Now()) {
|
||||
t.Fatal("catalog credential is not accepted by the node key")
|
||||
}
|
||||
direct := postJSON(t, nodeSrv.URL+"/v1/jobs", `{"target":"127.0.0.1","port":1,"profile":"tcp-connect","intervalMs":200,"timeoutMs":200,"durationSec":1}`)
|
||||
direct.Body.Close()
|
||||
req, _ := http.NewRequest(http.MethodPost, nodeSrv.URL+"/v1/jobs", strings.NewReader(`{"target":"127.0.0.1","port":1,"profile":"tcp-connect","intervalMs":200,"timeoutMs":200,"durationSec":1}`))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Authorization", "Bearer "+publicCred)
|
||||
res, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
res.Body.Close()
|
||||
if direct.StatusCode != http.StatusUnauthorized || res.StatusCode != http.StatusCreated {
|
||||
t.Fatalf("direct %d credential %d", direct.StatusCode, res.StatusCode)
|
||||
}
|
||||
|
||||
other := centerGET(t, api.URL+"/v1/center/catalog", "ops-token")
|
||||
otherRaw, _ := io.ReadAll(other.Body)
|
||||
other.Body.Close()
|
||||
if other.StatusCode != http.StatusOK || strings.Contains(string(otherRaw), "实验室节点") || strings.Contains(string(otherRaw), hiddenHost) {
|
||||
t.Fatalf("other group %d %s", other.StatusCode, otherRaw)
|
||||
}
|
||||
|
||||
denied := centerPOST(t, api.URL+"/v1/center/servers/secret-node/jobs", "ops-token", `{"target":"127.0.0.1","port":1,"profile":"tcp-connect","intervalMs":200,"timeoutMs":200,"durationSec":1}`)
|
||||
deniedRaw, _ := io.ReadAll(denied.Body)
|
||||
denied.Body.Close()
|
||||
if denied.StatusCode != http.StatusForbidden || strings.Contains(string(deniedRaw), hiddenHost) || strings.Contains(string(deniedRaw), nodeToken) {
|
||||
t.Fatalf("denied %d %s", denied.StatusCode, deniedRaw)
|
||||
}
|
||||
|
||||
jobBody := `{"target":"` + page.URL + `/","port":` + page.URL[strings.LastIndex(page.URL, ":")+1:] + `,"profile":"http","intervalMs":200,"timeoutMs":1500,"durationSec":2,"allowIPv4":true,"allowIPv6":false,"http":{"version":"1.1","method":"GET"}}`
|
||||
created := centerPOST(t, api.URL+"/v1/center/servers/secret-node/jobs", "lab-token", jobBody)
|
||||
createdRaw, _ := io.ReadAll(created.Body)
|
||||
created.Body.Close()
|
||||
if created.StatusCode != http.StatusCreated || strings.Contains(string(createdRaw), hiddenHost) || strings.Contains(string(createdRaw), nodeToken) {
|
||||
t.Fatalf("proxy create %d %s", created.StatusCode, createdRaw)
|
||||
}
|
||||
var job struct {
|
||||
JobID string `json:"jobId"`
|
||||
}
|
||||
if err := json.Unmarshal(createdRaw, &job); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
streamReq, _ := http.NewRequest(http.MethodGet, api.URL+"/v1/center/servers/secret-node/jobs/"+job.JobID+"/stream", nil)
|
||||
streamReq.Header.Set("Authorization", "Bearer lab-token")
|
||||
stream, err := http.DefaultClient.Do(streamReq)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer stream.Body.Close()
|
||||
sample := readSSEMap(t, stream.Body)
|
||||
if sample["status"] != "ok" {
|
||||
t.Fatalf("proxied sample %+v", sample)
|
||||
}
|
||||
note, _ := sample["note"].(string)
|
||||
if !strings.Contains(note, "不是丢包") {
|
||||
t.Fatalf("note %s", note)
|
||||
}
|
||||
|
||||
login := centerPOST(t, api.URL+"/v1/center/login", "", `{"account":"lab","password":"example-password"}`)
|
||||
loginRaw, _ := io.ReadAll(login.Body)
|
||||
login.Body.Close()
|
||||
if login.StatusCode != http.StatusOK || strings.Contains(string(loginRaw), "example-password") {
|
||||
t.Fatalf("login %d %s", login.StatusCode, loginRaw)
|
||||
}
|
||||
var session map[string]string
|
||||
if err := json.Unmarshal(loginRaw, &session); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if session["token"] == "" || session["token"] == "lab-token" {
|
||||
t.Fatalf("session %+v", session)
|
||||
}
|
||||
again := centerGET(t, api.URL+"/v1/center/catalog", session["token"])
|
||||
againRaw, _ := io.ReadAll(again.Body)
|
||||
again.Body.Close()
|
||||
if again.StatusCode != http.StatusOK || strings.Contains(string(againRaw), hiddenHost) {
|
||||
t.Fatalf("session catalog %d %s", again.StatusCode, againRaw)
|
||||
}
|
||||
stored, err := os.ReadFile(filepath.Join(dir, "tokens.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if strings.Contains(string(stored), "lab-token") || strings.Contains(string(stored), "example-password") {
|
||||
t.Fatalf("token file stored a raw secret: %s", stored)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExampleCenterLoads(t *testing.T) {
|
||||
center := newCenter("example-center", "")
|
||||
key, err := loadCenterKeyFile("example-center")
|
||||
if err != nil || key == "" {
|
||||
t.Fatal(err, key)
|
||||
}
|
||||
center.Key = []byte(key)
|
||||
if _, err := center.load(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
api := httptest.NewServer(center.Handler())
|
||||
defer api.Close()
|
||||
res := centerGET(t, api.URL+"/v1/center/catalog", "example-token")
|
||||
raw, _ := io.ReadAll(res.Body)
|
||||
res.Body.Close()
|
||||
if res.StatusCode != http.StatusOK {
|
||||
t.Fatalf("example catalog %d %s", res.StatusCode, raw)
|
||||
}
|
||||
if strings.Contains(string(raw), "secret-node.internal") || strings.Contains(string(raw), "example-secret-node-token") || strings.Contains(string(raw), "example-node-token") {
|
||||
t.Fatalf("example catalog leaked: %s", raw)
|
||||
}
|
||||
if !strings.Contains(string(raw), "实验室节点") || !strings.Contains(string(raw), "保密节点") {
|
||||
t.Fatalf("example catalog %s", raw)
|
||||
}
|
||||
}
|
||||
|
||||
func writeCenterFixture(t *testing.T, dir, publicURL, secretURL, nodeToken, key string) {
|
||||
t.Helper()
|
||||
mustWrite(t, filepath.Join(dir, "groups.json"), `{"groups":[{"id":"lab","name":"实验室"},{"id":"ops","name":"另一组"}]}`)
|
||||
mustWrite(t, filepath.Join(dir, "tokens.json"), `{"tokens":[`+
|
||||
`{"id":"lab-reader","group":"lab","account":"lab","tokenHash":"`+hashSecret("lab-token")+`","passwordHash":"`+hashSecret("example-password")+`"},`+
|
||||
`{"id":"ops-reader","group":"ops","account":"ops","tokenHash":"`+hashSecret("ops-token")+`"}`+
|
||||
`]}`)
|
||||
if err := os.MkdirAll(filepath.Join(dir, "servers"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mustWrite(t, filepath.Join(dir, "servers", "lab.json"), `{
|
||||
"id":"lab-node","name":"实验室节点","controlUrl":"`+publicURL+`","groups":["lab"],"confidential":false,"nodeToken":"`+nodeToken+`"
|
||||
}`)
|
||||
mustWrite(t, filepath.Join(dir, "servers", "secret.json"), `{
|
||||
"id":"secret-node","name":"保密节点","controlUrl":"`+publicURL+`","groups":["lab"],"confidential":true,"nodeToken":"`+nodeToken+`"
|
||||
}`)
|
||||
mustWrite(t, filepath.Join(dir, "servers", "hidden.json"), `{
|
||||
"id":"hidden-node","name":"另一台保密节点","controlUrl":"`+secretURL+`","groups":["lab"],"confidential":true,"nodeToken":"`+nodeToken+`"
|
||||
}`)
|
||||
mustWrite(t, filepath.Join(dir, "center.key"), key+"\n")
|
||||
}
|
||||
|
||||
func centerGET(t *testing.T, rawURL, token string) *http.Response {
|
||||
t.Helper()
|
||||
req, err := http.NewRequest(http.MethodGet, rawURL, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if token != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
}
|
||||
res, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
func centerPOST(t *testing.T, rawURL, token, body string) *http.Response {
|
||||
t.Helper()
|
||||
req, err := http.NewRequest(http.MethodPost, rawURL, strings.NewReader(body))
|
||||
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)
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
func readSSEMap(t *testing.T, r io.Reader) map[string]any {
|
||||
t.Helper()
|
||||
sc := bufio.NewScanner(r)
|
||||
var data string
|
||||
for sc.Scan() {
|
||||
line := sc.Text()
|
||||
if strings.HasPrefix(line, "data: ") {
|
||||
data = strings.TrimPrefix(line, "data: ")
|
||||
}
|
||||
if line == "" && data != "" && data != "{}" {
|
||||
var msg map[string]any
|
||||
if err := json.Unmarshal([]byte(data), &msg); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if status, _ := msg["status"].(string); status != "" && status != "pending" {
|
||||
return msg
|
||||
}
|
||||
data = ""
|
||||
}
|
||||
}
|
||||
t.Fatalf("no sample: %v", sc.Err())
|
||||
return nil
|
||||
}
|
||||
+32
-4
@@ -40,6 +40,9 @@ type Config struct {
|
||||
TLSCert string
|
||||
TLSKey string
|
||||
Verbose bool
|
||||
CenterDir string
|
||||
CenterKey string
|
||||
ServerID string
|
||||
LoadedFiles []string
|
||||
}
|
||||
|
||||
@@ -50,7 +53,7 @@ func (c Config) Summary() string {
|
||||
files = strings.Join(c.LoadedFiles, ", ")
|
||||
}
|
||||
return fmt.Sprintf(
|
||||
"生效配置 mode=%s bind=%s tcp_port=%d udp_port=%d control_addr=%s echo_token=%s node_token=%s allow_private=%t allow_nets=%s tls_cert=%s tls_key=%s verbose=%t 配置文件=%s",
|
||||
"生效配置 mode=%s bind=%s tcp_port=%d udp_port=%d control_addr=%s echo_token=%s node_token=%s allow_private=%t allow_nets=%s tls_cert=%s tls_key=%s verbose=%t center_dir=%s center_key=%s server_id=%s 配置文件=%s",
|
||||
c.Mode,
|
||||
c.Bind,
|
||||
c.TCPPort,
|
||||
@@ -63,6 +66,9 @@ func (c Config) Summary() string {
|
||||
pathState(c.TLSCert),
|
||||
pathState(c.TLSKey),
|
||||
c.Verbose,
|
||||
pathState(c.CenterDir),
|
||||
secretState(c.CenterKey),
|
||||
emptyState(c.ServerID),
|
||||
files,
|
||||
)
|
||||
}
|
||||
@@ -81,6 +87,13 @@ func pathState(s string) string {
|
||||
return s
|
||||
}
|
||||
|
||||
func emptyState(s string) string {
|
||||
if strings.TrimSpace(s) == "" {
|
||||
return "未设置"
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// loadConfig resolves configuration for a real process start.
|
||||
// A missing .env next to the executable or in the working directory is ignored.
|
||||
func loadConfig(args []string, environ []string) (Config, error) {
|
||||
@@ -107,12 +120,15 @@ func loadConfigAt(args []string, environ []string, exeDir, cwd string) (Config,
|
||||
udpPort := fs.Int("udp-port", defaultUDPPort, "UDP 反射端口,0 表示关闭,对应 NQ_UDP_PORT")
|
||||
token := fs.String("token", "", "回显口令,最长 32 字节,留空不校验,对应 NQ_TOKEN")
|
||||
nodeToken := fs.String("node-token", "", "节点口令,留空则节点公开,对应 NQ_NODE_TOKEN")
|
||||
mode := fs.String("mode", defaultMode, "reflector、node 或 both,对应 NQ_MODE")
|
||||
mode := fs.String("mode", defaultMode, "reflector、node、both、center 或 helper,对应 NQ_MODE")
|
||||
controlAddr := fs.String("control-addr", defaultControlAddr, "节点控制地址,对应 NQ_CONTROL_ADDR")
|
||||
allowPrivate := fs.Bool("allow-private", false, "允许探测本机和局域网,对应 NQ_ALLOW_PRIVATE")
|
||||
allowNets := fs.String("allow-nets", "", "额外允许的网段,逗号分隔,对应 NQ_ALLOW_NETS")
|
||||
tlsCert := fs.String("tls-cert", "", "控制端口证书,对应 NQ_TLS_CERT")
|
||||
tlsKey := fs.String("tls-key", "", "控制端口私钥,对应 NQ_TLS_KEY")
|
||||
centerDir := fs.String("center-dir", "", "中心配置目录,对应 NQ_CENTER_DIR")
|
||||
centerKey := fs.String("center-key", "", "中心短期凭证密钥,对应 NQ_CENTER_KEY。不要把真实密钥写进命令历史")
|
||||
serverID := fs.String("server-id", "", "本节点在中心里的编号,对应 NQ_SERVER_ID")
|
||||
envPath := fs.String("env", "", "额外的 .env 路径,会覆盖其他 .env;文件必须存在")
|
||||
verbose := fs.Bool("v", false, "打印每一包日志,对应 NQ_VERBOSE")
|
||||
fs.Usage = func() {
|
||||
@@ -121,6 +137,9 @@ func loadConfigAt(args []string, environ []string, exeDir, cwd string) (Config,
|
||||
优先级:命令行参数 > 环境变量 > .env 文件 > 内置默认值。
|
||||
启动时读取程序所在目录和当前目录下的 .env(路径相同则只读一次)。
|
||||
找不到这些 .env 不会报错。-env 指定的文件必须存在,并覆盖前面的 .env。
|
||||
-mode 可以是 reflector、node、both、center 或 helper。
|
||||
center 读取 -center-dir。helper 从标准输入读 HTTP 探测,供本机客户端使用。
|
||||
-hash-secret 从标准输入读一行,只打印哈希,不启动服务。
|
||||
|
||||
`)
|
||||
fs.PrintDefaults()
|
||||
@@ -152,6 +171,9 @@ func loadConfigAt(args []string, environ []string, exeDir, cwd string) (Config,
|
||||
cfg.AllowNets = pickString(visited["allow-nets"], *allowNets, "NQ_ALLOW_NETS", real, fileEnv, "")
|
||||
cfg.TLSCert = pickString(visited["tls-cert"], *tlsCert, "NQ_TLS_CERT", real, fileEnv, "")
|
||||
cfg.TLSKey = pickString(visited["tls-key"], *tlsKey, "NQ_TLS_KEY", real, fileEnv, "")
|
||||
cfg.CenterDir = pickString(visited["center-dir"], *centerDir, "NQ_CENTER_DIR", real, fileEnv, "")
|
||||
cfg.CenterKey = pickString(visited["center-key"], *centerKey, "NQ_CENTER_KEY", real, fileEnv, "")
|
||||
cfg.ServerID = pickString(visited["server-id"], *serverID, "NQ_SERVER_ID", real, fileEnv, "")
|
||||
|
||||
tcpRaw := pickString(visited["tcp-port"], strconv.Itoa(*tcpPort), "NQ_TCP_PORT", real, fileEnv, strconv.Itoa(defaultTCPPort))
|
||||
udpRaw := pickString(visited["udp-port"], strconv.Itoa(*udpPort), "NQ_UDP_PORT", real, fileEnv, strconv.Itoa(defaultUDPPort))
|
||||
@@ -195,9 +217,12 @@ func pickString(fromFlag bool, flagVal, envKey string, real, file map[string]str
|
||||
|
||||
func (c Config) validate() error {
|
||||
switch c.Mode {
|
||||
case "reflector", "node", "both":
|
||||
case "reflector", "node", "both", "center", "helper":
|
||||
default:
|
||||
return fmt.Errorf("NQ_MODE 必须是 reflector、node 或 both,当前是 %q", c.Mode)
|
||||
return fmt.Errorf("NQ_MODE 必须是 reflector、node、both、center 或 helper,当前是 %q", c.Mode)
|
||||
}
|
||||
if c.Mode == "center" && strings.TrimSpace(c.CenterDir) == "" {
|
||||
return fmt.Errorf("中心模式需要 NQ_CENTER_DIR 或 -center-dir")
|
||||
}
|
||||
if c.TCPPort < 0 || c.TCPPort > 65535 || c.UDPPort < 0 || c.UDPPort > 65535 {
|
||||
return fmt.Errorf("端口必须在 0 到 65535 之间")
|
||||
@@ -337,6 +362,9 @@ var knownEnvKeys = map[string]struct{}{
|
||||
"NQ_TLS_CERT": {},
|
||||
"NQ_TLS_KEY": {},
|
||||
"NQ_VERBOSE": {},
|
||||
"NQ_CENTER_DIR": {},
|
||||
"NQ_CENTER_KEY": {},
|
||||
"NQ_SERVER_ID": {},
|
||||
}
|
||||
|
||||
func parseDotEnv(r io.Reader) (map[string]string, error) {
|
||||
|
||||
@@ -157,7 +157,7 @@ func TestConfigValidation(t *testing.T) {
|
||||
|
||||
func TestSummaryMasksTokens(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
mustWrite(t, filepath.Join(dir, ".env"), "NQ_TOKEN=super-secret-echo\nNQ_NODE_TOKEN=super-secret-node\nNQ_MODE=both\n")
|
||||
mustWrite(t, filepath.Join(dir, ".env"), "NQ_TOKEN=super-secret-echo\nNQ_NODE_TOKEN=super-secret-node\nNQ_CENTER_KEY=super-secret-center\nNQ_MODE=both\n")
|
||||
cfg, err := loadConfigAt(nil, nil, dir, t.TempDir())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -166,7 +166,7 @@ func TestSummaryMasksTokens(t *testing.T) {
|
||||
if strings.Contains(line, "super-secret") {
|
||||
t.Fatal(line)
|
||||
}
|
||||
if !strings.Contains(line, "echo_token=已设置") || !strings.Contains(line, "node_token=已设置") {
|
||||
if !strings.Contains(line, "echo_token=已设置") || !strings.Contains(line, "node_token=已设置") || !strings.Contains(line, "center_key=已设置") {
|
||||
t.Fatal(line)
|
||||
}
|
||||
plain, err := loadConfigAt(nil, nil, t.TempDir(), t.TempDir())
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
// Copyright (C) 2026 言灸
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"crypto/hmac"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// hashSecret returns the stored form of a token or password.
|
||||
// Only this hash is written to the center config. The raw value is not.
|
||||
func hashSecret(secret string) string {
|
||||
sum := sha256.Sum256([]byte(secret))
|
||||
return "sha256:" + hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
func hashEqual(stored, secret string) bool {
|
||||
stored = strings.TrimSpace(stored)
|
||||
want := hashSecret(secret)
|
||||
if len(stored) != len(want) {
|
||||
subtle.ConstantTimeCompare([]byte(want), []byte(want))
|
||||
return false
|
||||
}
|
||||
return subtle.ConstantTimeCompare([]byte(stored), []byte(want)) == 1
|
||||
}
|
||||
|
||||
func randomToken() (string, error) {
|
||||
var b [32]byte
|
||||
if _, err := rand.Read(b[:]); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return hex.EncodeToString(b[:]), nil
|
||||
}
|
||||
|
||||
// mintCredential signs a short-lived node credential. It is not the node's
|
||||
// long-lived token. The payload is the server id and an expiry, nothing else.
|
||||
func mintCredential(serverID string, exp time.Time, key []byte) (string, error) {
|
||||
if len(key) == 0 {
|
||||
return "", errors.New("missing center key")
|
||||
}
|
||||
if !validServerID(serverID) {
|
||||
return "", errors.New("bad server id")
|
||||
}
|
||||
payload := serverID + "|" + strconv.FormatInt(exp.Unix(), 10)
|
||||
enc := base64.RawURLEncoding.EncodeToString([]byte(payload))
|
||||
mac := hmac.New(sha256.New, key)
|
||||
_, _ = mac.Write([]byte(enc))
|
||||
sig := base64.RawURLEncoding.EncodeToString(mac.Sum(nil))
|
||||
return "nq1." + enc + "." + sig, nil
|
||||
}
|
||||
|
||||
func verifyCredential(token string, key []byte, serverID string, now time.Time) bool {
|
||||
if len(key) == 0 || !validServerID(serverID) || token == "" {
|
||||
return false
|
||||
}
|
||||
parts := strings.Split(token, ".")
|
||||
if len(parts) != 3 || parts[0] != "nq1" || parts[1] == "" || parts[2] == "" {
|
||||
return false
|
||||
}
|
||||
mac := hmac.New(sha256.New, key)
|
||||
_, _ = mac.Write([]byte(parts[1]))
|
||||
expected := mac.Sum(nil)
|
||||
got, err := base64.RawURLEncoding.DecodeString(parts[2])
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
if !hmac.Equal(expected, got) {
|
||||
return false
|
||||
}
|
||||
raw, err := base64.RawURLEncoding.DecodeString(parts[1])
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
id, expText, ok := strings.Cut(string(raw), "|")
|
||||
if !ok || id != serverID {
|
||||
return false
|
||||
}
|
||||
expUnix, err := strconv.ParseInt(expText, 10, 64)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
exp := time.Unix(expUnix, 0)
|
||||
return now.Before(exp)
|
||||
}
|
||||
|
||||
func validServerID(id string) bool {
|
||||
if id == "" || len(id) > 64 {
|
||||
return false
|
||||
}
|
||||
for _, r := range id {
|
||||
switch {
|
||||
case r >= 'a' && r <= 'z':
|
||||
case r >= 'A' && r <= 'Z':
|
||||
case r >= '0' && r <= '9':
|
||||
case r == '.' || r == '_' || r == '-':
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
[Unit]
|
||||
Description=网络质量探测中心
|
||||
After=network-online.target
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
WorkingDirectory=/opt/netquality
|
||||
ExecStart=/opt/netquality/netquality-reflector
|
||||
Environment=NQ_MODE=center
|
||||
Environment=NQ_CENTER_DIR=/etc/netquality/center
|
||||
Environment=NQ_CONTROL_ADDR=127.0.0.1:8443
|
||||
ReadOnlyPaths=/etc/netquality/center
|
||||
Restart=on-failure
|
||||
RestartSec=2
|
||||
NoNewPrivileges=true
|
||||
ProtectSystem=strict
|
||||
ProtectHome=true
|
||||
PrivateTmp=true
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -0,0 +1,18 @@
|
||||
# 中心配置示例
|
||||
|
||||
这里的口令、密码和密钥都是占位,只能用来在本机看目录长什么样。不要拿到公网上去用。
|
||||
|
||||
目录:
|
||||
|
||||
- `groups.json`:用户组。一个中心可以有很多组。
|
||||
- `tokens.json`:只保存口令和密码的 `sha256:` 哈希,不保存原文。每一条口令只属于一个组。
|
||||
- `servers/*.json`:中心分配的显示名、节点控制地址、哪些组可以用、是否保密。节点的长期口令只写在这里,发给中心用来转发,不会交给客户端。
|
||||
- `center.key`:签发短期凭证的密钥。节点上的 `NQ_CENTER_KEY` 要和它相同,`NQ_SERVER_ID` 要和对应服务器文件的 `id` 相同。
|
||||
|
||||
示例账号 `lab`,口令原文 `example-token`,密码原文 `example-password`。哈希用:
|
||||
|
||||
```bash
|
||||
printf '%s' 'example-token' | ./netquality-reflector -hash-secret
|
||||
```
|
||||
|
||||
`实验室节点` 不是保密的,客户端能看到地址,并用短期凭证直接连接。`保密节点` 的地址只留在这份配置里,目录接口不会把它交出去,探测由中心转发。
|
||||
@@ -0,0 +1,2 @@
|
||||
# 这是示例密钥,不能用于真正的部署。换成只有中心和对应节点知道的一长串随机字符。
|
||||
example-center-key
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"groups": [
|
||||
{"id": "lab", "name": "实验室"}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"id": "lab-node",
|
||||
"name": "实验室节点",
|
||||
"controlUrl": "https://127.0.0.1:8443",
|
||||
"groups": ["lab"],
|
||||
"confidential": false,
|
||||
"nodeToken": "example-node-token"
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"id": "secret-node",
|
||||
"name": "保密节点",
|
||||
"controlUrl": "https://secret-node.internal:8443",
|
||||
"groups": ["lab"],
|
||||
"confidential": true,
|
||||
"nodeToken": "example-secret-node-token"
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"tokens": [
|
||||
{
|
||||
"id": "lab-reader",
|
||||
"group": "lab",
|
||||
"account": "lab",
|
||||
"tokenHash": "sha256:4d1566a1d7df42a8517456d60ea06ed284e535cfe4c956aa6ee172dbcdf945f7",
|
||||
"passwordHash": "sha256:a4b7fbda9179055ba005b83fe1d9d558c85e5f6afc2ce4071439ecdab864b98e"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
// Copyright (C) 2026 言灸
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// familyError is a user-facing refusal to use an address family.
|
||||
type familyError struct{ msg string }
|
||||
|
||||
func (e *familyError) Error() string { return e.msg }
|
||||
|
||||
func familyMessage(msg string) error { return &familyError{msg: msg} }
|
||||
|
||||
// filterFamily keeps only the address families the user turned on.
|
||||
// A literal address of a disabled family is refused. When every resolved
|
||||
// address is in a disabled family, the probe does not start.
|
||||
func filterFamily(host string, ips []net.IP, allow4, allow6 bool) ([]net.IP, error) {
|
||||
if !allow4 && !allow6 {
|
||||
return nil, familyMessage("IPv4 和 IPv6 都已关闭,无法开始探测")
|
||||
}
|
||||
literal := net.ParseIP(strings.Trim(strings.TrimSpace(host), "[]"))
|
||||
if literal != nil {
|
||||
if literal.To4() != nil && !allow4 {
|
||||
return nil, familyMessage("目标是 IPv4 地址,但 IPv4 已关闭")
|
||||
}
|
||||
if literal.To4() == nil && !allow6 {
|
||||
return nil, familyMessage("目标是 IPv6 地址,但 IPv6 已关闭")
|
||||
}
|
||||
}
|
||||
out := make([]net.IP, 0, len(ips))
|
||||
for _, ip := range ips {
|
||||
if ip == nil {
|
||||
continue
|
||||
}
|
||||
if ip.To4() != nil {
|
||||
if allow4 {
|
||||
out = append(out, ip)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if allow6 {
|
||||
out = append(out, ip)
|
||||
}
|
||||
}
|
||||
if len(out) == 0 {
|
||||
return nil, familyMessage("解析到的地址都不在已打开的地址族里")
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func flagOrDefault(v *bool, fallback bool) bool {
|
||||
if v == nil {
|
||||
return fallback
|
||||
}
|
||||
return *v
|
||||
}
|
||||
|
||||
// preferIP rotates ips so preferred is first when it is one of them.
|
||||
func preferIP(ips []net.IP, preferred net.IP) []net.IP {
|
||||
if preferred == nil || len(ips) == 0 {
|
||||
return ips
|
||||
}
|
||||
for i, ip := range ips {
|
||||
if ip.Equal(preferred) {
|
||||
if i == 0 {
|
||||
return ips
|
||||
}
|
||||
out := make([]net.IP, 0, len(ips))
|
||||
out = append(out, ips[i:]...)
|
||||
out = append(out, ips[:i]...)
|
||||
return out
|
||||
}
|
||||
}
|
||||
return ips
|
||||
}
|
||||
|
||||
func asFamily(err error) (*familyError, bool) {
|
||||
var fe *familyError
|
||||
if errors.As(err, &fe) {
|
||||
return fe, true
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
@@ -1,3 +1,21 @@
|
||||
module netquality/server
|
||||
|
||||
go 1.22
|
||||
|
||||
require github.com/quic-go/quic-go v0.49.0
|
||||
|
||||
require (
|
||||
github.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572 // indirect
|
||||
github.com/google/pprof v0.0.0-20210407192527-94a9f03dee38 // indirect
|
||||
github.com/onsi/ginkgo/v2 v2.9.5 // indirect
|
||||
github.com/quic-go/qpack v0.5.1 // indirect
|
||||
go.uber.org/mock v0.5.0 // indirect
|
||||
golang.org/x/crypto v0.26.0 // indirect
|
||||
golang.org/x/exp v0.0.0-20240506185415-9bf2ced13842 // indirect
|
||||
golang.org/x/mod v0.18.0 // indirect
|
||||
golang.org/x/net v0.28.0 // indirect
|
||||
golang.org/x/sync v0.8.0 // indirect
|
||||
golang.org/x/sys v0.23.0 // indirect
|
||||
golang.org/x/text v0.17.0 // indirect
|
||||
golang.org/x/tools v0.22.0 // indirect
|
||||
)
|
||||
@@ -0,0 +1,58 @@
|
||||
github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI=
|
||||
github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI=
|
||||
github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/go-logr/logr v1.2.4 h1:g01GSCwiDw2xSZfjJ2/T9M+S6pFdcNtFYsp+Y43HYDQ=
|
||||
github.com/go-logr/logr v1.2.4/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
|
||||
github.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572 h1:tfuBGBXKqDEevZMzYi5KSi8KkcZtzBcTgAUUtapy0OI=
|
||||
github.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572/go.mod h1:9Pwr4B2jHnOSGXyyzV8ROjYa2ojvAY6HCGYYfMoC3Ls=
|
||||
github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg=
|
||||
github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY=
|
||||
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
|
||||
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||
github.com/google/pprof v0.0.0-20210407192527-94a9f03dee38 h1:yAJXTCF9TqKcTiHJAE8dj7HMvPfh66eeA2JYW7eFpSE=
|
||||
github.com/google/pprof v0.0.0-20210407192527-94a9f03dee38/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE=
|
||||
github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc=
|
||||
github.com/onsi/ginkgo/v2 v2.9.5 h1:+6Hr4uxzP4XIUyAkg61dWBw8lb/gc4/X5luuxN/EC+Q=
|
||||
github.com/onsi/ginkgo/v2 v2.9.5/go.mod h1:tvAoo1QUJwNEU2ITftXTpR7R1RbCzoZUOs3RonqW57k=
|
||||
github.com/onsi/gomega v1.27.6 h1:ENqfyGeS5AX/rlXDd/ETokDz93u0YufY1Pgxuy/PvWE=
|
||||
github.com/onsi/gomega v1.27.6/go.mod h1:PIQNjfQwkP3aQAH7lf7j87O/5FiNr+ZR8+ipb+qQlhg=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/quic-go/qpack v0.5.1 h1:giqksBPnT/HDtZ6VhtFKgoLOWmlyo9Ei6u9PqzIMbhI=
|
||||
github.com/quic-go/qpack v0.5.1/go.mod h1:+PC4XFrEskIVkcLzpEkbLqq1uCoxPhQuvK5rH1ZgaEg=
|
||||
github.com/quic-go/quic-go v0.49.0 h1:w5iJHXwHxs1QxyBv1EHKuC50GX5to8mJAxvtnttJp94=
|
||||
github.com/quic-go/quic-go v0.49.0/go.mod h1:s2wDnmCdooUQBmQfpUSTCYBl1/D4FcqbULMMkASvR6s=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
|
||||
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||
go.uber.org/mock v0.5.0 h1:KAMbZvZPyBPWgD14IrIQ38QCyjwpvVVV6K/bHl1IwQU=
|
||||
go.uber.org/mock v0.5.0/go.mod h1:ge71pBPLYDk7QIi1LupWxdAykm7KIEFchiOqd6z7qMM=
|
||||
golang.org/x/crypto v0.26.0 h1:RrRspgV4mU+YwB4FYnuBoKsUapNIL5cohGAmSH3azsw=
|
||||
golang.org/x/crypto v0.26.0/go.mod h1:GY7jblb9wI+FOo5y8/S2oY4zWP07AkOJ4+jxCqdqn54=
|
||||
golang.org/x/exp v0.0.0-20240506185415-9bf2ced13842 h1:vr/HnozRka3pE4EsMEg1lgkXJkTFJCVUX+S/ZT6wYzM=
|
||||
golang.org/x/exp v0.0.0-20240506185415-9bf2ced13842/go.mod h1:XtvwrStGgqGPLc4cjQfWqZHG1YFdYs6swckp8vpsjnc=
|
||||
golang.org/x/mod v0.18.0 h1:5+9lSbEzPSdWkH32vYPBwEpX8KwDbM52Ud9xBUvNlb0=
|
||||
golang.org/x/mod v0.18.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
|
||||
golang.org/x/net v0.28.0 h1:a9JDOJc5GMUJ0+UDqmLT86WiEy7iWyIhz8gz8E4e5hE=
|
||||
golang.org/x/net v0.28.0/go.mod h1:yqtgsTWOOnlGLG9GFRrK3++bGOUEkNBoHZc8MEDWPNg=
|
||||
golang.org/x/sync v0.8.0 h1:3NFvSEYkUoMifnESzZl15y791HH1qU2xm6eCJU5ZPXQ=
|
||||
golang.org/x/sync v0.8.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||
golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.23.0 h1:YfKFowiIMvtgl1UERQoTPPToxltDeZfbj4H7dVUCwmM=
|
||||
golang.org/x/sys v0.23.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/text v0.17.0 h1:XtiM5bkSOt+ewxlOE/aE/AKEHibwj/6gvWMl9Rsh0Qc=
|
||||
golang.org/x/text v0.17.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY=
|
||||
golang.org/x/time v0.5.0 h1:o7cqy6amK/52YcAKIPlM3a+Fpj35zvRj2TP+e1xFSfk=
|
||||
golang.org/x/time v0.5.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM=
|
||||
golang.org/x/tools v0.22.0 h1:gqSGLZqv+AI9lIQzniJ0nZDRG5GBPsSi+DRNHWNz6yA=
|
||||
golang.org/x/tools v0.22.0/go.mod h1:aCwcsjqvq7Yqt6TNyX7QMU2enbQ/Gt0bo6krSeEri+c=
|
||||
google.golang.org/protobuf v1.33.0 h1:uNO2rsAINq/JlFpSdYEKIZ0uKD/R9cpdv0T+yoGwGmI=
|
||||
google.golang.org/protobuf v1.33.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
@@ -0,0 +1,114 @@
|
||||
// Copyright (C) 2026 言灸
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// runHelper speaks one JSON request per line and writes one JSON outcome.
|
||||
// The Flutter client uses this for local HTTP probes so it runs the same
|
||||
// engine as a remote node. Logs stay off stdout.
|
||||
func runHelper(r io.Reader, w io.Writer) error {
|
||||
sc := bufio.NewScanner(r)
|
||||
sc.Buffer(make([]byte, 64*1024), 1<<20)
|
||||
enc := json.NewEncoder(w)
|
||||
for sc.Scan() {
|
||||
line := strings.TrimSpace(sc.Text())
|
||||
if line == "" {
|
||||
continue
|
||||
}
|
||||
var req helperRequest
|
||||
if err := json.Unmarshal([]byte(line), &req); err != nil {
|
||||
_ = enc.Encode(outcomeWire(httpFail(statusError, "请求无法解析")))
|
||||
continue
|
||||
}
|
||||
if req.Profile != "" && req.Profile != "http" {
|
||||
_ = enc.Encode(outcomeWire(httpFail(statusError, "本机引擎目前只负责 HTTP 探测")))
|
||||
continue
|
||||
}
|
||||
out := probeHTTP(context.Background(), req.ctxInput())
|
||||
_ = enc.Encode(outcomeWire(out))
|
||||
}
|
||||
return sc.Err()
|
||||
}
|
||||
|
||||
type helperRequest struct {
|
||||
Profile string `json:"profile"`
|
||||
Target string `json:"target"`
|
||||
Port int `json:"port"`
|
||||
TimeoutMs int `json:"timeoutMs"`
|
||||
AllowIPv4 *bool `json:"allowIPv4"`
|
||||
AllowIPv6 *bool `json:"allowIPv6"`
|
||||
HTTP *httpOptionsReq `json:"http"`
|
||||
Insecure bool `json:"insecure"`
|
||||
}
|
||||
|
||||
type httpOptionsReq struct {
|
||||
Version string `json:"version"`
|
||||
Resolve string `json:"resolve"`
|
||||
Method string `json:"method"`
|
||||
Body string `json:"body"`
|
||||
Referer string `json:"referer"`
|
||||
UserAgent string `json:"userAgent"`
|
||||
Cookies string `json:"cookies"`
|
||||
MaxRedirects *int `json:"maxRedirects"`
|
||||
}
|
||||
|
||||
func (h helperRequest) ctxInput() HTTPInput {
|
||||
in := HTTPInput{
|
||||
Target: h.Target,
|
||||
Port: h.Port,
|
||||
Timeout: 0,
|
||||
Allow4: flagOrDefault(h.AllowIPv4, true),
|
||||
Allow6: flagOrDefault(h.AllowIPv6, true),
|
||||
CheckSafety: false,
|
||||
AllowPrivate: true,
|
||||
Insecure: h.Insecure,
|
||||
}
|
||||
if h.TimeoutMs > 0 {
|
||||
in.Timeout = time.Duration(h.TimeoutMs) * time.Millisecond
|
||||
}
|
||||
applyHTTPOptions(&in, h.HTTP)
|
||||
return in
|
||||
}
|
||||
|
||||
func applyHTTPOptions(in *HTTPInput, opt *httpOptionsReq) {
|
||||
if opt == nil {
|
||||
return
|
||||
}
|
||||
in.Version = opt.Version
|
||||
in.Resolve = opt.Resolve
|
||||
in.Method = opt.Method
|
||||
in.Body = opt.Body
|
||||
in.Referer = opt.Referer
|
||||
in.UserAgent = opt.UserAgent
|
||||
in.Cookies = opt.Cookies
|
||||
if opt.MaxRedirects != nil {
|
||||
in.MaxRedirects = *opt.MaxRedirects
|
||||
in.MaxSet = true
|
||||
}
|
||||
}
|
||||
|
||||
type wireOutcome struct {
|
||||
Status string `json:"status"`
|
||||
Kind string `json:"kind"`
|
||||
RttMs *float64 `json:"rttMs,omitempty"`
|
||||
Note string `json:"note,omitempty"`
|
||||
Detail map[string]string `json:"detail,omitempty"`
|
||||
}
|
||||
|
||||
func outcomeWire(o Outcome) wireOutcome {
|
||||
w := wireOutcome{Status: o.Status, Kind: o.Kind, Note: o.Note, Detail: o.Detail}
|
||||
if o.HasRtt {
|
||||
ms := float64(o.Rtt) / float64(1e6)
|
||||
w.RttMs = &ms
|
||||
}
|
||||
return w
|
||||
}
|
||||
@@ -0,0 +1,646 @@
|
||||
// Copyright (C) 2026 言灸
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptrace"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/quic-go/quic-go"
|
||||
"github.com/quic-go/quic-go/http3"
|
||||
)
|
||||
|
||||
const httpBodyCap = 32 << 10
|
||||
|
||||
// HTTPInput is one HTTP probe. The same function serves the node and the
|
||||
// local helper, so desktop, Android and remote nodes share this engine.
|
||||
type HTTPInput struct {
|
||||
Target string
|
||||
Port int
|
||||
Version string
|
||||
Resolve string
|
||||
Method string
|
||||
Body string
|
||||
Referer string
|
||||
UserAgent string
|
||||
Cookies string
|
||||
MaxRedirects int
|
||||
MaxSet bool
|
||||
Timeout time.Duration
|
||||
Allow4 bool
|
||||
Allow6 bool
|
||||
CheckSafety bool
|
||||
AllowPrivate bool
|
||||
Extra []*net.IPNet
|
||||
Resolver resolver
|
||||
Insecure bool
|
||||
Roots *x509.CertPool
|
||||
Preferred net.IP
|
||||
}
|
||||
|
||||
func probeHTTP(ctx context.Context, in HTTPInput) Outcome {
|
||||
started := time.Now()
|
||||
version, err := normalizeHTTPVersion(in.Version)
|
||||
if err != nil {
|
||||
return httpFail(statusError, err.Error())
|
||||
}
|
||||
method := strings.ToUpper(strings.TrimSpace(in.Method))
|
||||
if method == "" {
|
||||
method = http.MethodGet
|
||||
}
|
||||
if method != http.MethodGet && method != http.MethodPost {
|
||||
return httpFail(statusError, "HTTP 方法只支持 GET 和 POST")
|
||||
}
|
||||
if method != http.MethodPost {
|
||||
in.Body = ""
|
||||
}
|
||||
if len(in.Body) > 64<<10 || len(in.Referer) > 4096 || len(in.UserAgent) > 4096 || len(in.Cookies) > 4096 {
|
||||
return httpFail(statusError, "HTTP 选项超过长度限制")
|
||||
}
|
||||
page, err := buildHTTPURL(in.Target, in.Port)
|
||||
if err != nil {
|
||||
return httpFail(statusError, err.Error())
|
||||
}
|
||||
if (version == "2" || version == "3") && page.Scheme != "https" {
|
||||
name := "HTTP/2"
|
||||
if version == "3" {
|
||||
name = "HTTP/3"
|
||||
}
|
||||
return httpFail(statusError, "强制 "+name+" 需要 HTTPS,不会降级")
|
||||
}
|
||||
maxRedirect := in.MaxRedirects
|
||||
if !in.MaxSet && maxRedirect == 0 {
|
||||
maxRedirect = 5
|
||||
}
|
||||
if maxRedirect < 0 || maxRedirect > 20 {
|
||||
return httpFail(statusError, "跳转次数需要在 0 到 20 之间")
|
||||
}
|
||||
if in.Timeout <= 0 {
|
||||
in.Timeout = 1500 * time.Millisecond
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, in.Timeout)
|
||||
defer cancel()
|
||||
|
||||
originHost := page.Hostname()
|
||||
var chain []string
|
||||
var dnsSum, connSum, tlsSum time.Duration
|
||||
var used net.IP
|
||||
var gotVersion string
|
||||
var ttfb time.Duration
|
||||
current := page
|
||||
currentMethod := method
|
||||
currentBody := in.Body
|
||||
seen := map[string]int{}
|
||||
|
||||
for followed := 0; ; followed++ {
|
||||
if seen[current.String()] > 2 {
|
||||
return httpDone(started, dnsSum, connSum, tlsSum, ttfb, used, gotVersion, 0, current.String(), chain, statusError, "跳转出现了循环")
|
||||
}
|
||||
seen[current.String()]++
|
||||
resp, hop, err := in.do(ctx, current, currentMethod, currentBody, version, originHost)
|
||||
dnsSum += hop.dns
|
||||
connSum += hop.connect
|
||||
tlsSum += hop.tls
|
||||
if hop.addr != nil {
|
||||
used = hop.addr
|
||||
}
|
||||
if hop.version != "" {
|
||||
gotVersion = hop.version
|
||||
}
|
||||
if err != nil {
|
||||
if ctx.Err() != nil && !errors.Is(err, errForbiddenTarget) {
|
||||
if fe, ok := asFamily(err); ok {
|
||||
return httpDone(started, dnsSum, connSum, tlsSum, ttfb, used, gotVersion, 0, current.String(), chain, statusError, fe.Error())
|
||||
}
|
||||
}
|
||||
return httpDone(started, dnsSum, connSum, tlsSum, ttfb, used, gotVersion, 0, current.String(), chain, hop.status, hop.note)
|
||||
}
|
||||
if hop.ttfb > 0 && ttfb == 0 {
|
||||
ttfb = time.Since(started)
|
||||
}
|
||||
if hop.ttfb > 0 {
|
||||
ttfb = time.Since(started)
|
||||
}
|
||||
code := resp.StatusCode
|
||||
finalURL := current.String()
|
||||
if resp.Request != nil && resp.Request.URL != nil {
|
||||
finalURL = resp.Request.URL.String()
|
||||
}
|
||||
chain = append(chain, strconv.Itoa(code)+" "+finalURL)
|
||||
loc := resp.Header.Get("Location")
|
||||
redirect := code >= 300 && code < 400 && loc != ""
|
||||
if !redirect {
|
||||
_, _ = io.CopyN(io.Discard, resp.Body, httpBodyCap)
|
||||
_ = resp.Body.Close()
|
||||
note := fmt.Sprintf("HTTP %d", code)
|
||||
if code >= 400 {
|
||||
note += "。这是服务器返回的状态,不是丢包"
|
||||
}
|
||||
out := httpDone(started, dnsSum, connSum, tlsSum, ttfb, used, gotVersion, code, finalURL, chain, statusOK, note)
|
||||
if hop.fallback != "" {
|
||||
out.Detail["fallback"] = hop.fallback
|
||||
}
|
||||
out.HasRtt = true
|
||||
out.Rtt = time.Since(started)
|
||||
return out
|
||||
}
|
||||
_ = resp.Body.Close()
|
||||
if followed >= maxRedirect {
|
||||
return httpDone(started, dnsSum, connSum, tlsSum, ttfb, used, gotVersion, code, finalURL, chain, statusError, fmt.Sprintf("超过了最多 %d 次跳转", maxRedirect))
|
||||
}
|
||||
next, err := current.Parse(loc)
|
||||
if err != nil || next.Host == "" || (next.Scheme != "http" && next.Scheme != "https") {
|
||||
return httpDone(started, dnsSum, connSum, tlsSum, ttfb, used, gotVersion, code, finalURL, chain, statusError, "跳转地址无效")
|
||||
}
|
||||
current = next
|
||||
if code == http.StatusMovedPermanently || code == http.StatusFound || code == http.StatusSeeOther {
|
||||
currentMethod = http.MethodGet
|
||||
currentBody = ""
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type httpHop struct {
|
||||
dns time.Duration
|
||||
connect time.Duration
|
||||
tls time.Duration
|
||||
ttfb time.Duration
|
||||
addr net.IP
|
||||
version string
|
||||
status string
|
||||
note string
|
||||
fallback string
|
||||
}
|
||||
|
||||
func (in HTTPInput) do(ctx context.Context, page *url.URL, method, body, version, originHost string) (*http.Response, httpHop, error) {
|
||||
connectHost := page.Hostname()
|
||||
if strings.EqualFold(connectHost, originHost) && strings.TrimSpace(in.Resolve) != "" {
|
||||
connectHost = strings.TrimSpace(in.Resolve)
|
||||
}
|
||||
ips, dnsDur, err := in.lookup(ctx, connectHost)
|
||||
hop := httpHop{dns: dnsDur, status: statusError, note: "连接失败"}
|
||||
if err != nil {
|
||||
hop.status, hop.note = classifyHTTPLookup(err, version)
|
||||
return nil, hop, err
|
||||
}
|
||||
ips = preferIP(ips, in.Preferred)
|
||||
var last error
|
||||
var skipped []string
|
||||
for _, ip := range ips {
|
||||
resp, one, err := in.exchange(ctx, page, method, body, version, ip)
|
||||
one.dns = dnsDur
|
||||
if err == nil {
|
||||
if len(skipped) > 0 {
|
||||
one.fallback = "已尝试 " + strings.Join(skipped, "、") + ",随后改用 " + familyOf(ip) + " " + ip.String()
|
||||
}
|
||||
return resp, one, nil
|
||||
}
|
||||
last = err
|
||||
hop = one
|
||||
hop.dns = dnsDur
|
||||
if !retryHTTP(err) {
|
||||
break
|
||||
}
|
||||
skipped = append(skipped, familyOf(ip)+" "+ip.String())
|
||||
}
|
||||
if last == nil {
|
||||
last = errors.New("连接失败")
|
||||
}
|
||||
if hop.note == "" || hop.note == "skipped" {
|
||||
hop.status, hop.note = classifyHTTPDial(last, version)
|
||||
}
|
||||
if len(skipped) > 0 && hop.note != "" {
|
||||
hop.note = "已尝试 " + strings.Join(skipped, "、") + "。" + hop.note
|
||||
}
|
||||
return nil, hop, last
|
||||
}
|
||||
|
||||
func (in HTTPInput) exchange(ctx context.Context, page *url.URL, method, body, version string, ip net.IP) (*http.Response, httpHop, error) {
|
||||
hop := httpHop{addr: ip, status: statusError, note: "连接失败"}
|
||||
req, err := http.NewRequestWithContext(ctx, method, page.String(), strings.NewReader(body))
|
||||
if err != nil {
|
||||
hop.note = "无法构造 HTTP 请求"
|
||||
return nil, hop, err
|
||||
}
|
||||
if body != "" {
|
||||
req.ContentLength = int64(len(body))
|
||||
req.Header.Set("Content-Type", "text/plain; charset=utf-8")
|
||||
}
|
||||
if in.Referer != "" {
|
||||
req.Header.Set("Referer", in.Referer)
|
||||
}
|
||||
if in.UserAgent != "" {
|
||||
req.Header.Set("User-Agent", in.UserAgent)
|
||||
}
|
||||
if in.Cookies != "" {
|
||||
req.Header.Set("Cookie", in.Cookies)
|
||||
}
|
||||
var connectDur, tlsDur time.Duration
|
||||
var connectStart, tlsStart time.Time
|
||||
trace := &httptrace.ClientTrace{
|
||||
ConnectStart: func(string, string) { connectStart = time.Now() },
|
||||
ConnectDone: func(string, string, error) {
|
||||
if !connectStart.IsZero() {
|
||||
connectDur = time.Since(connectStart)
|
||||
}
|
||||
},
|
||||
TLSHandshakeStart: func() { tlsStart = time.Now() },
|
||||
TLSHandshakeDone: func(tls.ConnectionState, error) {
|
||||
if !tlsStart.IsZero() {
|
||||
tlsDur = time.Since(tlsStart)
|
||||
}
|
||||
},
|
||||
GotFirstResponseByte: func() { hop.ttfb = time.Nanosecond },
|
||||
}
|
||||
req = req.WithContext(httptrace.WithClientTrace(req.Context(), trace))
|
||||
|
||||
var resp *http.Response
|
||||
switch version {
|
||||
case "3":
|
||||
t0 := time.Now()
|
||||
resp, err = in.roundTripH3(req, ip)
|
||||
elapsed := time.Since(t0)
|
||||
// QUIC finishes the UDP association and the TLS handshake together.
|
||||
connectDur = elapsed
|
||||
tlsDur = elapsed
|
||||
default:
|
||||
resp, err = in.roundTripTCP(req, ip, version)
|
||||
}
|
||||
hop.connect = connectDur
|
||||
hop.tls = tlsDur
|
||||
if err != nil {
|
||||
hop.status, hop.note = classifyHTTPDial(err, version)
|
||||
return nil, hop, err
|
||||
}
|
||||
got := canonicalProto(resp.Proto)
|
||||
if version == "1.1" && got != "1.1" {
|
||||
_ = resp.Body.Close()
|
||||
hop.note = "服务器没有使用 HTTP/1.1,已按设置失败,没有降级"
|
||||
return nil, hop, errors.New(hop.note)
|
||||
}
|
||||
if version == "2" && got != "2" {
|
||||
_ = resp.Body.Close()
|
||||
hop.note = "服务器不支持 HTTP/2,已按设置失败,没有降级"
|
||||
return nil, hop, errors.New(hop.note)
|
||||
}
|
||||
if version == "3" && got != "3" {
|
||||
_ = resp.Body.Close()
|
||||
hop.note = "服务器不支持 HTTP/3,已按设置失败,没有降级"
|
||||
return nil, hop, errors.New(hop.note)
|
||||
}
|
||||
hop.version = got
|
||||
hop.status = statusOK
|
||||
hop.note = ""
|
||||
return resp, hop, nil
|
||||
}
|
||||
|
||||
func (in HTTPInput) roundTripTCP(req *http.Request, ip net.IP, version string) (*http.Response, error) {
|
||||
port := req.URL.Port()
|
||||
if port == "" {
|
||||
if req.URL.Scheme == "https" {
|
||||
port = "443"
|
||||
} else {
|
||||
port = "80"
|
||||
}
|
||||
}
|
||||
dialAddr := net.JoinHostPort(ip.String(), port)
|
||||
tlsConf := &tls.Config{
|
||||
ServerName: req.URL.Hostname(),
|
||||
InsecureSkipVerify: in.Insecure,
|
||||
RootCAs: in.Roots,
|
||||
MinVersion: tls.VersionTLS12,
|
||||
}
|
||||
switch version {
|
||||
case "1.1":
|
||||
tlsConf.NextProtos = []string{"http/1.1"}
|
||||
case "2":
|
||||
tlsConf.NextProtos = []string{"h2"}
|
||||
default:
|
||||
tlsConf.NextProtos = []string{"h2", "http/1.1"}
|
||||
}
|
||||
transport := &http.Transport{
|
||||
Proxy: nil,
|
||||
ForceAttemptHTTP2: version != "1.1",
|
||||
TLSClientConfig: tlsConf,
|
||||
DisableKeepAlives: true,
|
||||
DialContext: func(ctx context.Context, network, _ string) (net.Conn, error) {
|
||||
d := net.Dialer{}
|
||||
use := "tcp4"
|
||||
if ip.To4() == nil {
|
||||
use = "tcp6"
|
||||
}
|
||||
return d.DialContext(ctx, use, dialAddr)
|
||||
},
|
||||
}
|
||||
if version == "1.1" {
|
||||
transport.ForceAttemptHTTP2 = false
|
||||
transport.TLSNextProto = map[string]func(string, *tls.Conn) http.RoundTripper{}
|
||||
}
|
||||
defer transport.CloseIdleConnections()
|
||||
client := &http.Client{
|
||||
Transport: transport,
|
||||
CheckRedirect: func(*http.Request, []*http.Request) error {
|
||||
return http.ErrUseLastResponse
|
||||
},
|
||||
}
|
||||
return client.Do(req)
|
||||
}
|
||||
|
||||
func (in HTTPInput) roundTripH3(req *http.Request, ip net.IP) (*http.Response, error) {
|
||||
port := req.URL.Port()
|
||||
if port == "" {
|
||||
port = "443"
|
||||
}
|
||||
addr := net.JoinHostPort(ip.String(), port)
|
||||
tlsConf := &tls.Config{
|
||||
ServerName: req.URL.Hostname(),
|
||||
InsecureSkipVerify: in.Insecure,
|
||||
RootCAs: in.Roots,
|
||||
NextProtos: []string{http3.NextProtoH3},
|
||||
MinVersion: tls.VersionTLS12,
|
||||
}
|
||||
rt := &http3.Transport{
|
||||
TLSClientConfig: tlsConf,
|
||||
Dial: func(ctx context.Context, _ string, tlsCfg *tls.Config, cfg *quic.Config) (quic.EarlyConnection, error) {
|
||||
if cfg == nil {
|
||||
cfg = &quic.Config{}
|
||||
} else {
|
||||
cfg = cfg.Clone()
|
||||
}
|
||||
if cfg.HandshakeIdleTimeout == 0 || cfg.HandshakeIdleTimeout > time.Second {
|
||||
cfg.HandshakeIdleTimeout = time.Second
|
||||
}
|
||||
return quic.DialAddrEarly(ctx, addr, tlsCfg, cfg)
|
||||
},
|
||||
}
|
||||
defer rt.Close()
|
||||
client := &http.Client{
|
||||
Transport: rt,
|
||||
CheckRedirect: func(*http.Request, []*http.Request) error {
|
||||
return http.ErrUseLastResponse
|
||||
},
|
||||
}
|
||||
return client.Do(req)
|
||||
}
|
||||
|
||||
func (in HTTPInput) lookup(ctx context.Context, host string) ([]net.IP, time.Duration, error) {
|
||||
host = strings.TrimSpace(host)
|
||||
host = strings.Trim(host, "[]")
|
||||
if host == "" {
|
||||
return nil, 0, errors.New("empty host")
|
||||
}
|
||||
if !in.Allow4 && !in.Allow6 {
|
||||
return nil, 0, familyMessage("IPv4 和 IPv6 都已关闭,无法开始探测")
|
||||
}
|
||||
if ip := net.ParseIP(host); ip != nil {
|
||||
filtered, err := filterFamily(host, []net.IP{ip}, in.Allow4, in.Allow6)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
if in.CheckSafety && !ipAllowed(ip, in.AllowPrivate, in.Extra) {
|
||||
return nil, 0, fmt.Errorf("%w: %s", errForbiddenTarget, ip.String())
|
||||
}
|
||||
return filtered, 0, nil
|
||||
}
|
||||
start := time.Now()
|
||||
var ips []net.IP
|
||||
var err error
|
||||
if in.CheckSafety {
|
||||
ips, err = resolveTargets(ctx, in.Resolver, host, in.AllowPrivate, in.Extra)
|
||||
} else {
|
||||
ips, err = lookupPlain(ctx, in.Resolver, host)
|
||||
}
|
||||
elapsed := time.Since(start)
|
||||
if err != nil {
|
||||
return nil, elapsed, err
|
||||
}
|
||||
filtered, err := filterFamily(host, ips, in.Allow4, in.Allow6)
|
||||
if err != nil {
|
||||
return nil, elapsed, err
|
||||
}
|
||||
return filtered, elapsed, nil
|
||||
}
|
||||
|
||||
func lookupPlain(ctx context.Context, r resolver, host string) ([]net.IP, error) {
|
||||
if r == nil {
|
||||
r = net.DefaultResolver
|
||||
}
|
||||
lookupCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
defer cancel()
|
||||
addrs, err := r.LookupIPAddr(lookupCtx, host)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(addrs) == 0 {
|
||||
return nil, &net.DNSError{Err: "no addresses", Name: host, IsNotFound: true}
|
||||
}
|
||||
out := make([]net.IP, 0, len(addrs))
|
||||
for _, addr := range addrs {
|
||||
out = append(out, addr.IP)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func buildHTTPURL(target string, port int) (*url.URL, error) {
|
||||
target = strings.TrimSpace(target)
|
||||
if target == "" {
|
||||
return nil, errors.New("请填写目标地址")
|
||||
}
|
||||
raw := target
|
||||
if !strings.Contains(raw, "://") {
|
||||
scheme := "https"
|
||||
if port == 80 {
|
||||
scheme = "http"
|
||||
}
|
||||
hostpart := raw
|
||||
path := ""
|
||||
if i := strings.Index(raw, "/"); i >= 0 {
|
||||
hostpart, path = raw[:i], raw[i:]
|
||||
}
|
||||
if strings.Count(hostpart, ":") >= 2 && !strings.HasPrefix(hostpart, "[") {
|
||||
hostpart = "[" + hostpart + "]"
|
||||
}
|
||||
raw = scheme + "://" + hostpart + path
|
||||
}
|
||||
u, err := url.Parse(raw)
|
||||
if err != nil || u.Hostname() == "" || (u.Scheme != "http" && u.Scheme != "https") {
|
||||
return nil, errors.New("HTTP 目标需要是主机名或 http/https 网址")
|
||||
}
|
||||
if u.Port() == "" {
|
||||
if port < 1 || port > 65535 {
|
||||
return nil, errors.New("端口需要在 1 到 65535 之间")
|
||||
}
|
||||
u.Host = net.JoinHostPort(u.Hostname(), strconv.Itoa(port))
|
||||
}
|
||||
if u.Path == "" {
|
||||
u.Path = "/"
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
func normalizeHTTPVersion(v string) (string, error) {
|
||||
switch strings.ToLower(strings.TrimSpace(v)) {
|
||||
case "", "auto":
|
||||
return "auto", nil
|
||||
case "1.1", "http/1.1":
|
||||
return "1.1", nil
|
||||
case "2", "http/2":
|
||||
return "2", nil
|
||||
case "3", "http/3":
|
||||
return "3", nil
|
||||
default:
|
||||
return "", errors.New("HTTP 版本需要是自动、1.1、2 或 3")
|
||||
}
|
||||
}
|
||||
|
||||
func canonicalProto(proto string) string {
|
||||
p := strings.ToUpper(strings.TrimSpace(proto))
|
||||
switch {
|
||||
case strings.Contains(p, "3"):
|
||||
return "3"
|
||||
case strings.Contains(p, "2"):
|
||||
return "2"
|
||||
case strings.Contains(p, "1.1"):
|
||||
return "1.1"
|
||||
case strings.Contains(p, "1.0"):
|
||||
return "1.0"
|
||||
default:
|
||||
return p
|
||||
}
|
||||
}
|
||||
|
||||
func classifyHTTPLookup(err error, version string) (string, string) {
|
||||
if fe, ok := asFamily(err); ok {
|
||||
return statusError, fe.Error()
|
||||
}
|
||||
if errors.Is(err, errForbiddenTarget) {
|
||||
return statusError, "远程节点默认不探测本机、内网、链路本地或云元数据地址。管理员开放局域网后才能测这些地址"
|
||||
}
|
||||
var dnsErr *net.DNSError
|
||||
if errors.As(err, &dnsErr) {
|
||||
return statusDNS, "域名无法解析"
|
||||
}
|
||||
return classifyHTTPDial(err, version)
|
||||
}
|
||||
|
||||
func classifyHTTPDial(err error, version string) (string, string) {
|
||||
if err == nil {
|
||||
return statusError, "连接失败"
|
||||
}
|
||||
if fe, ok := asFamily(err); ok {
|
||||
return statusError, fe.Error()
|
||||
}
|
||||
if errors.Is(err, errForbiddenTarget) {
|
||||
return statusError, "远程节点默认不探测本机、内网、链路本地或云元数据地址。管理员开放局域网后才能测这些地址"
|
||||
}
|
||||
var dnsErr *net.DNSError
|
||||
if errors.As(err, &dnsErr) {
|
||||
return statusDNS, "域名无法解析"
|
||||
}
|
||||
msg := err.Error()
|
||||
if strings.Contains(msg, "没有使用 HTTP/1.1") || strings.Contains(msg, "不支持 HTTP/2") || strings.Contains(msg, "不支持 HTTP/3") {
|
||||
return statusError, msg
|
||||
}
|
||||
out := classifyDial(err)
|
||||
if out.Note == "" {
|
||||
out.Note = "连接失败"
|
||||
}
|
||||
if version == "2" || version == "3" {
|
||||
if out.Status == statusTimeout || out.Status == statusRefused || out.Status == statusDNS {
|
||||
return out.Status, out.Note
|
||||
}
|
||||
name := "HTTP/2"
|
||||
if version == "3" {
|
||||
name = "HTTP/3"
|
||||
}
|
||||
return statusError, "服务器不支持 " + name + ",已按设置失败,没有降级"
|
||||
}
|
||||
return out.Status, out.Note
|
||||
}
|
||||
|
||||
func retryHTTP(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) {
|
||||
return false
|
||||
}
|
||||
if _, ok := asFamily(err); ok {
|
||||
return false
|
||||
}
|
||||
if errors.Is(err, errForbiddenTarget) {
|
||||
return false
|
||||
}
|
||||
var dnsErr *net.DNSError
|
||||
return !errors.As(err, &dnsErr)
|
||||
}
|
||||
|
||||
func httpFail(status, note string) Outcome {
|
||||
return Outcome{Status: status, Kind: kindQuery, Note: note}
|
||||
}
|
||||
|
||||
func httpDone(started time.Time, dns, conn, tls, ttfb time.Duration, ip net.IP, version string, code int, final string, chain []string, status, note string) Outcome {
|
||||
detail := map[string]string{}
|
||||
putMs(detail, "dnsMs", dns)
|
||||
putMs(detail, "connectMs", conn)
|
||||
putMs(detail, "tlsMs", tls)
|
||||
putMs(detail, "ttfbMs", ttfb)
|
||||
putMs(detail, "totalMs", time.Since(started))
|
||||
if version != "" {
|
||||
detail["httpVersion"] = version
|
||||
}
|
||||
if code > 0 {
|
||||
detail["statusCode"] = strconv.Itoa(code)
|
||||
}
|
||||
if final != "" {
|
||||
detail["finalUrl"] = final
|
||||
}
|
||||
if len(chain) > 0 {
|
||||
detail["redirects"] = strings.Join(chain, " -> ")
|
||||
}
|
||||
out := Outcome{Status: status, Kind: kindQuery, Note: note, Detail: detail}
|
||||
if ip != nil {
|
||||
out = stampIP(out, ip)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
type httpProbe struct {
|
||||
spec jobSpec
|
||||
}
|
||||
|
||||
func (p *httpProbe) Close() error { return nil }
|
||||
|
||||
func (p *httpProbe) Probe(ctx context.Context) Outcome {
|
||||
in := p.spec.HTTP
|
||||
in.Preferred = p.spec.dialIP()
|
||||
out := probeHTTP(ctx, in)
|
||||
if p.spec.state != nil {
|
||||
p.spec.state.used = nil
|
||||
if out.Status == statusOK {
|
||||
if ip := net.ParseIP(out.Detail["address"]); ip != nil {
|
||||
p.spec.state.used = append(net.IP(nil), ip...)
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func putMs(detail map[string]string, key string, d time.Duration) {
|
||||
if d < 0 {
|
||||
d = 0
|
||||
}
|
||||
detail[key] = strconv.FormatFloat(float64(d)/float64(time.Millisecond), 'f', 3, 64)
|
||||
}
|
||||
@@ -0,0 +1,445 @@
|
||||
// Copyright (C) 2026 言灸
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/ecdsa"
|
||||
"crypto/elliptic"
|
||||
"crypto/rand"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"crypto/x509/pkix"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"math/big"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/quic-go/quic-go/http3"
|
||||
)
|
||||
|
||||
func TestFilterFamily(t *testing.T) {
|
||||
v4 := net.ParseIP("1.1.1.1")
|
||||
v6 := net.ParseIP("2001:db8::1")
|
||||
both := []net.IP{v4, v6}
|
||||
only4, err := filterFamily("example.com", both, true, false)
|
||||
if err != nil || len(only4) != 1 || !only4[0].Equal(v4) {
|
||||
t.Fatalf("v4 only: %v %v", only4, err)
|
||||
}
|
||||
only6, err := filterFamily("example.com", both, false, true)
|
||||
if err != nil || len(only6) != 1 || !only6[0].Equal(v6) {
|
||||
t.Fatalf("v6 only: %v %v", only6, err)
|
||||
}
|
||||
if _, err := filterFamily("example.com", both, false, false); err == nil || !strings.Contains(err.Error(), "都已关闭") {
|
||||
t.Fatalf("both off: %v", err)
|
||||
}
|
||||
if _, err := filterFamily("1.1.1.1", []net.IP{v4}, false, true); err == nil || !strings.Contains(err.Error(), "IPv4") {
|
||||
t.Fatalf("literal v4: %v", err)
|
||||
}
|
||||
if _, err := filterFamily("2001:db8::1", []net.IP{v6}, true, false); err == nil || !strings.Contains(err.Error(), "IPv6") {
|
||||
t.Fatalf("literal v6: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHTTPRedirectStatusIsNotLoss(t *testing.T) {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/a", func(w http.ResponseWriter, r *http.Request) {
|
||||
http.Redirect(w, r, "/b", http.StatusFound)
|
||||
})
|
||||
mux.HandleFunc("/b", func(w http.ResponseWriter, r *http.Request) {
|
||||
http.Redirect(w, r, "/c", http.StatusMovedPermanently)
|
||||
})
|
||||
mux.HandleFunc("/c", func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
t.Errorf("method %s", r.Method)
|
||||
}
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
_, _ = w.Write([]byte("missing"))
|
||||
})
|
||||
srv := httptest.NewServer(mux)
|
||||
defer srv.Close()
|
||||
port := mustPort(t, srv.URL)
|
||||
out := probeHTTP(context.Background(), HTTPInput{
|
||||
Target: srv.URL + "/a", Port: port, Version: "1.1", Method: "POST", Body: "ignored-after-redirect",
|
||||
Allow4: true, Allow6: true, Timeout: 3 * time.Second, MaxSet: true, MaxRedirects: 5,
|
||||
})
|
||||
if out.Status != statusOK {
|
||||
t.Fatalf("status %s note %s", out.Status, out.Note)
|
||||
}
|
||||
if strings.Contains(out.Note, "丢包") && !strings.Contains(out.Note, "不是丢包") {
|
||||
t.Fatalf("note treats 404 as loss: %s", out.Note)
|
||||
}
|
||||
if !strings.Contains(out.Note, "不是丢包") || out.Detail["statusCode"] != "404" {
|
||||
t.Fatalf("note/detail %+v %s", out.Detail, out.Note)
|
||||
}
|
||||
if !strings.Contains(out.Detail["finalUrl"], "/c") || !strings.Contains(out.Detail["redirects"], "/a") || !strings.Contains(out.Detail["redirects"], "/b") {
|
||||
t.Fatalf("chain %+v", out.Detail)
|
||||
}
|
||||
if out.Detail["httpVersion"] != "1.1" || !out.HasRtt {
|
||||
t.Fatalf("version/rtt %+v", out)
|
||||
}
|
||||
for _, key := range []string{"dnsMs", "connectMs", "tlsMs", "ttfbMs", "totalMs"} {
|
||||
if _, err := strconv.ParseFloat(out.Detail[key], 64); err != nil {
|
||||
t.Fatalf("%s: %v", key, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestHTTPPostHeadersAndResolve(t *testing.T) {
|
||||
var gotHost, gotBody, gotRef, gotUA, gotCookie string
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
gotHost = r.Host
|
||||
raw, _ := io.ReadAll(r.Body)
|
||||
gotBody = string(raw)
|
||||
gotRef = r.Referer()
|
||||
gotUA = r.UserAgent()
|
||||
gotCookie = r.Header.Get("Cookie")
|
||||
if r.URL.Path != "/only" {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
}))
|
||||
defer srv.Close()
|
||||
port := mustPort(t, srv.URL)
|
||||
out := probeHTTP(context.Background(), HTTPInput{
|
||||
Target: "http://example.com/only", Port: port, Version: "1.1", Method: "POST", Body: "hello",
|
||||
Referer: "https://from.example/a", UserAgent: "nq-test", Cookies: "a=b",
|
||||
Resolve: "cdn.test", Resolver: stubResolver{[]net.IP{net.ParseIP("127.0.0.1")}},
|
||||
Allow4: true, Allow6: true, Timeout: 3 * time.Second,
|
||||
})
|
||||
if out.Status != statusOK || out.Detail["statusCode"] != "201" {
|
||||
t.Fatalf("%s %s %+v", out.Status, out.Note, out.Detail)
|
||||
}
|
||||
if gotHost != "example.com:"+strconv.Itoa(port) {
|
||||
t.Fatalf("host %q", gotHost)
|
||||
}
|
||||
if gotBody != "hello" || gotRef != "https://from.example/a" || gotUA != "nq-test" || gotCookie != "a=b" {
|
||||
t.Fatalf("body %q ref %q ua %q cookie %q", gotBody, gotRef, gotUA, gotCookie)
|
||||
}
|
||||
if out.Detail["address"] != "127.0.0.1" || out.Detail["family"] != "IPv4" {
|
||||
t.Fatalf("address %+v", out.Detail)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHTTPForceVersionAndSNI(t *testing.T) {
|
||||
cert, pool := testCert(t)
|
||||
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.TLS == nil || r.TLS.ServerName != "example.com" {
|
||||
http.Error(w, "bad sni", http.StatusBadGateway)
|
||||
return
|
||||
}
|
||||
if !strings.HasPrefix(r.Host, "example.com") {
|
||||
http.Error(w, "bad host", http.StatusBadGateway)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
})
|
||||
h2addr, h2close := serveTLS(t, handler, []string{"h2", "http/1.1"}, true, cert)
|
||||
defer h2close()
|
||||
h1addr, h1close := serveTLS(t, handler, []string{"http/1.1"}, false, cert)
|
||||
defer h1close()
|
||||
h2port := mustPort(t, "https://"+h2addr)
|
||||
h1port := mustPort(t, "https://"+h1addr)
|
||||
|
||||
auto := probeHTTP(context.Background(), tlsInput("https://example.com/path", h2port, "auto", pool))
|
||||
if auto.Status != statusOK || auto.Detail["httpVersion"] != "2" || auto.Detail["statusCode"] != "204" {
|
||||
t.Fatalf("auto h2: %s %s %+v", auto.Status, auto.Note, auto.Detail)
|
||||
}
|
||||
forced1 := probeHTTP(context.Background(), tlsInput("https://example.com/path", h2port, "1.1", pool))
|
||||
if forced1.Status != statusOK || forced1.Detail["httpVersion"] != "1.1" {
|
||||
t.Fatalf("force 1.1: %s %s %+v", forced1.Status, forced1.Note, forced1.Detail)
|
||||
}
|
||||
forced2 := probeHTTP(context.Background(), tlsInput("https://example.com/path", h1port, "2", pool))
|
||||
if forced2.Status == statusOK || !strings.Contains(forced2.Note, "HTTP/2") || strings.Contains(forced2.Note, "降级到") {
|
||||
t.Fatalf("force 2 should fail closed: %s %s", forced2.Status, forced2.Note)
|
||||
}
|
||||
plain := probeHTTP(context.Background(), HTTPInput{
|
||||
Target: "http://127.0.0.1/x", Port: 9, Version: "3", Allow4: true, Allow6: true, Timeout: time.Second,
|
||||
})
|
||||
if plain.Status == statusOK || !strings.Contains(plain.Note, "需要 HTTPS") {
|
||||
t.Fatalf("cleartext h3: %s %s", plain.Status, plain.Note)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHTTP3(t *testing.T) {
|
||||
cert, pool := testCert(t)
|
||||
udp, err := net.ListenUDP("udp", &net.UDPAddr{IP: net.ParseIP("127.0.0.1")})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer udp.Close()
|
||||
h3 := &http3.Server{
|
||||
TLSConfig: &tls.Config{Certificates: []tls.Certificate{cert}},
|
||||
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.TLS == nil || r.TLS.ServerName != "example.com" {
|
||||
http.Error(w, "bad sni", http.StatusBadGateway)
|
||||
return
|
||||
}
|
||||
if !strings.HasPrefix(r.Host, "example.com") {
|
||||
http.Error(w, "bad host "+r.Host, http.StatusBadGateway)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = io.WriteString(w, "h3")
|
||||
}),
|
||||
}
|
||||
go h3.Serve(udp)
|
||||
defer h3.Close()
|
||||
port := udp.LocalAddr().(*net.UDPAddr).Port
|
||||
out := probeHTTP(context.Background(), tlsInput("https://example.com/h3", port, "3", pool))
|
||||
if out.Status != statusOK || out.Detail["httpVersion"] != "3" || out.Detail["statusCode"] != "200" {
|
||||
t.Fatalf("h3: %s %s %+v", out.Status, out.Note, out.Detail)
|
||||
}
|
||||
if out.Detail["address"] != "127.0.0.1" {
|
||||
t.Fatalf("address %+v", out.Detail)
|
||||
}
|
||||
tcpAddr, closeTCP := serveTLS(t, http.NotFoundHandler(), []string{"h2", "http/1.1"}, true, cert)
|
||||
defer closeTCP()
|
||||
failed := probeHTTP(context.Background(), tlsInput("https://example.com/nope", mustPort(t, "https://"+tcpAddr), "3", pool))
|
||||
if failed.Status == statusOK || strings.Contains(failed.Note, "降到") {
|
||||
t.Fatalf("h3 against tcp: %s %s", failed.Status, failed.Note)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHTTPFamilyRefusal(t *testing.T) {
|
||||
out := probeHTTP(context.Background(), HTTPInput{
|
||||
Target: "127.0.0.1", Port: 80, Allow4: false, Allow6: true, Timeout: time.Second,
|
||||
})
|
||||
if out.Status == statusOK || !strings.Contains(out.Note, "IPv4") {
|
||||
t.Fatalf("%s %s", out.Status, out.Note)
|
||||
}
|
||||
both := probeHTTP(context.Background(), HTTPInput{
|
||||
Target: "example.com", Port: 443, Allow4: false, Allow6: false, Timeout: time.Second,
|
||||
})
|
||||
if !strings.Contains(both.Note, "都已关闭") {
|
||||
t.Fatal(both.Note)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNodeHonorsFamilyAndHTTP(t *testing.T) {
|
||||
page := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusBadGateway)
|
||||
}))
|
||||
defer page.Close()
|
||||
port := mustPort(t, page.URL)
|
||||
node := newNode("", true, nil, testLimits())
|
||||
node.Resolver = stubResolver{[]net.IP{net.ParseIP("127.0.0.1"), net.ParseIP("::1")}}
|
||||
ts := httptest.NewServer(node.Handler())
|
||||
defer ts.Close()
|
||||
|
||||
bad := postJSON(t, ts.URL+"/v1/jobs", `{"target":"127.0.0.1","port":1,"profile":"tcp-connect","intervalMs":200,"timeoutMs":300,"durationSec":1,"allowIPv4":false,"allowIPv6":true}`)
|
||||
if bad.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("literal v4 status %d", bad.StatusCode)
|
||||
}
|
||||
badBody, _ := io.ReadAll(bad.Body)
|
||||
bad.Body.Close()
|
||||
if !strings.Contains(string(badBody), "IPv4") {
|
||||
t.Fatalf("body %s", badBody)
|
||||
}
|
||||
both := postJSON(t, ts.URL+"/v1/jobs", `{"target":"127.0.0.1","port":1,"profile":"tcp-connect","intervalMs":200,"timeoutMs":300,"durationSec":1,"allowIPv4":false,"allowIPv6":false}`)
|
||||
both.Body.Close()
|
||||
if both.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("both off %d", both.StatusCode)
|
||||
}
|
||||
|
||||
created := postJSON(t, ts.URL+"/v1/jobs", `{"target":"example.test","port":1,"profile":"tcp-connect","intervalMs":200,"timeoutMs":300,"durationSec":1,"allowIPv4":false,"allowIPv6":true}`)
|
||||
defer created.Body.Close()
|
||||
if created.StatusCode != http.StatusCreated {
|
||||
raw, _ := io.ReadAll(created.Body)
|
||||
t.Fatalf("family filter create %d %s", created.StatusCode, raw)
|
||||
}
|
||||
var createdBody map[string]any
|
||||
if err := json.NewDecoder(created.Body).Decode(&createdBody); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resolved, _ := createdBody["resolved"].([]any)
|
||||
if len(resolved) != 1 {
|
||||
t.Fatalf("resolved %+v", createdBody["resolved"])
|
||||
}
|
||||
first, _ := resolved[0].(map[string]any)
|
||||
if first["address"] != "::1" || first["family"] != "IPv6" {
|
||||
t.Fatalf("resolved %+v", first)
|
||||
}
|
||||
|
||||
httpJob := postJSON(t, ts.URL+"/v1/jobs", `{"target":"`+page.URL+`/","port":`+strconv.Itoa(port)+`,"profile":"http","intervalMs":200,"timeoutMs":1500,"durationSec":2,"http":{"version":"1.1","method":"GET","maxRedirects":5}}`)
|
||||
defer httpJob.Body.Close()
|
||||
if httpJob.StatusCode != http.StatusCreated {
|
||||
raw, _ := io.ReadAll(httpJob.Body)
|
||||
t.Fatalf("http create %d %s", httpJob.StatusCode, raw)
|
||||
}
|
||||
var job map[string]any
|
||||
if err := json.NewDecoder(httpJob.Body).Decode(&job); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
id, _ := job["jobId"].(string)
|
||||
sample := readSampleURL(t, ts.URL+"/v1/jobs/"+id+"/stream")
|
||||
if sample["status"] != statusOK {
|
||||
t.Fatalf("sample %+v", sample)
|
||||
}
|
||||
detail, _ := sample["detail"].(map[string]any)
|
||||
if detail["statusCode"] != "502" {
|
||||
t.Fatalf("detail %+v", detail)
|
||||
}
|
||||
note, _ := sample["note"].(string)
|
||||
if !strings.Contains(note, "不是丢包") {
|
||||
t.Fatalf("note %s", note)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHelperSpeaksHTTPEngine(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}))
|
||||
defer srv.Close()
|
||||
port := mustPort(t, srv.URL)
|
||||
var in bytes.Buffer
|
||||
req, _ := json.Marshal(map[string]any{
|
||||
"profile": "http", "target": srv.URL + "/", "port": port, "timeoutMs": 2000,
|
||||
"allowIPv4": true, "allowIPv6": false,
|
||||
"http": map[string]any{"version": "1.1", "method": "GET"},
|
||||
})
|
||||
in.Write(req)
|
||||
in.WriteByte('\n')
|
||||
var out bytes.Buffer
|
||||
if err := runHelper(&in, &out); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sc := bufio.NewScanner(&out)
|
||||
if !sc.Scan() {
|
||||
t.Fatal("no output")
|
||||
}
|
||||
var body map[string]any
|
||||
if err := json.Unmarshal(sc.Bytes(), &body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if body["status"] != statusOK {
|
||||
t.Fatalf("%+v", body)
|
||||
}
|
||||
detail, _ := body["detail"].(map[string]any)
|
||||
if detail["httpVersion"] != "1.1" || detail["statusCode"] != "204" {
|
||||
t.Fatalf("%+v", detail)
|
||||
}
|
||||
}
|
||||
|
||||
func tlsInput(target string, port int, version string, pool *x509.CertPool) HTTPInput {
|
||||
return HTTPInput{
|
||||
Target: target, Port: port, Version: version, Resolve: "127.0.0.1",
|
||||
Allow4: true, Allow6: true, Timeout: 4 * time.Second, Roots: pool,
|
||||
}
|
||||
}
|
||||
|
||||
func testCert(t *testing.T) (tls.Certificate, *x509.CertPool) {
|
||||
t.Helper()
|
||||
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tmpl := &x509.Certificate{
|
||||
SerialNumber: big.NewInt(1),
|
||||
Subject: pkix.Name{CommonName: "example.com"},
|
||||
NotBefore: time.Now().Add(-time.Hour),
|
||||
NotAfter: time.Now().Add(time.Hour),
|
||||
DNSNames: []string{"example.com"},
|
||||
IPAddresses: []net.IP{net.ParseIP("127.0.0.1")},
|
||||
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
|
||||
KeyUsage: x509.KeyUsageDigitalSignature,
|
||||
}
|
||||
der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
leaf, err := x509.ParseCertificate(der)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pool := x509.NewCertPool()
|
||||
pool.AddCert(leaf)
|
||||
return tls.Certificate{Certificate: [][]byte{der}, PrivateKey: key}, pool
|
||||
}
|
||||
|
||||
func serveTLS(t *testing.T, handler http.Handler, protos []string, h2 bool, cert tls.Certificate) (string, func()) {
|
||||
t.Helper()
|
||||
ln, err := tls.Listen("tcp", "127.0.0.1:0", &tls.Config{
|
||||
Certificates: []tls.Certificate{cert},
|
||||
NextProtos: protos,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
srv := &http.Server{Handler: handler, ReadHeaderTimeout: 5 * time.Second}
|
||||
if !h2 {
|
||||
srv.TLSNextProto = map[string]func(*http.Server, *tls.Conn, http.Handler){}
|
||||
}
|
||||
go srv.Serve(ln)
|
||||
return ln.Addr().String(), func() { _ = srv.Close() }
|
||||
}
|
||||
|
||||
func mustPort(t *testing.T, raw string) int {
|
||||
t.Helper()
|
||||
if !strings.Contains(raw, "://") {
|
||||
raw = "https://" + raw
|
||||
}
|
||||
u, err := url.Parse(raw)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
port, err := strconv.Atoi(u.Port())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return port
|
||||
}
|
||||
|
||||
func postJSON(t *testing.T, url, body string) *http.Response {
|
||||
t.Helper()
|
||||
res, err := http.Post(url, "application/json", strings.NewReader(body))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
func readSampleURL(t *testing.T, rawURL string) map[string]any {
|
||||
t.Helper()
|
||||
req, err := http.NewRequest(http.MethodGet, rawURL, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
client := &http.Client{Timeout: 5 * time.Second}
|
||||
res, err := client.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer res.Body.Close()
|
||||
sc := bufio.NewScanner(res.Body)
|
||||
var data string
|
||||
for sc.Scan() {
|
||||
line := sc.Text()
|
||||
if strings.HasPrefix(line, "data: ") {
|
||||
data = strings.TrimPrefix(line, "data: ")
|
||||
}
|
||||
if line == "" && data != "" && data != "{}" {
|
||||
var msg map[string]any
|
||||
if err := json.Unmarshal([]byte(data), &msg); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if msg["status"] != "" && msg["status"] != "pending" {
|
||||
return msg
|
||||
}
|
||||
data = ""
|
||||
}
|
||||
}
|
||||
t.Fatal("no sample")
|
||||
return nil
|
||||
}
|
||||
+86
-6
@@ -1,12 +1,14 @@
|
||||
// Copyright (C) 2026 灸 言
|
||||
// Copyright (C) 2026 言灸
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
@@ -19,6 +21,12 @@ import (
|
||||
)
|
||||
|
||||
func main() {
|
||||
if hashRequested(os.Args[1:]) {
|
||||
if err := printHash(os.Stdin); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
return
|
||||
}
|
||||
cfg, err := loadConfig(os.Args[1:], os.Environ())
|
||||
if err != nil {
|
||||
if errors.Is(err, errHelp) {
|
||||
@@ -26,6 +34,19 @@ func main() {
|
||||
}
|
||||
log.Fatal(err)
|
||||
}
|
||||
if cfg.CenterKey == "" && cfg.CenterDir != "" {
|
||||
key, err := loadCenterKeyFile(cfg.CenterDir)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
cfg.CenterKey = key
|
||||
}
|
||||
if cfg.Mode == "helper" {
|
||||
if err := runHelper(os.Stdin, os.Stdout); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
return
|
||||
}
|
||||
log.Printf("netquality %s", appVersion)
|
||||
log.Printf("%s", cfg.Summary())
|
||||
|
||||
@@ -51,11 +72,27 @@ func main() {
|
||||
}
|
||||
|
||||
var httpSrv *http.Server
|
||||
var node *Node
|
||||
if cfg.Mode == "node" || cfg.Mode == "both" {
|
||||
node := newNode(cfg.NodeToken, cfg.AllowPrivate, extra, defaultLimits())
|
||||
node = newNode(cfg.NodeToken, cfg.AllowPrivate, extra, defaultLimits())
|
||||
node.CenterKey = []byte(cfg.CenterKey)
|
||||
node.ServerID = strings.TrimSpace(cfg.ServerID)
|
||||
if cfg.CenterKey != "" && node.ServerID == "" {
|
||||
log.Printf("设置了中心密钥但没有 NQ_SERVER_ID,将不接受中心签发的短期凭证")
|
||||
}
|
||||
}
|
||||
var center *Center
|
||||
if strings.TrimSpace(cfg.CenterDir) != "" && cfg.Mode != "reflector" {
|
||||
center = newCenter(cfg.CenterDir, cfg.CenterKey)
|
||||
if _, err := center.load(); err != nil {
|
||||
log.Fatalf("中心配置无法读取: %v", err)
|
||||
}
|
||||
log.Printf("center directory %s", cfg.CenterDir)
|
||||
}
|
||||
if node != nil || center != nil {
|
||||
httpSrv = &http.Server{
|
||||
Addr: cfg.ControlAddr,
|
||||
Handler: node.Handler(),
|
||||
Handler: controlHandler(node, center),
|
||||
ReadHeaderTimeout: 5 * time.Second,
|
||||
IdleTimeout: 2 * time.Minute,
|
||||
}
|
||||
@@ -76,14 +113,17 @@ func main() {
|
||||
errCh <- serveErr
|
||||
}
|
||||
}()
|
||||
if node.Public() && !loopbackHost(cfg.ControlAddr) {
|
||||
if node != nil && node.Public() && !loopbackHost(cfg.ControlAddr) {
|
||||
log.Printf("WARNING: this node is PUBLIC. Anyone who can reach %s can start bounded probes. Set NQ_NODE_TOKEN or -node-token to require a control token. Caps stay on: jobs=%d duration=%s interval>=%s probes/s=%d bandwidth=%dB/s",
|
||||
cfg.ControlAddr, node.Limits.MaxJobs, node.Limits.MaxDuration, node.Limits.MinInterval, node.Limits.MaxProbePerSec, node.Limits.MaxBytesPerSec)
|
||||
} else if node.Public() {
|
||||
} else if node != nil && node.Public() {
|
||||
log.Printf("node is public and bound to loopback; no control token is required")
|
||||
} else {
|
||||
} else if node != nil {
|
||||
log.Printf("node is private; a control token is required and is not logged")
|
||||
}
|
||||
if center != nil {
|
||||
log.Printf("center API is on the control port; use HTTPS before exposing it")
|
||||
}
|
||||
if cfg.AllowPrivate {
|
||||
log.Printf("private and loopback targets are allowed; metadata addresses stay blocked")
|
||||
}
|
||||
@@ -189,6 +229,46 @@ func parseNets(s string) ([]*net.IPNet, error) {
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func controlHandler(node *Node, center *Center) http.Handler {
|
||||
switch {
|
||||
case node != nil && center == nil:
|
||||
return node.Handler()
|
||||
case node == nil && center != nil:
|
||||
return center.Handler()
|
||||
default:
|
||||
mux := http.NewServeMux()
|
||||
mux.Handle("/v1/center/", center.Handler())
|
||||
mux.Handle("/v1/", node.Handler())
|
||||
return mux
|
||||
}
|
||||
}
|
||||
|
||||
func hashRequested(args []string) bool {
|
||||
for _, arg := range args {
|
||||
if arg == "-hash-secret" || arg == "--hash-secret" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func printHash(r io.Reader) error {
|
||||
sc := bufio.NewScanner(r)
|
||||
sc.Buffer(make([]byte, 64*1024), 1<<20)
|
||||
if !sc.Scan() {
|
||||
if err := sc.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
return errors.New("请从标准输入传入一行要计算哈希的内容")
|
||||
}
|
||||
line := strings.TrimRight(sc.Text(), "\r")
|
||||
if strings.TrimSpace(line) == "" {
|
||||
return errors.New("内容是空的")
|
||||
}
|
||||
fmt.Println(hashSecret(line))
|
||||
return nil
|
||||
}
|
||||
|
||||
func loopbackHost(addr string) bool {
|
||||
host, _, err := net.SplitHostPort(addr)
|
||||
if err != nil {
|
||||
|
||||
+1
-1
@@ -172,7 +172,7 @@ func (b *sampleBook) summary() summaryMsg {
|
||||
v := float64(b.timeout) * 100 / float64(b.timeout+b.ok)
|
||||
s.ProbeLossPct = &v
|
||||
}
|
||||
case "tcp-connect", "minecraft-java":
|
||||
case "tcp-connect", "minecraft-java", "http":
|
||||
denom := b.ok + b.timeout + b.refused + b.dns + b.protocol + b.other
|
||||
if denom > 0 {
|
||||
v := float64(denom-b.ok) * 100 / float64(denom)
|
||||
|
||||
+59
-12
@@ -30,6 +30,9 @@ type jobSpec struct {
|
||||
DNSName string
|
||||
Payload []byte
|
||||
Expect []byte
|
||||
Allow4 bool
|
||||
Allow6 bool
|
||||
HTTP HTTPInput
|
||||
}
|
||||
|
||||
type Limits struct {
|
||||
@@ -69,6 +72,8 @@ type Node struct {
|
||||
ExtraNets []*net.IPNet
|
||||
Limits Limits
|
||||
Resolver resolver
|
||||
CenterKey []byte
|
||||
ServerID string
|
||||
|
||||
mu sync.Mutex
|
||||
jobs map[string]*probeJob
|
||||
@@ -93,7 +98,7 @@ func newNode(token string, allowPrivate bool, extra []*net.IPNet, limits Limits)
|
||||
return n
|
||||
}
|
||||
|
||||
func (n *Node) Public() bool { return n.Token == "" }
|
||||
func (n *Node) Public() bool { return n.Token == "" && len(n.CenterKey) == 0 }
|
||||
|
||||
func (n *Node) Handler() http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
@@ -116,8 +121,9 @@ func (n *Node) info(w http.ResponseWriter, _ *http.Request) {
|
||||
"authRequired": !n.Public(),
|
||||
"profiles": []string{
|
||||
"nq-tcp", "nq-udp", "tcp-connect", "udp-generic", "dns",
|
||||
"minecraft-java", "minecraft-bedrock", "custom-udp",
|
||||
"minecraft-java", "minecraft-bedrock", "custom-udp", "http",
|
||||
},
|
||||
"ipFamily": true,
|
||||
"limits": map[string]int{
|
||||
"maxJobs": n.Limits.MaxJobs,
|
||||
"maxDurationSec": int(n.Limits.MaxDuration / time.Second),
|
||||
@@ -131,16 +137,20 @@ func (n *Node) info(w http.ResponseWriter, _ *http.Request) {
|
||||
|
||||
func (n *Node) auth(next http.HandlerFunc) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
if n.Token == "" {
|
||||
if n.Public() {
|
||||
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", "节点口令不正确或未提供")
|
||||
if n.Token != "" && got != "" && subtle.ConstantTimeCompare([]byte(got), []byte(n.Token)) == 1 {
|
||||
next(w, r)
|
||||
return
|
||||
}
|
||||
next(w, r)
|
||||
if verifyCredential(got, n.CenterKey, n.ServerID, time.Now()) {
|
||||
next(w, r)
|
||||
return
|
||||
}
|
||||
writeErr(w, http.StatusUnauthorized, "unauthorized", "节点口令不正确或未提供")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -152,10 +162,13 @@ type createReq struct {
|
||||
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"`
|
||||
EchoToken string `json:"echoToken"`
|
||||
DNSName string `json:"dnsName"`
|
||||
PayloadHex string `json:"payloadHex"`
|
||||
ExpectHex string `json:"expectHex"`
|
||||
AllowIPv4 *bool `json:"allowIPv4"`
|
||||
AllowIPv6 *bool `json:"allowIPv6"`
|
||||
HTTP *httpOptionsReq `json:"http"`
|
||||
}
|
||||
|
||||
func (n *Node) create(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -205,10 +218,12 @@ func (n *Node) create(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
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":
|
||||
case "nq-tcp", "nq-udp", "tcp-connect", "udp-generic", "dns", "minecraft-java", "minecraft-bedrock", "custom-udp", "http":
|
||||
default:
|
||||
return jobSpec{}, &apiError{http.StatusBadRequest, "bad_profile", "不支持的探测类型"}
|
||||
}
|
||||
allow4 := flagOrDefault(req.AllowIPv4, true)
|
||||
allow6 := flagOrDefault(req.AllowIPv6, true)
|
||||
if req.Port < 1 || req.Port > 65535 {
|
||||
return jobSpec{}, &apiError{http.StatusBadRequest, "bad_port", "端口需要在 1 到 65535 之间"}
|
||||
}
|
||||
@@ -257,7 +272,31 @@ func (n *Node) prepare(ctx context.Context, req createReq) (jobSpec, error) {
|
||||
}
|
||||
}
|
||||
}
|
||||
ips, err := resolveTargets(ctx, n.Resolver, req.Target, n.AllowPrivate, n.ExtraNets)
|
||||
httpIn := HTTPInput{
|
||||
Target: req.Target, Port: req.Port, Timeout: timeout,
|
||||
Allow4: allow4, Allow6: allow6, CheckSafety: true,
|
||||
AllowPrivate: n.AllowPrivate, Extra: n.ExtraNets, Resolver: n.Resolver,
|
||||
}
|
||||
applyHTTPOptions(&httpIn, req.HTTP)
|
||||
lookupHost := req.Target
|
||||
if req.Profile == "http" {
|
||||
page, err := buildHTTPURL(req.Target, req.Port)
|
||||
if err != nil {
|
||||
return jobSpec{}, &apiError{http.StatusBadRequest, "bad_target", err.Error()}
|
||||
}
|
||||
if _, err := normalizeHTTPVersion(httpIn.Version); err != nil {
|
||||
return jobSpec{}, &apiError{http.StatusBadRequest, "bad_profile", err.Error()}
|
||||
}
|
||||
method := strings.ToUpper(strings.TrimSpace(httpIn.Method))
|
||||
if method != "" && method != "GET" && method != "POST" {
|
||||
return jobSpec{}, &apiError{http.StatusBadRequest, "bad_request", "HTTP 方法只支持 GET 和 POST"}
|
||||
}
|
||||
lookupHost = page.Hostname()
|
||||
if strings.TrimSpace(httpIn.Resolve) != "" {
|
||||
lookupHost = strings.TrimSpace(httpIn.Resolve)
|
||||
}
|
||||
}
|
||||
ips, err := resolveTargets(ctx, n.Resolver, lookupHost, n.AllowPrivate, n.ExtraNets)
|
||||
if err != nil {
|
||||
var dnsErr *net.DNSError
|
||||
if errors.As(err, &dnsErr) {
|
||||
@@ -268,11 +307,19 @@ func (n *Node) prepare(ctx context.Context, req createReq) (jobSpec, error) {
|
||||
}
|
||||
return jobSpec{}, &apiError{http.StatusBadRequest, "bad_target", "目标地址无效"}
|
||||
}
|
||||
ips, err = filterFamily(lookupHost, ips, allow4, allow6)
|
||||
if err != nil {
|
||||
if fe, ok := asFamily(err); ok {
|
||||
return jobSpec{}, &apiError{http.StatusBadRequest, "bad_family", fe.Error()}
|
||||
}
|
||||
return jobSpec{}, &apiError{http.StatusBadRequest, "bad_family", "地址族不被允许"}
|
||||
}
|
||||
return jobSpec{
|
||||
Host: req.Target, Port: req.Port, Profile: req.Profile, IP: ips[0],
|
||||
state: &dialState{picker: newEndpointPicker(ips)},
|
||||
Interval: interval, Timeout: timeout, Duration: duration, PacketSize: size,
|
||||
Echo: echo, DNSName: req.DNSName, Payload: payload, Expect: expect,
|
||||
Allow4: allow4, Allow6: allow6, HTTP: httpIn,
|
||||
}, nil
|
||||
}
|
||||
|
||||
|
||||
+11
-1
@@ -79,9 +79,19 @@ func TestPublicAndPrivateAuth(t *testing.T) {
|
||||
if err := json.NewDecoder(info.Body).Decode(&body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if body["visibility"] != "public" || body["authRequired"] != false {
|
||||
if body["visibility"] != "public" || body["authRequired"] != false || body["ipFamily"] != true {
|
||||
t.Fatalf("info %+v", body)
|
||||
}
|
||||
profiles, _ := body["profiles"].([]any)
|
||||
seenHTTP := false
|
||||
for _, item := range profiles {
|
||||
if item == "http" {
|
||||
seenHTTP = true
|
||||
}
|
||||
}
|
||||
if !seenHTTP {
|
||||
t.Fatalf("info profiles %+v", body["profiles"])
|
||||
}
|
||||
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
|
||||
@@ -38,6 +38,8 @@ func newProber(spec jobSpec) (prober, error) {
|
||||
return &mcJava{spec: spec}, nil
|
||||
case "minecraft-bedrock":
|
||||
return &mcBedrock{spec: spec}, nil
|
||||
case "http":
|
||||
return &httpProbe{spec: spec}, nil
|
||||
default:
|
||||
return nil, fmt.Errorf("unknown profile %q", spec.Profile)
|
||||
}
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
const appVersion = "1.1.2"
|
||||
const appVersion = "1.1.3"
|
||||
|
||||
// dialState is shared by the job runner and the prober. Both hold a copy of
|
||||
// jobSpec, so the mutable address choice has to live behind a pointer.
|
||||
|
||||
Reference in new issue
Block a user