point.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package point
  2. import (
  3. "github.com/v2ray/v2ray-core/app/point/config"
  4. "github.com/v2ray/v2ray-core/common/log"
  5. v2net "github.com/v2ray/v2ray-core/common/net"
  6. "github.com/v2ray/v2ray-core/common/retry"
  7. "github.com/v2ray/v2ray-core/proxy/common/connhandler"
  8. "github.com/v2ray/v2ray-core/transport/ray"
  9. )
  10. // Point is an single server in V2Ray system.
  11. type Point struct {
  12. port uint16
  13. ich connhandler.InboundConnectionHandler
  14. och connhandler.OutboundConnectionHandler
  15. }
  16. // NewPoint returns a new Point server based on given configuration.
  17. // The server is not started at this point.
  18. func NewPoint(pConfig config.PointConfig) (*Point, error) {
  19. var vpoint = new(Point)
  20. vpoint.port = pConfig.Port()
  21. ichFactory := connhandler.GetInboundConnectionHandlerFactory(pConfig.InboundConfig().Protocol())
  22. if ichFactory == nil {
  23. log.Error("Unknown inbound connection handler factory %s", pConfig.InboundConfig().Protocol())
  24. return nil, config.BadConfiguration
  25. }
  26. ichConfig := pConfig.InboundConfig().Settings()
  27. ich, err := ichFactory.Create(vpoint, ichConfig)
  28. if err != nil {
  29. log.Error("Failed to create inbound connection handler: %v", err)
  30. return nil, err
  31. }
  32. vpoint.ich = ich
  33. ochFactory := connhandler.GetOutboundConnectionHandlerFactory(pConfig.OutboundConfig().Protocol())
  34. if ochFactory == nil {
  35. log.Error("Unknown outbound connection handler factory %s", pConfig.OutboundConfig().Protocol())
  36. return nil, config.BadConfiguration
  37. }
  38. ochConfig := pConfig.OutboundConfig().Settings()
  39. och, err := ochFactory.Create(ochConfig)
  40. if err != nil {
  41. log.Error("Failed to create outbound connection handler: %v", err)
  42. return nil, err
  43. }
  44. vpoint.och = och
  45. return vpoint, nil
  46. }
  47. // Start starts the Point server, and return any error during the process.
  48. // In the case of any errors, the state of the server is unpredicatable.
  49. func (vp *Point) Start() error {
  50. if vp.port <= 0 {
  51. log.Error("Invalid port %d", vp.port)
  52. return config.BadConfiguration
  53. }
  54. return retry.Timed(100 /* times */, 100 /* ms */).On(func() error {
  55. err := vp.ich.Listen(vp.port)
  56. if err == nil {
  57. log.Warning("Point server started on port %d", vp.port)
  58. return nil
  59. }
  60. return err
  61. })
  62. }
  63. func (p *Point) DispatchToOutbound(packet v2net.Packet) ray.InboundRay {
  64. direct := ray.NewRay()
  65. go p.och.Dispatch(packet, direct)
  66. return direct
  67. }