v2fly/functions.go

57 lines
1.8 KiB
Go
Raw Normal View History

2018-05-31 09:55:11 +00:00
package core
import (
"context"
"v2ray.com/core/common"
"v2ray.com/core/common/buf"
2018-10-13 13:21:52 +00:00
"v2ray.com/core/common/net"
2018-10-21 08:27:13 +00:00
"v2ray.com/core/features/routing"
2018-05-31 09:55:11 +00:00
)
// CreateObject creates a new object based on the given V2Ray instance and config. The V2Ray instance may be nil.
func CreateObject(v *Instance, config interface{}) (interface{}, error) {
ctx := context.Background()
if v != nil {
ctx = context.WithValue(ctx, v2rayKey, v)
}
return common.CreateObject(ctx, config)
}
2018-09-21 14:54:06 +00:00
2018-10-11 21:36:38 +00:00
// StartInstance starts a new V2Ray instance with given serialized config.
2018-10-16 12:23:10 +00:00
// By default V2Ray only support config in protobuf format, i.e., configFormat = "protobuf". Caller need to load other packages to add JSON support.
2018-10-11 21:36:38 +00:00
func StartInstance(configFormat string, configBytes []byte) (*Instance, error) {
var mb buf.MultiBuffer
2018-11-12 18:51:21 +00:00
defer mb.Release()
common.Must2(mb.Write(configBytes))
config, err := LoadConfig(configFormat, "", &mb)
if err != nil {
return nil, err
}
instance, err := New(config)
if err != nil {
return nil, err
}
if err := instance.Start(); err != nil {
return nil, err
}
return instance, nil
}
2018-10-13 13:21:52 +00:00
// Dial provides an easy way for upstream caller to create net.Conn through V2Ray.
// It dispatches the request to the given destination by the given V2Ray instance.
// Since it is under a proxy context, the LocalAddr() and RemoteAddr() in returned net.Conn
// will not show real addresses being used for communication.
func Dial(ctx context.Context, v *Instance, dest net.Destination) (net.Conn, error) {
2018-10-21 08:27:13 +00:00
dispatcher := v.GetFeature(routing.DispatcherType())
if dispatcher == nil {
return nil, newError("routing.Dispatcher is not registered in V2Ray core")
}
r, err := dispatcher.(routing.Dispatcher).Dispatch(ctx, dest)
2018-10-13 13:21:52 +00:00
if err != nil {
return nil, err
}
return net.NewConnection(net.ConnectionInputMulti(r.Writer), net.ConnectionOutputMulti(r.Reader)), nil
}