socks.go 7.9 KB

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