socks.go 8.2 KB

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