server.go 6.6 KB

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