unix.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. package inbound
  2. import (
  3. "context"
  4. "v2ray.com/core/app/proxyman"
  5. "v2ray.com/core/app/proxyman/mux"
  6. "v2ray.com/core/common"
  7. "v2ray.com/core/common/net"
  8. "v2ray.com/core/proxy"
  9. "v2ray.com/core/transport/internet/domainsocket"
  10. )
  11. type UnixInboundHandler struct {
  12. tag string
  13. listenerHolder *domainsocket.Listener
  14. ctx context.Context
  15. path string
  16. proxy proxy.Inbound
  17. mux *mux.Server
  18. }
  19. func (uih *UnixInboundHandler) Start() {
  20. var err error
  21. uih.listenerHolder, err = domainsocket.ListenDS(uih.ctx, uih.path)
  22. if err != nil {
  23. newError(err).AtError().WriteToLog()
  24. }
  25. err = uih.listenerHolder.LowerUP()
  26. if err != nil {
  27. newError(err).AtError().WriteToLog()
  28. }
  29. nchan := make(chan net.Conn, 2)
  30. err = uih.listenerHolder.UP(nchan, false)
  31. if err != nil {
  32. newError(err).AtError().WriteToLog()
  33. }
  34. go uih.progressTraffic(nchan)
  35. return
  36. }
  37. func (uih *UnixInboundHandler) progressTraffic(rece <-chan net.Conn) {
  38. for {
  39. conn := <-rece
  40. go func(conn net.Conn) {
  41. ctx, cancel := context.WithCancel(uih.ctx)
  42. if len(uih.tag) > 0 {
  43. ctx = proxy.ContextWithInboundTag(ctx, uih.tag)
  44. }
  45. if err := uih.proxy.Process(ctx, net.Network_TCP, conn, uih.mux); err != nil {
  46. newError("connection ends").Base(err).WriteToLog()
  47. }
  48. cancel()
  49. conn.Close()
  50. }(conn)
  51. }
  52. }
  53. func (uih *UnixInboundHandler) Close() {
  54. if uih.listenerHolder != nil {
  55. uih.listenerHolder.Down()
  56. } else {
  57. newError("Called UnixInboundHandler.Close while listenerHolder is nil").AtDebug().WriteToLog()
  58. }
  59. }
  60. func (uih *UnixInboundHandler) Tag() string {
  61. return uih.tag
  62. }
  63. func (uih *UnixInboundHandler) GetRandomInboundProxy() (interface{}, net.Port, int) {
  64. //It makes bo sense to support it
  65. return nil, 0, 0
  66. }
  67. func NewUnixInboundHandler(ctx context.Context, tag string, receiverConfig *proxyman.UnixReceiverConfig, proxyConfig interface{}) (*UnixInboundHandler, error) {
  68. rawProxy, err := common.CreateObject(ctx, proxyConfig)
  69. if err != nil {
  70. return nil, err
  71. }
  72. p, ok := rawProxy.(proxy.Inbound)
  73. if !ok {
  74. return nil, newError("not an inbound proxy.")
  75. }
  76. h := &UnixInboundHandler{
  77. proxy: p,
  78. mux: mux.NewServer(ctx),
  79. tag: tag,
  80. ctx: ctx,
  81. path: receiverConfig.DomainSockSettings.GetPath(),
  82. }
  83. return h, nil
  84. }