functions.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. "v2ray.com/core/transport/internet/udp"
  9. )
  10. // CreateObject creates a new object based on the given V2Ray instance and config. The V2Ray instance may be nil.
  11. func CreateObject(v *Instance, config interface{}) (interface{}, error) {
  12. ctx := context.Background()
  13. if v != nil {
  14. ctx = context.WithValue(ctx, v2rayKey, v)
  15. }
  16. return common.CreateObject(ctx, config)
  17. }
  18. // StartInstance starts a new V2Ray instance with given serialized config.
  19. // By default V2Ray only support config in protobuf format, i.e., configFormat = "protobuf". Caller need to load other packages to add JSON support.
  20. //
  21. // v2ray:api:stable
  22. func StartInstance(configFormat string, configBytes []byte) (*Instance, error) {
  23. config, err := LoadConfig(configFormat, "", bytes.NewReader(configBytes))
  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. //
  41. // v2ray:api:stable
  42. func Dial(ctx context.Context, v *Instance, dest net.Destination) (net.Conn, error) {
  43. dispatcher := v.GetFeature(routing.DispatcherType())
  44. if dispatcher == nil {
  45. return nil, newError("routing.Dispatcher is not registered in V2Ray core")
  46. }
  47. r, err := dispatcher.(routing.Dispatcher).Dispatch(ctx, dest)
  48. if err != nil {
  49. return nil, err
  50. }
  51. return net.NewConnection(net.ConnectionInputMulti(r.Writer), net.ConnectionOutputMulti(r.Reader)), nil
  52. }
  53. // DialUDP provides a way to exchange UDP packets through V2Ray instance to remote servers.
  54. // Since it is under a proxy context, the LocalAddr() in returned PacketConn will not show the real address.
  55. //
  56. // TODO: SetDeadline() / SetReadDeadline() / SetWriteDeadline() are not implemented.
  57. //
  58. // v2ray:api:beta
  59. func DialUDP(ctx context.Context, v *Instance) (net.PacketConn, error) {
  60. dispatcher := v.GetFeature(routing.DispatcherType())
  61. if dispatcher == nil {
  62. return nil, newError("routing.Dispatcher is not registered in V2Ray core")
  63. }
  64. return udp.DialDispatcher(ctx, dispatcher.(routing.Dispatcher))
  65. }