server.go 6.8 KB

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