server.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. package socks
  2. import (
  3. "errors"
  4. "io"
  5. "sync"
  6. "time"
  7. "github.com/v2ray/v2ray-core/app"
  8. "github.com/v2ray/v2ray-core/app/dispatcher"
  9. v2io "github.com/v2ray/v2ray-core/common/io"
  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/internal"
  14. "github.com/v2ray/v2ray-core/proxy/socks/protocol"
  15. "github.com/v2ray/v2ray-core/transport/hub"
  16. )
  17. var (
  18. ErrorUnsupportedSocksCommand = errors.New("Unsupported socks command.")
  19. ErrorUnsupportedAuthMethod = errors.New("Unsupported auth method.")
  20. )
  21. // Server is a SOCKS 5 proxy server
  22. type Server struct {
  23. tcpMutex sync.RWMutex
  24. udpMutex sync.RWMutex
  25. accepting bool
  26. packetDispatcher dispatcher.PacketDispatcher
  27. config *Config
  28. tcpListener *hub.TCPHub
  29. udpHub *hub.UDPHub
  30. udpAddress v2net.Destination
  31. udpServer *hub.UDPServer
  32. listeningPort v2net.Port
  33. listeningAddress v2net.Address
  34. }
  35. // NewServer creates a new Server object.
  36. func NewServer(config *Config, packetDispatcher dispatcher.PacketDispatcher) *Server {
  37. return &Server{
  38. config: config,
  39. packetDispatcher: packetDispatcher,
  40. }
  41. }
  42. // Port implements InboundHandler.Port().
  43. func (this *Server) Port() v2net.Port {
  44. return this.listeningPort
  45. }
  46. // Close implements InboundHandler.Close().
  47. func (this *Server) Close() {
  48. this.accepting = false
  49. if this.tcpListener != nil {
  50. this.tcpMutex.Lock()
  51. this.tcpListener.Close()
  52. this.tcpListener = nil
  53. this.tcpMutex.Unlock()
  54. }
  55. if this.udpHub != nil {
  56. this.udpMutex.Lock()
  57. this.udpHub.Close()
  58. this.udpHub = nil
  59. this.udpMutex.Unlock()
  60. }
  61. }
  62. // Listen implements InboundHandler.Listen().
  63. func (this *Server) Listen(address v2net.Address, port v2net.Port) error {
  64. if this.accepting {
  65. if this.listeningPort == port && this.listeningAddress.Equals(address) {
  66. return nil
  67. } else {
  68. return proxy.ErrorAlreadyListening
  69. }
  70. }
  71. this.listeningPort = port
  72. this.listeningAddress = address
  73. listener, err := hub.ListenTCP(address, port, this.handleConnection, nil)
  74. if err != nil {
  75. log.Error("Socks: failed to listen on port ", port, ": ", err)
  76. return err
  77. }
  78. this.accepting = true
  79. this.tcpMutex.Lock()
  80. this.tcpListener = listener
  81. this.tcpMutex.Unlock()
  82. if this.config.UDPEnabled {
  83. this.listenUDP(address, port)
  84. }
  85. return nil
  86. }
  87. func (this *Server) handleConnection(connection *hub.Connection) {
  88. defer connection.Close()
  89. timedReader := v2net.NewTimeOutReader(120, connection)
  90. reader := v2io.NewBufferedReader(timedReader)
  91. defer reader.Release()
  92. writer := v2io.NewBufferedWriter(connection)
  93. defer writer.Release()
  94. auth, auth4, err := protocol.ReadAuthentication(reader)
  95. if err != nil && err != protocol.Socks4Downgrade {
  96. if err != io.EOF {
  97. log.Warning("Socks: failed to read authentication: ", err)
  98. }
  99. return
  100. }
  101. if err != nil && err == protocol.Socks4Downgrade {
  102. this.handleSocks4(reader, writer, auth4)
  103. } else {
  104. this.handleSocks5(reader, writer, auth)
  105. }
  106. }
  107. func (this *Server) handleSocks5(reader *v2io.BufferedReader, writer *v2io.BufferedWriter, auth protocol.Socks5AuthenticationRequest) error {
  108. expectedAuthMethod := protocol.AuthNotRequired
  109. if this.config.AuthType == AuthTypePassword {
  110. expectedAuthMethod = protocol.AuthUserPass
  111. }
  112. if !auth.HasAuthMethod(expectedAuthMethod) {
  113. authResponse := protocol.NewAuthenticationResponse(protocol.AuthNoMatchingMethod)
  114. err := protocol.WriteAuthentication(writer, authResponse)
  115. writer.Flush()
  116. if err != nil {
  117. log.Warning("Socks: failed to write authentication: ", err)
  118. return err
  119. }
  120. log.Warning("Socks: client doesn't support any allowed auth methods.")
  121. return ErrorUnsupportedAuthMethod
  122. }
  123. authResponse := protocol.NewAuthenticationResponse(expectedAuthMethod)
  124. protocol.WriteAuthentication(writer, authResponse)
  125. err := writer.Flush()
  126. if err != nil {
  127. log.Error("Socks: failed to write authentication: ", err)
  128. return err
  129. }
  130. if this.config.AuthType == AuthTypePassword {
  131. upRequest, err := protocol.ReadUserPassRequest(reader)
  132. if err != nil {
  133. log.Warning("Socks: failed to read username and password: ", err)
  134. return err
  135. }
  136. status := byte(0)
  137. if !this.config.HasAccount(upRequest.Username(), upRequest.Password()) {
  138. status = byte(0xFF)
  139. }
  140. upResponse := protocol.NewSocks5UserPassResponse(status)
  141. err = protocol.WriteUserPassResponse(writer, upResponse)
  142. writer.Flush()
  143. if err != nil {
  144. log.Error("Socks: failed to write user pass response: ", err)
  145. return err
  146. }
  147. if status != byte(0) {
  148. log.Warning("Socks: Invalid user account: ", upRequest.AuthDetail())
  149. return proxy.ErrorInvalidAuthentication
  150. }
  151. }
  152. request, err := protocol.ReadRequest(reader)
  153. if err != nil {
  154. log.Warning("Socks: failed to read request: ", err)
  155. return err
  156. }
  157. if request.Command == protocol.CmdUdpAssociate && this.config.UDPEnabled {
  158. return this.handleUDP(reader, writer)
  159. }
  160. if request.Command == protocol.CmdBind || request.Command == protocol.CmdUdpAssociate {
  161. response := protocol.NewSocks5Response()
  162. response.Error = protocol.ErrorCommandNotSupported
  163. response.Port = v2net.Port(0)
  164. response.SetIPv4([]byte{0, 0, 0, 0})
  165. response.Write(writer)
  166. writer.Flush()
  167. if err != nil {
  168. log.Error("Socks: failed to write response: ", err)
  169. return err
  170. }
  171. log.Warning("Socks: Unsupported socks command ", request.Command)
  172. return ErrorUnsupportedSocksCommand
  173. }
  174. response := protocol.NewSocks5Response()
  175. response.Error = protocol.ErrorSuccess
  176. // Some SOCKS software requires a value other than dest. Let's fake one:
  177. response.Port = v2net.Port(1717)
  178. response.SetIPv4([]byte{0, 0, 0, 0})
  179. response.Write(writer)
  180. if err != nil {
  181. log.Error("Socks: failed to write response: ", err)
  182. return err
  183. }
  184. reader.SetCached(false)
  185. writer.SetCached(false)
  186. dest := request.Destination()
  187. log.Info("Socks: TCP Connect request to ", dest)
  188. this.transport(reader, writer, dest)
  189. return nil
  190. }
  191. func (this *Server) handleUDP(reader io.Reader, writer *v2io.BufferedWriter) 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. response.Write(writer)
  205. err := writer.Flush()
  206. if err != nil {
  207. log.Error("Socks: failed to write response: ", err)
  208. return err
  209. }
  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 *Server) handleSocks4(reader *v2io.BufferedReader, writer *v2io.BufferedWriter, 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. socks4Response.Write(writer)
  223. if result == protocol.Socks4RequestRejected {
  224. log.Warning("Socks: Unsupported socks 4 command ", auth.Command)
  225. return ErrorUnsupportedSocksCommand
  226. }
  227. reader.SetCached(false)
  228. writer.SetCached(false)
  229. dest := v2net.TCPDestination(v2net.IPAddress(auth.IP[:]), auth.Port)
  230. this.transport(reader, writer, dest)
  231. return nil
  232. }
  233. func (this *Server) transport(reader io.Reader, writer io.Writer, destination v2net.Destination) {
  234. ray := this.packetDispatcher.DispatchToOutbound(destination)
  235. input := ray.InboundInput()
  236. output := ray.InboundOutput()
  237. var inputFinish, outputFinish sync.Mutex
  238. inputFinish.Lock()
  239. outputFinish.Lock()
  240. go func() {
  241. v2reader := v2io.NewAdaptiveReader(reader)
  242. defer v2reader.Release()
  243. v2io.Pipe(v2reader, input)
  244. inputFinish.Unlock()
  245. input.Close()
  246. }()
  247. go func() {
  248. v2writer := v2io.NewAdaptiveWriter(writer)
  249. defer v2writer.Release()
  250. v2io.Pipe(output, v2writer)
  251. outputFinish.Unlock()
  252. output.Release()
  253. }()
  254. outputFinish.Lock()
  255. }
  256. func init() {
  257. internal.MustRegisterInboundHandlerCreator("socks",
  258. func(space app.Space, rawConfig interface{}) (proxy.InboundHandler, error) {
  259. if !space.HasApp(dispatcher.APP_ID) {
  260. return nil, internal.ErrorBadConfiguration
  261. }
  262. return NewServer(
  263. rawConfig.(*Config),
  264. space.GetApp(dispatcher.APP_ID).(dispatcher.PacketDispatcher)), nil
  265. })
  266. }