Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
105 lines
2.5 KiB
Go
105 lines
2.5 KiB
Go
package server
|
|
|
|
import (
|
|
"sort"
|
|
"strings"
|
|
)
|
|
|
|
// maxHostSel bounds how many names one host selection may carry.
|
|
const maxHostSel = 16
|
|
|
|
// hostSel is a resolved host selection of a request: "all" (or empty), one
|
|
// host, or a comma list such as host=oracle,hostinger.
|
|
type hostSel struct {
|
|
all bool // every host: no filtering
|
|
local bool // this node is part of the selection
|
|
peers []string // the other nodes of the selection (sorted), empty with all
|
|
}
|
|
|
|
// csv is the canonical text of the selection ("" for all): the hub's own name
|
|
// (when present) first, then the peers.
|
|
func (h hostSel) csv(self string) string {
|
|
if h.all {
|
|
return ""
|
|
}
|
|
var n []string
|
|
if h.local {
|
|
n = append(n, self)
|
|
}
|
|
return strings.Join(append(n, h.peers...), ",")
|
|
}
|
|
|
|
// only is the peers' list the fed.Hub understands ("" asks every node).
|
|
func (h hostSel) only() string {
|
|
if h.all {
|
|
return ""
|
|
}
|
|
return strings.Join(h.peers, ",")
|
|
}
|
|
|
|
// parseHosts resolves a host query value. ok is false for names this hub does
|
|
// not serve, for a malformed or oversized list.
|
|
func (s *Server) parseHosts(raw string) (hostSel, bool) {
|
|
raw = strings.TrimSpace(raw)
|
|
if raw == "" || raw == "all" {
|
|
return hostSel{all: true, local: true}, true
|
|
}
|
|
if len(raw) > 64*maxHostSel {
|
|
return hostSel{}, false
|
|
}
|
|
self := s.opt.Store.Name()
|
|
seen := map[string]bool{}
|
|
var sel hostSel
|
|
for _, n := range strings.Split(raw, ",") {
|
|
n = strings.TrimSpace(n)
|
|
switch {
|
|
case n == "":
|
|
continue
|
|
case n == "all":
|
|
return hostSel{all: true, local: true}, true
|
|
case len(n) > 64 || len(seen) >= maxHostSel:
|
|
return hostSel{}, false
|
|
case seen[n]:
|
|
continue
|
|
}
|
|
seen[n] = true
|
|
if n == self {
|
|
sel.local = true
|
|
} else if s.opt.Hub != nil && s.opt.Hub.Has(n) {
|
|
sel.peers = append(sel.peers, n)
|
|
} else {
|
|
return hostSel{}, false
|
|
}
|
|
}
|
|
if len(seen) == 0 {
|
|
return hostSel{all: true, local: true}, true
|
|
}
|
|
sort.Strings(sel.peers)
|
|
// naming every node is the same as asking for all of them
|
|
if sel.local {
|
|
every := true
|
|
if s.opt.Hub != nil {
|
|
for _, p := range s.opt.Hub.PeerNames() {
|
|
every = every && seen[p]
|
|
}
|
|
}
|
|
if every {
|
|
return hostSel{all: true, local: true}, true
|
|
}
|
|
}
|
|
return sel, true
|
|
}
|
|
|
|
// hostListOK bounds the text of a host list: names of 64 bytes at most, 16 at most.
|
|
func hostListOK(raw string) bool {
|
|
if len(raw) > 64*maxHostSel+maxHostSel {
|
|
return false
|
|
}
|
|
for _, n := range strings.Split(raw, ",") {
|
|
if len(strings.TrimSpace(n)) > 64 {
|
|
return false
|
|
}
|
|
}
|
|
return true
|
|
}
|