functions.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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. common.Must2(mb.Write(configBytes))
  22. config, err := LoadConfig(configFormat, "", &mb)
  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. func Dial(ctx context.Context, v *Instance, dest net.Destination) (net.Conn, error) {
  40. dispatcher := v.GetFeature(routing.DispatcherType())
  41. if dispatcher == nil {
  42. return nil, newError("routing.Dispatcher is not registered in V2Ray core")
  43. }
  44. r, err := dispatcher.(routing.Dispatcher).Dispatch(ctx, dest)
  45. if err != nil {
  46. return nil, err
  47. }
  48. return net.NewConnection(net.ConnectionInputMulti(r.Writer), net.ConnectionOutputMulti(r.Reader)), nil
  49. }