functions.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. package core
  2. import (
  3. "context"
  4. "v2ray.com/core/common"
  5. "v2ray.com/core/common/buf"
  6. "v2ray.com/core/common/net"
  7. "v2ray.com/core/features/routing"
  8. )
  9. // CreateObject creates a new object based on the given V2Ray instance and config. The V2Ray instance may be nil.
  10. func CreateObject(v *Instance, config interface{}) (interface{}, error) {
  11. ctx := context.Background()
  12. if v != nil {
  13. ctx = context.WithValue(ctx, v2rayKey, v)
  14. }
  15. return common.CreateObject(ctx, config)
  16. }
  17. // StartInstance starts a new V2Ray instance with given serialized config.
  18. // By default V2Ray only support config in protobuf format, i.e., configFormat = "protobuf". Caller need to load other packages to add JSON support.
  19. func StartInstance(configFormat string, configBytes []byte) (*Instance, error) {
  20. var mb buf.MultiBuffer
  21. defer mb.Release()
  22. common.Must2(mb.Write(configBytes))
  23. config, err := LoadConfig(configFormat, "", &mb)
  24. if err != nil {
  25. return nil, err
  26. }
  27. instance, err := New(config)
  28. if err != nil {
  29. return nil, err
  30. }
  31. if err := instance.Start(); err != nil {
  32. return nil, err
  33. }
  34. return instance, nil
  35. }
  36. // Dial provides an easy way for upstream caller to create net.Conn through V2Ray.
  37. // It dispatches the request to the given destination by the given V2Ray instance.
  38. // Since it is under a proxy context, the LocalAddr() and RemoteAddr() in returned net.Conn
  39. // will not show real addresses being used for communication.
  40. func Dial(ctx context.Context, v *Instance, dest net.Destination) (net.Conn, error) {
  41. dispatcher := v.GetFeature(routing.DispatcherType())
  42. if dispatcher == nil {
  43. return nil, newError("routing.Dispatcher is not registered in V2Ray core")
  44. }
  45. r, err := dispatcher.(routing.Dispatcher).Dispatch(ctx, dest)
  46. if err != nil {
  47. return nil, err
  48. }
  49. return net.NewConnection(net.ConnectionInputMulti(r.Writer), net.ConnectionOutputMulti(r.Reader)), nil
  50. }