socks.go 7.9 KB

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