server.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  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. 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. port: inbound.Gateway.Port,
  84. }
  85. reader := &buf.BufferedReader{Reader: buf.NewReader(conn)}
  86. request, err := svrSession.Handshake(reader, conn)
  87. if err != nil {
  88. if inbound != nil && inbound.Source.IsValid() {
  89. log.Record(&log.AccessMessage{
  90. From: inbound.Source,
  91. To: "",
  92. Status: log.AccessRejected,
  93. Reason: err,
  94. })
  95. }
  96. return newError("failed to read request").Base(err)
  97. }
  98. if request.User != nil {
  99. inbound.User.Email = request.User.Email
  100. }
  101. if err := conn.SetReadDeadline(time.Time{}); err != nil {
  102. newError("failed to clear deadline").Base(err).WriteToLog(session.ExportIDToError(ctx))
  103. }
  104. if request.Command == protocol.RequestCommandTCP {
  105. dest := request.Destination()
  106. newError("TCP Connect request to ", dest).WriteToLog(session.ExportIDToError(ctx))
  107. if inbound != nil && inbound.Source.IsValid() {
  108. ctx = log.ContextWithAccessMessage(ctx, &log.AccessMessage{
  109. From: inbound.Source,
  110. To: dest,
  111. Status: log.AccessAccepted,
  112. Reason: "",
  113. })
  114. }
  115. return s.transport(ctx, reader, conn, dest, dispatcher)
  116. }
  117. if request.Command == protocol.RequestCommandUDP {
  118. return s.handleUDP(conn)
  119. }
  120. return nil
  121. }
  122. func (*Server) handleUDP(c io.Reader) error {
  123. // The TCP connection closes after this method returns. We need to wait until
  124. // the client closes it.
  125. return common.Error2(io.Copy(buf.DiscardBytes, c))
  126. }
  127. func (s *Server) transport(ctx context.Context, reader io.Reader, writer io.Writer, dest net.Destination, dispatcher routing.Dispatcher) error {
  128. ctx, cancel := context.WithCancel(ctx)
  129. timer := signal.CancelAfterInactivity(ctx, cancel, s.policy().Timeouts.ConnectionIdle)
  130. plcy := s.policy()
  131. ctx = policy.ContextWithBufferPolicy(ctx, plcy.Buffer)
  132. link, err := dispatcher.Dispatch(ctx, dest)
  133. if err != nil {
  134. return err
  135. }
  136. requestDone := func() error {
  137. defer timer.SetTimeout(plcy.Timeouts.DownlinkOnly)
  138. if err := buf.Copy(buf.NewReader(reader), link.Writer, buf.UpdateActivity(timer)); err != nil {
  139. return newError("failed to transport all TCP request").Base(err)
  140. }
  141. return nil
  142. }
  143. responseDone := func() error {
  144. defer timer.SetTimeout(plcy.Timeouts.UplinkOnly)
  145. v2writer := buf.NewWriter(writer)
  146. if err := buf.Copy(link.Reader, v2writer, buf.UpdateActivity(timer)); err != nil {
  147. return newError("failed to transport all TCP response").Base(err)
  148. }
  149. return nil
  150. }
  151. var requestDonePost = task.OnSuccess(requestDone, task.Close(link.Writer))
  152. if err := task.Run(ctx, requestDonePost, responseDone); err != nil {
  153. common.Interrupt(link.Reader)
  154. common.Interrupt(link.Writer)
  155. return newError("connection ends").Base(err)
  156. }
  157. return nil
  158. }
  159. func (s *Server) handleUDPPayload(ctx context.Context, conn internet.Connection, dispatcher routing.Dispatcher) error {
  160. udpServer := udp.NewDispatcher(dispatcher, func(ctx context.Context, packet *udp_proto.Packet) {
  161. payload := packet.Payload
  162. newError("writing back UDP response with ", payload.Len(), " bytes").AtDebug().WriteToLog(session.ExportIDToError(ctx))
  163. request := protocol.RequestHeaderFromContext(ctx)
  164. if request == nil {
  165. return
  166. }
  167. udpMessage, err := EncodeUDPPacket(request, payload.Bytes())
  168. payload.Release()
  169. defer udpMessage.Release()
  170. if err != nil {
  171. newError("failed to write UDP response").AtWarning().Base(err).WriteToLog(session.ExportIDToError(ctx))
  172. }
  173. conn.Write(udpMessage.Bytes()) // nolint: errcheck
  174. })
  175. if inbound := session.InboundFromContext(ctx); inbound != nil && inbound.Source.IsValid() {
  176. newError("client UDP connection from ", inbound.Source).WriteToLog(session.ExportIDToError(ctx))
  177. }
  178. reader := buf.NewPacketReader(conn)
  179. for {
  180. mpayload, err := reader.ReadMultiBuffer()
  181. if err != nil {
  182. return err
  183. }
  184. for _, payload := range mpayload {
  185. request, err := DecodeUDPPacket(payload)
  186. if err != nil {
  187. newError("failed to parse UDP request").Base(err).WriteToLog(session.ExportIDToError(ctx))
  188. payload.Release()
  189. continue
  190. }
  191. if payload.IsEmpty() {
  192. payload.Release()
  193. continue
  194. }
  195. newError("send packet to ", request.Destination(), " with ", payload.Len(), " bytes").AtDebug().WriteToLog(session.ExportIDToError(ctx))
  196. if inbound := session.InboundFromContext(ctx); inbound != nil && inbound.Source.IsValid() {
  197. ctx = log.ContextWithAccessMessage(ctx, &log.AccessMessage{
  198. From: inbound.Source,
  199. To: request.Destination(),
  200. Status: log.AccessAccepted,
  201. Reason: "",
  202. })
  203. }
  204. ctx = protocol.ContextWithRequestHeader(ctx, request)
  205. udpServer.Dispatch(ctx, request.Destination(), payload)
  206. }
  207. }
  208. }
  209. func init() {
  210. common.Must(common.RegisterConfig((*ServerConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  211. return NewServer(ctx, config.(*ServerConfig))
  212. }))
  213. }