socks.go 7.8 KB

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