functions.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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. func StartInstance(configFormat string, configBytes []byte) (*Instance, error) {
  18. var mb buf.MultiBuffer
  19. common.Must2(mb.Write(configBytes))
  20. config, err := LoadConfig(configFormat, "", &mb)
  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. r, err := v.Dispatcher().Dispatch(ctx, dest)
  39. if err != nil {
  40. return nil, err
  41. }
  42. return net.NewConnection(net.ConnectionInputMulti(r.Writer), net.ConnectionOutputMulti(r.Reader)), nil
  43. }