functions.go 1.8 KB

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