functions.go 1.6 KB

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