server.go 8.3 KB

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