2026-10-31 02:19:51 -07:00
|
|
|
package runtime
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"bytes"
|
|
|
|
|
"encoding/json"
|
|
|
|
|
"fmt"
|
|
|
|
|
"unicode/utf8"
|
2026-10-31 06:25:21 -07:00
|
|
|
|
|
|
|
|
"github.com/mhsanaei/3x-ui/v3/internal/util/json_util"
|
2026-10-31 02:19:51 -07:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
// Per-endpoint caps on node-reported lists: each "{}" decodes into a whole struct, so the
|
|
|
|
|
// byte cap alone still lets a node's answer expand into gigabytes.
|
|
|
|
|
const (
|
|
|
|
|
maxNodeDescendants = 1024
|
|
|
|
|
maxNodeInbounds = 65536
|
|
|
|
|
maxNodeHostGroups = 65536
|
|
|
|
|
maxNodeClientIPs = 1 << 20
|
|
|
|
|
// maxNodeMapValues bounds every value of the GUID-keyed trees and maps a node reports.
|
|
|
|
|
maxNodeMapValues = 1 << 20
|
|
|
|
|
)
|
|
|
|
|
|
2026-10-31 06:25:21 -07:00
|
|
|
var errRemoteListTooLong = json_util.ErrListTooLong
|
2026-10-31 02:19:51 -07:00
|
|
|
|
|
|
|
|
// decodeCappedValues unmarshals raw into v after checking it holds at most maxValues
|
2026-11-01 04:14:46 -08:00
|
|
|
// JSON values in all, nested ones included; object keys and closing brackets are not values.
|
2026-10-31 02:19:51 -07:00
|
|
|
func decodeCappedValues(raw json.RawMessage, v any, maxValues int) error {
|
|
|
|
|
dec := json.NewDecoder(bytes.NewReader(raw))
|
2026-11-01 04:14:46 -08:00
|
|
|
// One frame per open container; an object's strings alternate between key and value.
|
|
|
|
|
type frame struct{ object, wantKey bool }
|
|
|
|
|
var open []frame
|
|
|
|
|
count := 0
|
|
|
|
|
for {
|
2026-10-31 02:19:51 -07:00
|
|
|
tok, err := dec.Token()
|
|
|
|
|
if err != nil {
|
|
|
|
|
break
|
|
|
|
|
}
|
2026-11-01 04:14:46 -08:00
|
|
|
delim, isDelim := tok.(json.Delim)
|
|
|
|
|
if isDelim && (delim == ']' || delim == '}') {
|
|
|
|
|
open = open[:len(open)-1]
|
2026-10-31 02:19:51 -07:00
|
|
|
continue
|
|
|
|
|
}
|
2026-11-01 04:14:46 -08:00
|
|
|
if top := len(open) - 1; top >= 0 && open[top].object {
|
|
|
|
|
if open[top].wantKey {
|
|
|
|
|
open[top].wantKey = false
|
|
|
|
|
continue
|
|
|
|
|
}
|
|
|
|
|
open[top].wantKey = true
|
|
|
|
|
}
|
|
|
|
|
if count++; count > maxValues {
|
2026-10-31 02:19:51 -07:00
|
|
|
return fmt.Errorf("%w (%d values)", errRemoteListTooLong, maxValues)
|
|
|
|
|
}
|
2026-11-01 04:14:46 -08:00
|
|
|
if isDelim {
|
|
|
|
|
open = append(open, frame{object: delim == '{', wantKey: delim == '{'})
|
|
|
|
|
}
|
2026-10-31 02:19:51 -07:00
|
|
|
}
|
|
|
|
|
return json.Unmarshal(raw, v)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// truncateNodeMessage bounds a node-supplied message the master turns into an error,
|
|
|
|
|
// which is logged and stored as the node's lastError.
|
|
|
|
|
func truncateNodeMessage(msg string) string {
|
|
|
|
|
if len(msg) <= errBodyDiagBytes {
|
|
|
|
|
return msg
|
|
|
|
|
}
|
|
|
|
|
cut := errBodyDiagBytes
|
|
|
|
|
for cut > 0 && !utf8.RuneStart(msg[cut]) {
|
|
|
|
|
cut--
|
|
|
|
|
}
|
|
|
|
|
return msg[:cut] + "... (truncated)"
|
|
|
|
|
}
|