server.go 6.8 KB

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