server.go 7.6 KB

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