functions.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. package core
  2. import (
  3. "bytes"
  4. "context"
  5. "v2ray.com/core/common"
  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. //
  20. // v2ray:api:stable
  21. func StartInstance(configFormat string, configBytes []byte) (*Instance, error) {
  22. config, err := LoadConfig(configFormat, "", bytes.NewReader(configBytes))
  23. if err != nil {
  24. return nil, err
  25. }
  26. instance, err := New(config)
  27. if err != nil {
  28. return nil, err
  29. }
  30. if err := instance.Start(); err != nil {
  31. return nil, err
  32. }
  33. return instance, nil
  34. }
  35. // Dial provides an easy way for upstream caller to create net.Conn through V2Ray.
  36. // It dispatches the request to the given destination by the given V2Ray instance.
  37. // Since it is under a proxy context, the LocalAddr() and RemoteAddr() in returned net.Conn
  38. // will not show real addresses being used for communication.
  39. //
  40. // v2ray:api:stable
  41. func Dial(ctx context.Context, v *Instance, dest net.Destination) (net.Conn, error) {
  42. dispatcher := v.GetFeature(routing.DispatcherType())
  43. if dispatcher == nil {
  44. return nil, newError("routing.Dispatcher is not registered in V2Ray core")
  45. }
  46. r, err := dispatcher.(routing.Dispatcher).Dispatch(ctx, dest)
  47. if err != nil {
  48. return nil, err
  49. }
  50. return net.NewConnection(net.ConnectionInputMulti(r.Writer), net.ConnectionOutputMulti(r.Reader)), nil
  51. }