-
Notifications
You must be signed in to change notification settings - Fork 375
Expand file tree
/
Copy pathbuilder.go
More file actions
168 lines (144 loc) · 6.29 KB
/
Copy pathbuilder.go
File metadata and controls
168 lines (144 loc) · 6.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
package outbound
import (
"context"
"encoding/json"
"errors"
"fmt"
stdlog "log"
"github.com/sagernet/sing-box/adapter"
"github.com/sagernet/sing-box/adapter/endpoint"
"github.com/sagernet/sing-box/adapter/inbound"
sbOutbound "github.com/sagernet/sing-box/adapter/outbound"
"github.com/sagernet/sing-box/dns"
"github.com/sagernet/sing-box/include"
"github.com/sagernet/sing-box/log"
"github.com/sagernet/sing-box/option"
"github.com/sagernet/sing/common"
sJson "github.com/sagernet/sing/common/json"
"github.com/sagernet/sing/service"
)
// OutboundBuilder creates outbound instances from raw node options.
type OutboundBuilder interface {
Build(rawOptions json.RawMessage) (adapter.Outbound, error)
}
// ---------------------------------------------------------------------------
// SingboxBuilder — creates real sing-box adapter.Outbound instances.
// ---------------------------------------------------------------------------
// SingboxBuilder builds real sing-box outbound instances from raw JSON options.
// It holds a fully-wired context with DNS services so that domain-based
// outbound servers can be resolved.
type SingboxBuilder struct {
outboundManager *sbOutbound.Manager
ctx context.Context
logFactory log.Factory
dnsTransportManager *dns.TransportManager
dnsRouter *dns.Router
}
// NewSingboxBuilder creates a SingboxBuilder with a complete sing-box service
// graph (registries + DNS). The caller must call Close() when done.
func NewSingboxBuilder() (*SingboxBuilder, error) {
ctx := context.Background()
ctx = include.Context(ctx) // inject protocol registries
logFactory := log.NewNOPFactory()
logger := logFactory.NewLogger("resin-outbound")
dnsRegistry, ok := service.FromContext[adapter.DNSTransportRegistry](ctx).(*dns.TransportRegistry)
if !ok {
return nil, fmt.Errorf("singbox builder: unexpected DNS transport registry type %T", service.FromContext[adapter.DNSTransportRegistry](ctx))
}
registerSecureDNSTransport(dnsRegistry)
// --- Service graph (same order as Demos/simple-proxy/main.go) -----------
// Endpoint Manager
endpointMgr := endpoint.NewManager(logger, service.FromContext[adapter.EndpointRegistry](ctx))
service.MustRegister[adapter.EndpointManager](ctx, endpointMgr)
// Inbound Manager (required dependency even though unused)
inboundMgr := inbound.NewManager(logger, service.FromContext[adapter.InboundRegistry](ctx), endpointMgr)
service.MustRegister[adapter.InboundManager](ctx, inboundMgr)
// Outbound Manager (sing-box's own manager, for detour resolution)
outboundMgr := sbOutbound.NewManager(logger, service.FromContext[adapter.OutboundRegistry](ctx), endpointMgr, "")
service.MustRegister[adapter.OutboundManager](ctx, outboundMgr)
// DNS Transport Manager
dnsTransportMgr := dns.NewTransportManager(logger, service.FromContext[adapter.DNSTransportRegistry](ctx), outboundMgr, secureDNSFailoverTransportTag)
service.MustRegister[adapter.DNSTransportManager](ctx, dnsTransportMgr)
// DNS Router
dnsRouter := dns.NewRouter(ctx, logFactory, option.DNSOptions{})
service.MustRegister[adapter.DNSRouter](ctx, dnsRouter)
for _, spec := range secureDNSTransportSpecs() {
if err := dnsTransportMgr.Create(ctx, logger, spec.tag, spec.transportType, spec.options); err != nil {
return nil, fmt.Errorf("singbox builder: create DNS transport %s[%s]: %w", spec.transportType, spec.tag, err)
}
}
// Start DNS Transport Manager lifecycle
if err := dnsTransportMgr.Start(adapter.StartStateInitialize); err != nil {
return nil, fmt.Errorf("singbox builder: initialize DNS transport manager: %w", err)
}
if err := dnsTransportMgr.Start(adapter.StartStateStart); err != nil {
_ = dnsTransportMgr.Close()
return nil, fmt.Errorf("singbox builder: start DNS transport manager: %w", err)
}
// Start DNS Router lifecycle
if err := dnsRouter.Initialize(nil); err != nil {
_ = dnsTransportMgr.Close()
return nil, fmt.Errorf("singbox builder: initialize DNS router: %w", err)
}
if err := dnsRouter.Start(adapter.StartStateStart); err != nil {
_ = dnsRouter.Close()
_ = dnsTransportMgr.Close()
return nil, fmt.Errorf("singbox builder: start DNS router: %w", err)
}
return &SingboxBuilder{
outboundManager: outboundMgr,
ctx: ctx,
logFactory: logFactory,
dnsTransportManager: dnsTransportMgr,
dnsRouter: dnsRouter,
}, nil
}
// Build parses rawOptions (a complete sing-box outbound JSON object with
// type/tag fields) into a real adapter.Outbound and runs it through the
// lifecycle stages.
func (b *SingboxBuilder) Build(rawOptions json.RawMessage) (adapter.Outbound, error) {
// 1. Parse via official option.Outbound path (strips type/tag, creates
// typed options via OutboundOptionsRegistry + badjson.UnmarshallExcluded).
var outboundConfig option.Outbound
if err := sJson.UnmarshalContext(b.ctx, rawOptions, &outboundConfig); err != nil {
return nil, fmt.Errorf("parse outbound options: %w", err)
}
fmt.Printf("[outbound] raw=%s\n", string(rawOptions))
stdlog.Printf("[outbound] raw=%s", string(rawOptions))
// 2. Create the outbound instance via manager.Create so detour dependencies
// can be resolved against a shared outbound manager registry.
logger := b.logFactory.NewLogger("outbound/" + outboundConfig.Type)
if err := b.outboundManager.Create(
b.ctx,
nil, // router — not needed for simple dialing
logger,
outboundConfig.Tag,
outboundConfig.Type,
outboundConfig.Options,
); err != nil {
return nil, fmt.Errorf("create outbound [%s]: %w", outboundConfig.Type, err)
}
ob, ok := b.outboundManager.Outbound(outboundConfig.Tag)
if !ok {
return nil, fmt.Errorf("create outbound [%s]: created outbound not found by tag %s", outboundConfig.Type, outboundConfig.Tag)
}
// 3. Run lifecycle start stages. On failure, close and return error.
for _, stage := range adapter.ListStartStages {
if err := adapter.LegacyStart(ob, stage); err != nil {
_ = common.Close(ob)
return nil, fmt.Errorf("outbound start %s [%s]: %w", stage, outboundConfig.Type, err)
}
}
return ob, nil
}
// Close shuts down the builder's internal DNS services.
func (b *SingboxBuilder) Close() error {
var errs []error
if b.dnsRouter != nil {
errs = append(errs, b.dnsRouter.Close())
}
if b.dnsTransportManager != nil {
errs = append(errs, b.dnsTransportManager.Close())
}
return errors.Join(errs...)
}