socks.go 7.7 KB

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