server.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. package socks
  2. import (
  3. "context"
  4. "io"
  5. "time"
  6. "v2ray.com/core"
  7. "v2ray.com/core/common"
  8. "v2ray.com/core/common/buf"
  9. "v2ray.com/core/common/log"
  10. "v2ray.com/core/common/net"
  11. "v2ray.com/core/common/protocol"
  12. "v2ray.com/core/common/signal"
  13. "v2ray.com/core/proxy"
  14. "v2ray.com/core/transport/internet"
  15. "v2ray.com/core/transport/internet/udp"
  16. "v2ray.com/core/transport/pipe"
  17. )
  18. // Server is a SOCKS 5 proxy server
  19. type Server struct {
  20. config *ServerConfig
  21. v *core.Instance
  22. }
  23. // NewServer creates a new Server object.
  24. func NewServer(ctx context.Context, config *ServerConfig) (*Server, error) {
  25. s := &Server{
  26. config: config,
  27. v: core.MustFromContext(ctx),
  28. }
  29. return s, nil
  30. }
  31. func (s *Server) policy() core.Policy {
  32. config := s.config
  33. p := s.v.PolicyManager().ForLevel(config.UserLevel)
  34. if config.Timeout > 0 && config.UserLevel == 0 {
  35. p.Timeouts.ConnectionIdle = time.Duration(config.Timeout) * time.Second
  36. }
  37. return p
  38. }
  39. // Network implements proxy.Inbound.
  40. func (s *Server) Network() net.NetworkList {
  41. list := net.NetworkList{
  42. Network: []net.Network{net.Network_TCP},
  43. }
  44. if s.config.UdpEnabled {
  45. list.Network = append(list.Network, net.Network_UDP)
  46. }
  47. return list
  48. }
  49. // Process implements proxy.Inbound.
  50. func (s *Server) Process(ctx context.Context, network net.Network, conn internet.Connection, dispatcher core.Dispatcher) error {
  51. switch network {
  52. case net.Network_TCP:
  53. return s.processTCP(ctx, conn, dispatcher)
  54. case net.Network_UDP:
  55. return s.handleUDPPayload(ctx, conn, dispatcher)
  56. default:
  57. return newError("unknown network: ", network)
  58. }
  59. }
  60. func (s *Server) processTCP(ctx context.Context, conn internet.Connection, dispatcher core.Dispatcher) error {
  61. if err := conn.SetReadDeadline(time.Now().Add(s.policy().Timeouts.Handshake)); err != nil {
  62. newError("failed to set deadline").Base(err).WithContext(ctx).WriteToLog()
  63. }
  64. reader := &buf.BufferedReader{Reader: buf.NewReader(conn)}
  65. inboundDest, ok := proxy.InboundEntryPointFromContext(ctx)
  66. if !ok {
  67. return newError("inbound entry point not specified")
  68. }
  69. session := &ServerSession{
  70. config: s.config,
  71. port: inboundDest.Port,
  72. }
  73. request, err := session.Handshake(reader, conn)
  74. if err != nil {
  75. if source, ok := proxy.SourceFromContext(ctx); ok {
  76. log.Record(&log.AccessMessage{
  77. From: source,
  78. To: "",
  79. Status: log.AccessRejected,
  80. Reason: err,
  81. })
  82. }
  83. return newError("failed to read request").Base(err)
  84. }
  85. if err := conn.SetReadDeadline(time.Time{}); err != nil {
  86. newError("failed to clear deadline").Base(err).WithContext(ctx).WriteToLog()
  87. }
  88. if request.Command == protocol.RequestCommandTCP {
  89. dest := request.Destination()
  90. newError("TCP Connect request to ", dest).WithContext(ctx).WriteToLog()
  91. if source, ok := proxy.SourceFromContext(ctx); ok {
  92. log.Record(&log.AccessMessage{
  93. From: source,
  94. To: dest,
  95. Status: log.AccessAccepted,
  96. Reason: "",
  97. })
  98. }
  99. return s.transport(ctx, reader, conn, dest, dispatcher)
  100. }
  101. if request.Command == protocol.RequestCommandUDP {
  102. return s.handleUDP(conn)
  103. }
  104. return nil
  105. }
  106. func (*Server) handleUDP(c io.Reader) error {
  107. // The TCP connection closes after this method returns. We need to wait until
  108. // the client closes it.
  109. return common.Error2(io.Copy(buf.DiscardBytes, c))
  110. }
  111. func (s *Server) transport(ctx context.Context, reader io.Reader, writer io.Writer, dest net.Destination, dispatcher core.Dispatcher) error {
  112. ctx, cancel := context.WithCancel(ctx)
  113. timer := signal.CancelAfterInactivity(ctx, cancel, s.policy().Timeouts.ConnectionIdle)
  114. plcy := s.policy()
  115. ctx = core.ContextWithBufferPolicy(ctx, plcy.Buffer)
  116. link, err := dispatcher.Dispatch(ctx, dest)
  117. if err != nil {
  118. return err
  119. }
  120. requestDone := func() error {
  121. defer timer.SetTimeout(plcy.Timeouts.DownlinkOnly)
  122. defer common.Close(link.Writer)
  123. v2reader := buf.NewReader(reader)
  124. if err := buf.Copy(v2reader, link.Writer, buf.UpdateActivity(timer)); err != nil {
  125. return newError("failed to transport all TCP request").Base(err)
  126. }
  127. return nil
  128. }
  129. responseDone := func() error {
  130. defer timer.SetTimeout(plcy.Timeouts.UplinkOnly)
  131. v2writer := buf.NewWriter(writer)
  132. if err := buf.Copy(link.Reader, v2writer, buf.UpdateActivity(timer)); err != nil {
  133. return newError("failed to transport all TCP response").Base(err)
  134. }
  135. return nil
  136. }
  137. if err := signal.ExecuteParallel(ctx, requestDone, responseDone); err != nil {
  138. pipe.CloseError(link.Reader)
  139. pipe.CloseError(link.Writer)
  140. return newError("connection ends").Base(err)
  141. }
  142. return nil
  143. }
  144. func (s *Server) handleUDPPayload(ctx context.Context, conn internet.Connection, dispatcher core.Dispatcher) error {
  145. udpServer := udp.NewDispatcher(dispatcher)
  146. if source, ok := proxy.SourceFromContext(ctx); ok {
  147. newError("client UDP connection from ", source).WithContext(ctx).WriteToLog()
  148. }
  149. reader := buf.NewReader(conn)
  150. for {
  151. mpayload, err := reader.ReadMultiBuffer()
  152. if err != nil {
  153. return err
  154. }
  155. for _, payload := range mpayload {
  156. request, err := DecodeUDPPacket(payload)
  157. if err != nil {
  158. newError("failed to parse UDP request").Base(err).WithContext(ctx).WriteToLog()
  159. payload.Release()
  160. continue
  161. }
  162. if payload.IsEmpty() {
  163. payload.Release()
  164. continue
  165. }
  166. newError("send packet to ", request.Destination(), " with ", payload.Len(), " bytes").AtDebug().WithContext(ctx).WriteToLog()
  167. if source, ok := proxy.SourceFromContext(ctx); ok {
  168. log.Record(&log.AccessMessage{
  169. From: source,
  170. To: request.Destination(),
  171. Status: log.AccessAccepted,
  172. Reason: "",
  173. })
  174. }
  175. udpServer.Dispatch(ctx, request.Destination(), payload, func(payload *buf.Buffer) {
  176. newError("writing back UDP response with ", payload.Len(), " bytes").AtDebug().WithContext(ctx).WriteToLog()
  177. udpMessage, err := EncodeUDPPacket(request, payload.Bytes())
  178. payload.Release()
  179. defer udpMessage.Release()
  180. if err != nil {
  181. newError("failed to write UDP response").AtWarning().Base(err).WithContext(ctx).WriteToLog()
  182. }
  183. conn.Write(udpMessage.Bytes())
  184. })
  185. }
  186. }
  187. }
  188. func init() {
  189. common.Must(common.RegisterConfig((*ServerConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  190. return NewServer(ctx, config.(*ServerConfig))
  191. }))
  192. }