server.go 7.5 KB

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