server.go 6.7 KB

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