server.go 6.9 KB

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