Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 12 additions & 2 deletions internal/backend/sagernet/backend.go
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,10 @@ func (o *Outbound) Close() error {
}

// DirectSpec dials the destination directly.
type DirectSpec struct{}
type DirectSpec struct {
// DomainStrategy uses the sing-box domain_strategy values.
DomainStrategy string
}

// ShadowsocksSpec is a Shadowsocks client.
type ShadowsocksSpec struct {
Expand Down Expand Up @@ -323,7 +326,14 @@ func (b *Backend) NewOutbound(tag string, spec any) (*Outbound, error) {
out = newDropOutbound(tag)
case DirectSpec:
typ = "direct"
out, err = direct.NewOutbound(b.ctx, b.router, b.componentLogger("outbound", typ, tag), tag, option.DirectOutboundOptions{})
var opts option.DirectOutboundOptions
if s.DomainStrategy != "" {
strategy, _ := json.Marshal(s.DomainStrategy)
if err = opts.DomainStrategy.UnmarshalJSON(strategy); err != nil {
break
}
}
out, err = direct.NewOutbound(b.ctx, b.router, b.componentLogger("outbound", typ, tag), tag, opts)
case HTTPSpec:
typ = "http"
out, err = http.NewOutbound(b.ctx, b.router, b.componentLogger("outbound", typ, tag), tag, option.HTTPOutboundOptions{
Expand Down
41 changes: 24 additions & 17 deletions internal/config/compile/compile.go
Original file line number Diff line number Diff line change
Expand Up @@ -593,26 +593,33 @@ func (c *compiler) outbounds(eff *Effective) {
}
}
for i := range eff.Outbounds {
identity := eff.Outbounds[i]
identity.Name = "" // display metadata must not rebuild a live outbound
if identity.Multiplex != nil {
m := *identity.Multiplex
m.Statistic = false
identity.Multiplex = &m
}
plugin, _ := json.Marshal(identity.Plugin)
params, _ := json.Marshal(identity.Protocol)
transport, _ := json.Marshal(identity.Transport)
headers, _ := json.Marshal(identity.Headers)
tlsSecrets := ""
if identity.TLS != nil {
carrier, _ := json.Marshal(identity.TLS.Carrier)
tlsSecrets = identity.TLS.Certificate + "\x00" + identity.TLS.PrivateKey + "\x00" + string(carrier)
}
eff.Outbounds[i].Fingerprint = fingerprint(identity, identity.Username, identity.Password, identity.UUID, identity.Encryption, string(plugin), string(params), string(transport), string(headers), tlsSecrets)
out := &eff.Outbounds[i]
if out.Dialer == nil || out.Dialer.Proxy == "" {
out.Fingerprint = outboundFingerprint(*out)
}
}
}

func outboundFingerprint(identity Outbound) string {
identity.Name = "" // display metadata must not rebuild a live outbound
identity.Fingerprint = ""
if identity.Multiplex != nil {
m := *identity.Multiplex
m.Statistic = false
identity.Multiplex = &m
}
plugin, _ := json.Marshal(identity.Plugin)
params, _ := json.Marshal(identity.Protocol)
transport, _ := json.Marshal(identity.Transport)
headers, _ := json.Marshal(identity.Headers)
tlsSecrets := ""
if identity.TLS != nil {
carrier, _ := json.Marshal(identity.TLS.Carrier)
tlsSecrets = identity.TLS.Certificate + "\x00" + identity.TLS.PrivateKey + "\x00" + string(carrier)
}
return fingerprint(identity, identity.Username, identity.Password, identity.UUID, identity.Encryption, string(plugin), string(params), string(transport), string(headers), tlsSecrets)
}

func (c *compiler) hasErrorAt(path string) bool {
for _, d := range c.diags {
if d.Path == path && d.Severity == model.SeverityError {
Expand Down
39 changes: 26 additions & 13 deletions internal/config/compile/detour.go
Original file line number Diff line number Diff line change
@@ -1,43 +1,55 @@
package compile

import (
"fmt"
"slices"
"strings"

"github.com/MimoProxy/reka/internal/config/model"
"github.com/MimoProxy/reka/internal/router"
)

// detours validates the combined outbound/group dependency graph and folds
// every possible parent transport into a child's replacement fingerprint.
func (c *compiler) detours(e *Effective) {
for _, o := range e.Outbounds {
if d := o.Dialer; d != nil && d.Proxy != "" && (d.Interface != "" || d.RoutingMark != 0 || d.IPVersion != "" || d.TFO || d.MPTCP) {
c.warnf(model.DocProfile, "/outbounds/"+o.ID+"/dialer", "outbound.detour-options", "dialer proxy uses its parent's physical socket options; set interface, routing mark, IP version, TFO and MPTCP on the parent")
}
}
if !c.diags.HasErrors() {
for _, message := range e.fingerprintDetours() {
c.errorf(model.DocProfile, "/outbounds", "outbound.detour", "%s", message)
}
}
}

// fingerprintDetours validates the combined outbound/group dependency graph
// and folds every possible parent transport into a child's fingerprint.
func (e *Effective) fingerprintDetours() []string {
hasDetour := false
nodes := map[string]*Outbound{}
groups := map[string]router.Group{}
for i := range e.Outbounds {
o := &e.Outbounds[i]
nodes[o.ID] = o
hasDetour = hasDetour || o.Dialer != nil && o.Dialer.Proxy != ""
if d := o.Dialer; d != nil && d.Proxy != "" && (d.Interface != "" || d.RoutingMark != 0 || d.IPVersion != "" || d.TFO || d.MPTCP) {
c.warnf(model.DocProfile, "/outbounds/"+o.ID+"/dialer", "outbound.detour-options", "dialer proxy uses its parent's physical socket options; set interface, routing mark, IP version, TFO and MPTCP on the parent")
}
}
if !hasDetour || c.diags.HasErrors() {
return
if !hasDetour {
return nil
}
groups := map[string]router.Group{}
for _, g := range e.Groups {
groups[g.ID] = g
}
state := map[string]int{}
hashes := map[string]string{}
stack := []string{}
var problems []string
var visit func(string) string
visit = func(id string) string {
if state[id] == 2 {
return hashes[id]
}
if state[id] == 1 {
c.errorf(model.DocProfile, "/outbounds", "outbound.detour", "cyclic dialer dependency: %s", strings.Join(append(stack, id), " -> "))
problems = append(problems, "cyclic dialer dependency: "+strings.Join(append(stack, id), " -> "))
return ""
}
state[id] = 1
Expand All @@ -56,10 +68,10 @@ func (c *compiler) detours(e *Effective) {
hashes[id] = o.Fingerprint
if o.Dialer != nil && o.Dialer.Proxy != "" {
parent := visit(o.Dialer.Proxy)
hashes[id] = fingerprint(o.Fingerprint, parent)
hashes[id] = fingerprint(outboundFingerprint(*o), parent)
}
} else {
c.errorf(model.DocProfile, "/outbounds", "outbound.detour", "dialer target %q is unavailable", id)
problems = append(problems, fmt.Sprintf("dialer target %q is unavailable", id))
}
state[id] = 2
return hashes[id]
Expand All @@ -69,14 +81,15 @@ func (c *compiler) detours(e *Effective) {
visit(o.ID)
}
}
if c.diags.HasErrors() {
return
if len(problems) > 0 {
return problems
}
for _, o := range nodes {
if o.Dialer != nil && o.Dialer.Proxy != "" {
o.Fingerprint = hashes[o.ID]
}
}
return nil
}

// DetourLeaves returns the direct possible parents of one detour (all group
Expand Down
10 changes: 7 additions & 3 deletions internal/config/compile/dns.go
Original file line number Diff line number Diff line change
Expand Up @@ -131,12 +131,16 @@ func (c *compiler) dns(eff *Effective) {
}
eff.DNS = cfg
eff.DNSMatches = matchers
eff.DNSFingerprint = eff.dnsFingerprint()
}

func (e *Effective) dnsFingerprint() string {
hashes := map[string]string{}
for name, r := range matchers {
for name, r := range e.DNSMatches {
hashes[name] = fingerprint(r.Rules().Rule(0))
}
eff.DNSFingerprint = fingerprint(struct {
return fingerprint(struct {
Config *RD.Config
Matches map[string]string
}{cfg, hashes})
}{e.DNS, hashes})
}
58 changes: 58 additions & 0 deletions internal/config/compile/ip_version.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package compile

import (
"errors"
"slices"

"github.com/MimoProxy/reka/internal/config/model"
)

// WithIPVersion returns a copy with the dialer IP policy and DNS IPv6 setting
// overridden. An empty policy keeps the compiled settings.
func (e *Effective) WithIPVersion(ipVersion string) (*Effective, error) {
eff := *e
switch ipVersion {
case "":
return &eff, nil
case "dual", "ipv4", "ipv6", "ipv4-prefer", "ipv6-prefer":
default:
return nil, errors.New("unknown IP version policy")
}
if e.DNS != nil {
cfg := *e.DNS
cfg.IPv6 = ipVersion != "ipv4"
eff.DNS = &cfg
if cfg.IPv6 != e.DNS.IPv6 {
eff.DNSFingerprint = eff.dnsFingerprint()
}
}
if ipVersion == "dual" {
ipVersion = ""
}
eff.Outbounds = slices.Clone(e.Outbounds)
changed := false
for i := range eff.Outbounds {
out := &eff.Outbounds[i]
switch out.Type {
case model.OutboundReject, "pass", "reject-drop":
continue
}
var dialer model.Dialer
if out.Dialer != nil {
dialer = *out.Dialer
}
if dialer.Proxy != "" || dialer.IPVersion == ipVersion {
continue
}
dialer.IPVersion = ipVersion
out.Dialer = &dialer
out.Fingerprint = outboundFingerprint(*out)
changed = true
}
if changed {
if problems := eff.fingerprintDetours(); len(problems) > 0 {
return nil, errors.New(problems[0])
}
}
return &eff, nil
}
30 changes: 23 additions & 7 deletions internal/runtime/generation/engine.go
Original file line number Diff line number Diff line change
Expand Up @@ -178,8 +178,9 @@ func NewEngine(opts EngineOptions) *Engine {
e.opts.Resolver = e.backend.Resolver()
}
e.rt = runtime.NewValue[*sagernet.Outbound](nil, &generation{historyScope: history.Scope{ProfileID: opts.ProfileID}}, runtime.Options{
DrainTimeout: opts.DrainTimeout,
MaxRetiring: opts.MaxRetiring,
DrainTimeout: opts.DrainTimeout,
MaxRetiring: opts.MaxRetiring,
AllowLargeReplacement: opts.HostPacketFlow,
OnClosed: func(id string, gen uint64, forced int64, err error) {
l := slog.Default()
if opts.Backend.Logger != nil {
Expand Down Expand Up @@ -273,10 +274,11 @@ func (e *Engine) plan(eff *compile.Effective) Plan {
p.Draining++
}
}
if cur := int(e.rt.Stats().Retiring); cur+p.Draining > e.opts.MaxRetiring {
p.Blocked = fmt.Sprintf("%d instances are draining and this change adds %d; the limit is %d", cur, p.Draining, e.opts.MaxRetiring)
retiring := int(e.rt.Stats().Retiring)
if limit := e.rt.RetiringLimit(p.Draining); retiring+p.Draining > limit {
p.Blocked = fmt.Sprintf("%d instances are draining and this change adds %d; the limit is %d", retiring, p.Draining, limit)
}
p.Draining += int(e.rt.Stats().Retiring)
p.Draining += retiring

for _, ch := range e.listenerChanges(eff.Listeners) {
p.Listeners = append(p.Listeners, ch.ResourceChange)
Expand Down Expand Up @@ -742,6 +744,9 @@ func usesUpstreamOutbound(o compile.Outbound) bool {
}

func specFor(o compile.Outbound) any {
if o.Builtin && o.Type == model.OutboundDirect {
return sagernet.DirectSpec{DomainStrategy: domainStrategy(o.Dialer)}
}
tls := func() *sagernet.TLSSpec {
if o.TLS == nil {
return nil
Expand Down Expand Up @@ -1289,12 +1294,23 @@ func (e *Engine) ListenerInstance(id string) any {
return nil
}

func domainStrategy(dialer *model.Dialer) string {
if dialer == nil {
return ""
}
return map[string]string{
"ipv4": "ipv4_only",
"ipv6": "ipv6_only",
"ipv4-prefer": "prefer_ipv4",
"ipv6-prefer": "prefer_ipv6",
}[dialer.IPVersion]
}

func protocolOptions(o compile.Outbound) json.RawMessage {
values := map[string]any{}
if d := o.Dialer; d != nil {
values["bind_interface"], values["routing_mark"], values["tcp_fast_open"], values["tcp_multi_path"] = d.Interface, d.RoutingMark, d.TFO, d.MPTCP
strategy := map[string]string{"ipv4": "ipv4_only", "ipv6": "ipv6_only", "ipv4-prefer": "prefer_ipv4", "ipv6-prefer": "prefer_ipv6"}[d.IPVersion]
if strategy != "" {
if strategy := domainStrategy(d); strategy != "" {
values["domain_strategy"] = strategy
}
}
Expand Down
Loading
Loading