-
Notifications
You must be signed in to change notification settings - Fork 48
/
v2ray.go
345 lines (293 loc) · 8.5 KB
/
v2ray.go
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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
// +build !confonly
package core
import (
"context"
"reflect"
"sync"
"github.com/v2fly/v2ray-core/v4/common"
"github.com/v2fly/v2ray-core/v4/common/serial"
"github.com/v2fly/v2ray-core/v4/features"
"github.com/v2fly/v2ray-core/v4/features/dns"
"github.com/v2fly/v2ray-core/v4/features/dns/localdns"
"github.com/v2fly/v2ray-core/v4/features/inbound"
"github.com/v2fly/v2ray-core/v4/features/outbound"
"github.com/v2fly/v2ray-core/v4/features/policy"
"github.com/v2fly/v2ray-core/v4/features/routing"
"github.com/v2fly/v2ray-core/v4/features/stats"
)
// Server is an instance of V2Ray. At any time, there must be at most one Server instance running.
type Server interface {
common.Runnable
}
// ServerType returns the type of the server.
func ServerType() interface{} {
return (*Instance)(nil)
}
type resolution struct {
deps []reflect.Type
callback interface{}
}
func getFeature(allFeatures []features.Feature, t reflect.Type) features.Feature {
for _, f := range allFeatures {
if reflect.TypeOf(f.Type()) == t {
return f
}
}
return nil
}
func (r *resolution) resolve(allFeatures []features.Feature) (bool, error) {
var fs []features.Feature
for _, d := range r.deps {
f := getFeature(allFeatures, d)
if f == nil {
return false, nil
}
fs = append(fs, f)
}
callback := reflect.ValueOf(r.callback)
var input []reflect.Value
callbackType := callback.Type()
for i := 0; i < callbackType.NumIn(); i++ {
pt := callbackType.In(i)
for _, f := range fs {
if reflect.TypeOf(f).AssignableTo(pt) {
input = append(input, reflect.ValueOf(f))
break
}
}
}
if len(input) != callbackType.NumIn() {
panic("Can't get all input parameters")
}
var err error
ret := callback.Call(input)
errInterface := reflect.TypeOf((*error)(nil)).Elem()
for i := len(ret) - 1; i >= 0; i-- {
if ret[i].Type() == errInterface {
v := ret[i].Interface()
if v != nil {
err = v.(error)
}
break
}
}
return true, err
}
// Instance combines all functionalities in V2Ray.
type Instance struct {
access sync.Mutex
features []features.Feature
featureResolutions []resolution
running bool
ctx context.Context
}
func AddInboundHandler(server *Instance, config *InboundHandlerConfig) error {
inboundManager := server.GetFeature(inbound.ManagerType()).(inbound.Manager)
rawHandler, err := CreateObject(server, config)
if err != nil {
return err
}
handler, ok := rawHandler.(inbound.Handler)
if !ok {
return newError("not an InboundHandler")
}
if err := inboundManager.AddHandler(server.ctx, handler); err != nil {
return err
}
return nil
}
func addInboundHandlers(server *Instance, configs []*InboundHandlerConfig) error {
for _, inboundConfig := range configs {
if err := AddInboundHandler(server, inboundConfig); err != nil {
return err
}
}
return nil
}
func AddOutboundHandler(server *Instance, config *OutboundHandlerConfig) error {
outboundManager := server.GetFeature(outbound.ManagerType()).(outbound.Manager)
rawHandler, err := CreateObject(server, config)
if err != nil {
return err
}
handler, ok := rawHandler.(outbound.Handler)
if !ok {
return newError("not an OutboundHandler")
}
if err := outboundManager.AddHandler(server.ctx, handler); err != nil {
return err
}
return nil
}
func addOutboundHandlers(server *Instance, configs []*OutboundHandlerConfig) error {
for _, outboundConfig := range configs {
if err := AddOutboundHandler(server, outboundConfig); err != nil {
return err
}
}
return nil
}
// RequireFeatures is a helper function to require features from Instance in context.
// See Instance.RequireFeatures for more information.
func RequireFeatures(ctx context.Context, callback interface{}) error {
v := MustFromContext(ctx)
return v.RequireFeatures(callback)
}
// New returns a new V2Ray instance based on given configuration.
// The instance is not started at this point.
// To ensure V2Ray instance works properly, the config must contain one Dispatcher, one InboundHandlerManager and one OutboundHandlerManager. Other features are optional.
func New(config *Config) (*Instance, error) {
server := &Instance{ctx: context.Background()}
done, err := initInstanceWithConfig(config, server)
if done {
return nil, err
}
return server, nil
}
func NewWithContext(ctx context.Context, config *Config) (*Instance, error) {
server := &Instance{ctx: ctx}
done, err := initInstanceWithConfig(config, server)
if done {
return nil, err
}
return server, nil
}
func initInstanceWithConfig(config *Config, server *Instance) (bool, error) {
if config.Transport != nil {
features.PrintDeprecatedFeatureWarning("global transport settings")
}
if err := config.Transport.Apply(); err != nil {
return true, err
}
for _, appSettings := range config.App {
settings, err := appSettings.GetInstance()
if err != nil {
return true, err
}
obj, err := CreateObject(server, settings)
if err != nil {
return true, err
}
if feature, ok := obj.(features.Feature); ok {
if err := server.AddFeature(feature); err != nil {
return true, err
}
}
}
essentialFeatures := []struct {
Type interface{}
Instance features.Feature
}{
{dns.ClientType(), localdns.New()},
{policy.ManagerType(), policy.DefaultManager{}},
{routing.RouterType(), routing.DefaultRouter{}},
{stats.ManagerType(), stats.NoopManager{}},
}
for _, f := range essentialFeatures {
if server.GetFeature(f.Type) == nil {
if err := server.AddFeature(f.Instance); err != nil {
return true, err
}
}
}
if server.featureResolutions != nil {
return true, newError("not all dependency are resolved.")
}
if err := addInboundHandlers(server, config.Inbound); err != nil {
return true, err
}
if err := addOutboundHandlers(server, config.Outbound); err != nil {
return true, err
}
return false, nil
}
// Type implements common.HasType.
func (s *Instance) Type() interface{} {
return ServerType()
}
// Close shutdown the V2Ray instance.
func (s *Instance) Close() error {
s.access.Lock()
defer s.access.Unlock()
s.running = false
var errors []interface{}
for _, f := range s.features {
if err := f.Close(); err != nil {
errors = append(errors, err)
}
}
if len(errors) > 0 {
return newError("failed to close all features").Base(newError(serial.Concat(errors...)))
}
return nil
}
// RequireFeatures registers a callback, which will be called when all dependent features are registered.
// The callback must be a func(). All its parameters must be features.Feature.
func (s *Instance) RequireFeatures(callback interface{}) error {
callbackType := reflect.TypeOf(callback)
if callbackType.Kind() != reflect.Func {
panic("not a function")
}
var featureTypes []reflect.Type
for i := 0; i < callbackType.NumIn(); i++ {
featureTypes = append(featureTypes, reflect.PtrTo(callbackType.In(i)))
}
r := resolution{
deps: featureTypes,
callback: callback,
}
if finished, err := r.resolve(s.features); finished {
return err
}
s.featureResolutions = append(s.featureResolutions, r)
return nil
}
// AddFeature registers a feature into current Instance.
func (s *Instance) AddFeature(feature features.Feature) error {
s.features = append(s.features, feature)
if s.running {
if err := feature.Start(); err != nil {
newError("failed to start feature").Base(err).WriteToLog()
}
return nil
}
if s.featureResolutions == nil {
return nil
}
var pendingResolutions []resolution
for _, r := range s.featureResolutions {
finished, err := r.resolve(s.features)
if finished && err != nil {
return err
}
if !finished {
pendingResolutions = append(pendingResolutions, r)
}
}
if len(pendingResolutions) == 0 {
s.featureResolutions = nil
} else if len(pendingResolutions) < len(s.featureResolutions) {
s.featureResolutions = pendingResolutions
}
return nil
}
// GetFeature returns a feature of the given type, or nil if such feature is not registered.
func (s *Instance) GetFeature(featureType interface{}) features.Feature {
return getFeature(s.features, reflect.TypeOf(featureType))
}
// Start starts the V2Ray instance, including all registered features. When Start returns error, the state of the instance is unknown.
// A V2Ray instance can be started only once. Upon closing, the instance is not guaranteed to start again.
//
// v2ray:api:stable
func (s *Instance) Start() error {
s.access.Lock()
defer s.access.Unlock()
s.running = true
for _, f := range s.features {
if err := f.Start(); err != nil {
return err
}
}
newError("V2Ray ", Version(), " started").AtWarning().WriteToLog()
return nil
}