server.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. package socks
  2. import (
  3. "errors"
  4. "io"
  5. "sync"
  6. "time"
  7. "v2ray.com/core/app"
  8. "v2ray.com/core/app/dispatcher"
  9. v2io "v2ray.com/core/common/io"
  10. "v2ray.com/core/common/log"
  11. v2net "v2ray.com/core/common/net"
  12. "v2ray.com/core/proxy"
  13. "v2ray.com/core/proxy/registry"
  14. "v2ray.com/core/proxy/socks/protocol"
  15. "v2ray.com/core/transport/internet"
  16. "v2ray.com/core/transport/internet/udp"
  17. )
  18. var (
  19. ErrUnsupportedSocksCommand = errors.New("Unsupported socks command.")
  20. ErrUnsupportedAuthMethod = errors.New("Unsupported auth method.")
  21. )
  22. // Server is a SOCKS 5 proxy server
  23. type Server struct {
  24. tcpMutex sync.RWMutex
  25. udpMutex sync.RWMutex
  26. accepting bool
  27. packetDispatcher dispatcher.PacketDispatcher
  28. config *Config
  29. tcpListener *internet.TCPHub
  30. udpHub *udp.UDPHub
  31. udpAddress v2net.Destination
  32. udpServer *udp.UDPServer
  33. meta *proxy.InboundHandlerMeta
  34. }
  35. // NewServer creates a new Server object.
  36. func NewServer(config *Config, space app.Space, meta *proxy.InboundHandlerMeta) *Server {
  37. s := &Server{
  38. config: config,
  39. meta: meta,
  40. }
  41. space.InitializeApplication(func() error {
  42. if !space.HasApp(dispatcher.APP_ID) {
  43. log.Error("Socks|Server: Dispatcher is not found in the space.")
  44. return app.ErrMissingApplication
  45. }
  46. s.packetDispatcher = space.GetApp(dispatcher.APP_ID).(dispatcher.PacketDispatcher)
  47. return nil
  48. })
  49. return s
  50. }
  51. // Port implements InboundHandler.Port().
  52. func (this *Server) Port() v2net.Port {
  53. return this.meta.Port
  54. }
  55. // Close implements InboundHandler.Close().
  56. func (this *Server) Close() {
  57. this.accepting = false
  58. if this.tcpListener != nil {
  59. this.tcpMutex.Lock()
  60. this.tcpListener.Close()
  61. this.tcpListener = nil
  62. this.tcpMutex.Unlock()
  63. }
  64. if this.udpHub != nil {
  65. this.udpMutex.Lock()
  66. this.udpHub.Close()
  67. this.udpHub = nil
  68. this.udpMutex.Unlock()
  69. }
  70. }
  71. // Listen implements InboundHandler.Listen().
  72. func (this *Server) Start() error {
  73. if this.accepting {
  74. return nil
  75. }
  76. listener, err := internet.ListenTCP(
  77. this.meta.Address,
  78. this.meta.Port,
  79. this.handleConnection,
  80. this.meta.StreamSettings)
  81. if err != nil {
  82. log.Error("Socks: failed to listen on ", this.meta.Address, ":", this.meta.Port, ": ", err)
  83. return err
  84. }
  85. this.accepting = true
  86. this.tcpMutex.Lock()
  87. this.tcpListener = listener
  88. this.tcpMutex.Unlock()
  89. if this.config.UDPEnabled {
  90. this.listenUDP()
  91. }
  92. return nil
  93. }
  94. func (this *Server) handleConnection(connection internet.Connection) {
  95. defer connection.Close()
  96. timedReader := v2net.NewTimeOutReader(this.config.Timeout, connection)
  97. reader := v2io.NewBufferedReader(timedReader)
  98. defer reader.Release()
  99. writer := v2io.NewBufferedWriter(connection)
  100. defer writer.Release()
  101. auth, auth4, err := protocol.ReadAuthentication(reader)
  102. if err != nil && err != protocol.Socks4Downgrade {
  103. if err != io.EOF {
  104. log.Warning("Socks: failed to read authentication: ", err)
  105. }
  106. return
  107. }
  108. clientAddr := v2net.DestinationFromAddr(connection.RemoteAddr())
  109. if err != nil && err == protocol.Socks4Downgrade {
  110. this.handleSocks4(clientAddr, reader, writer, auth4)
  111. } else {
  112. this.handleSocks5(clientAddr, reader, writer, auth)
  113. }
  114. }
  115. func (this *Server) handleSocks5(clientAddr v2net.Destination, reader *v2io.BufferedReader, writer *v2io.BufferedWriter, auth protocol.Socks5AuthenticationRequest) error {
  116. expectedAuthMethod := protocol.AuthNotRequired
  117. if this.config.AuthType == AuthTypePassword {
  118. expectedAuthMethod = protocol.AuthUserPass
  119. }
  120. if !auth.HasAuthMethod(expectedAuthMethod) {
  121. authResponse := protocol.NewAuthenticationResponse(protocol.AuthNoMatchingMethod)
  122. err := protocol.WriteAuthentication(writer, authResponse)
  123. writer.Flush()
  124. if err != nil {
  125. log.Warning("Socks: failed to write authentication: ", err)
  126. return err
  127. }
  128. log.Warning("Socks: client doesn't support any allowed auth methods.")
  129. return ErrUnsupportedAuthMethod
  130. }
  131. authResponse := protocol.NewAuthenticationResponse(expectedAuthMethod)
  132. protocol.WriteAuthentication(writer, authResponse)
  133. err := writer.Flush()
  134. if err != nil {
  135. log.Error("Socks: failed to write authentication: ", err)
  136. return err
  137. }
  138. if this.config.AuthType == AuthTypePassword {
  139. upRequest, err := protocol.ReadUserPassRequest(reader)
  140. if err != nil {
  141. log.Warning("Socks: failed to read username and password: ", err)
  142. return err
  143. }
  144. status := byte(0)
  145. if !this.config.HasAccount(upRequest.Username(), upRequest.Password()) {
  146. status = byte(0xFF)
  147. }
  148. upResponse := protocol.NewSocks5UserPassResponse(status)
  149. err = protocol.WriteUserPassResponse(writer, upResponse)
  150. writer.Flush()
  151. if err != nil {
  152. log.Error("Socks: failed to write user pass response: ", err)
  153. return err
  154. }
  155. if status != byte(0) {
  156. log.Warning("Socks: Invalid user account: ", upRequest.AuthDetail())
  157. log.Access(clientAddr, "", log.AccessRejected, proxy.ErrInvalidAuthentication)
  158. return proxy.ErrInvalidAuthentication
  159. }
  160. }
  161. request, err := protocol.ReadRequest(reader)
  162. if err != nil {
  163. log.Warning("Socks: failed to read request: ", err)
  164. return err
  165. }
  166. if request.Command == protocol.CmdUdpAssociate && this.config.UDPEnabled {
  167. return this.handleUDP(reader, writer)
  168. }
  169. if request.Command == protocol.CmdBind || request.Command == protocol.CmdUdpAssociate {
  170. response := protocol.NewSocks5Response()
  171. response.Error = protocol.ErrorCommandNotSupported
  172. response.Port = v2net.Port(0)
  173. response.SetIPv4([]byte{0, 0, 0, 0})
  174. response.Write(writer)
  175. writer.Flush()
  176. if err != nil {
  177. log.Error("Socks: failed to write response: ", err)
  178. return err
  179. }
  180. log.Warning("Socks: Unsupported socks command ", request.Command)
  181. return ErrUnsupportedSocksCommand
  182. }
  183. response := protocol.NewSocks5Response()
  184. response.Error = protocol.ErrorSuccess
  185. // Some SOCKS software requires a value other than dest. Let's fake one:
  186. response.Port = v2net.Port(1717)
  187. response.SetIPv4([]byte{0, 0, 0, 0})
  188. response.Write(writer)
  189. if err != nil {
  190. log.Error("Socks: failed to write response: ", err)
  191. return err
  192. }
  193. reader.SetCached(false)
  194. writer.SetCached(false)
  195. dest := request.Destination()
  196. session := &proxy.SessionInfo{
  197. Source: clientAddr,
  198. Destination: dest,
  199. }
  200. log.Info("Socks: TCP Connect request to ", dest)
  201. log.Access(clientAddr, dest, log.AccessAccepted, "")
  202. this.transport(reader, writer, session)
  203. return nil
  204. }
  205. func (this *Server) handleUDP(reader io.Reader, writer *v2io.BufferedWriter) error {
  206. response := protocol.NewSocks5Response()
  207. response.Error = protocol.ErrorSuccess
  208. udpAddr := this.udpAddress
  209. response.Port = udpAddr.Port()
  210. switch udpAddr.Address().Family() {
  211. case v2net.AddressFamilyIPv4:
  212. response.SetIPv4(udpAddr.Address().IP())
  213. case v2net.AddressFamilyIPv6:
  214. response.SetIPv6(udpAddr.Address().IP())
  215. case v2net.AddressFamilyDomain:
  216. response.SetDomain(udpAddr.Address().Domain())
  217. }
  218. response.Write(writer)
  219. err := writer.Flush()
  220. if err != nil {
  221. log.Error("Socks: failed to write response: ", err)
  222. return err
  223. }
  224. // The TCP connection closes after this method returns. We need to wait until
  225. // the client closes it.
  226. // TODO: get notified from UDP part
  227. <-time.After(5 * time.Minute)
  228. return nil
  229. }
  230. func (this *Server) handleSocks4(clientAddr v2net.Destination, reader *v2io.BufferedReader, writer *v2io.BufferedWriter, auth protocol.Socks4AuthenticationRequest) error {
  231. result := protocol.Socks4RequestGranted
  232. if auth.Command == protocol.CmdBind {
  233. result = protocol.Socks4RequestRejected
  234. }
  235. socks4Response := protocol.NewSocks4AuthenticationResponse(result, auth.Port, auth.IP[:])
  236. socks4Response.Write(writer)
  237. if result == protocol.Socks4RequestRejected {
  238. log.Warning("Socks: Unsupported socks 4 command ", auth.Command)
  239. log.Access(clientAddr, "", log.AccessRejected, ErrUnsupportedSocksCommand)
  240. return ErrUnsupportedSocksCommand
  241. }
  242. reader.SetCached(false)
  243. writer.SetCached(false)
  244. dest := v2net.TCPDestination(v2net.IPAddress(auth.IP[:]), auth.Port)
  245. session := &proxy.SessionInfo{
  246. Source: clientAddr,
  247. Destination: dest,
  248. }
  249. log.Access(clientAddr, dest, log.AccessAccepted, "")
  250. this.transport(reader, writer, session)
  251. return nil
  252. }
  253. func (this *Server) transport(reader io.Reader, writer io.Writer, session *proxy.SessionInfo) {
  254. ray := this.packetDispatcher.DispatchToOutbound(this.meta, session)
  255. input := ray.InboundInput()
  256. output := ray.InboundOutput()
  257. defer input.Close()
  258. defer output.Release()
  259. go func() {
  260. v2reader := v2io.NewAdaptiveReader(reader)
  261. defer v2reader.Release()
  262. v2io.Pipe(v2reader, input)
  263. }()
  264. v2writer := v2io.NewAdaptiveWriter(writer)
  265. defer v2writer.Release()
  266. v2io.Pipe(output, v2writer)
  267. output.Release()
  268. }
  269. type ServerFactory struct{}
  270. func (this *ServerFactory) StreamCapability() internet.StreamConnectionType {
  271. return internet.StreamConnectionTypeRawTCP
  272. }
  273. func (this *ServerFactory) Create(space app.Space, rawConfig interface{}, meta *proxy.InboundHandlerMeta) (proxy.InboundHandler, error) {
  274. return NewServer(rawConfig.(*Config), space, meta), nil
  275. }
  276. func init() {
  277. registry.MustRegisterInboundHandlerCreator("socks", new(ServerFactory))
  278. }