socks.go 7.8 KB

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