server.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  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. }
  34. // NewServer creates a new Server object.
  35. func NewServer(config *Config, packetDispatcher dispatcher.PacketDispatcher) *Server {
  36. return &Server{
  37. config: config,
  38. packetDispatcher: packetDispatcher,
  39. }
  40. }
  41. // Port implements InboundHandler.Port().
  42. func (this *Server) Port() v2net.Port {
  43. return this.listeningPort
  44. }
  45. // Close implements InboundHandler.Close().
  46. func (this *Server) Close() {
  47. this.accepting = false
  48. if this.tcpListener != nil {
  49. this.tcpMutex.Lock()
  50. this.tcpListener.Close()
  51. this.tcpListener = nil
  52. this.tcpMutex.Unlock()
  53. }
  54. if this.udpHub != nil {
  55. this.udpMutex.Lock()
  56. this.udpHub.Close()
  57. this.udpHub = nil
  58. this.udpMutex.Unlock()
  59. }
  60. }
  61. // Listen implements InboundHandler.Listen().
  62. func (this *Server) Listen(port v2net.Port) error {
  63. if this.accepting {
  64. if this.listeningPort == port {
  65. return nil
  66. } else {
  67. return proxy.ErrorAlreadyListening
  68. }
  69. }
  70. this.listeningPort = port
  71. listener, err := hub.ListenTCP(port, this.handleConnection, nil)
  72. if err != nil {
  73. log.Error("Socks: failed to listen on port ", port, ": ", err)
  74. return err
  75. }
  76. this.accepting = true
  77. this.tcpMutex.Lock()
  78. this.tcpListener = listener
  79. this.tcpMutex.Unlock()
  80. if this.config.UDPEnabled {
  81. this.listenUDP(port)
  82. }
  83. return nil
  84. }
  85. func (this *Server) handleConnection(connection *hub.Connection) {
  86. defer connection.Close()
  87. timedReader := v2net.NewTimeOutReader(120, connection)
  88. reader := v2io.NewBufferedReader(timedReader)
  89. defer reader.Release()
  90. writer := v2io.NewBufferedWriter(connection)
  91. defer writer.Release()
  92. auth, auth4, err := protocol.ReadAuthentication(reader)
  93. if err != nil && err != protocol.Socks4Downgrade {
  94. log.Error("Socks: failed to read authentication: ", err)
  95. return
  96. }
  97. if err != nil && err == protocol.Socks4Downgrade {
  98. this.handleSocks4(reader, writer, auth4)
  99. } else {
  100. this.handleSocks5(reader, writer, auth)
  101. }
  102. }
  103. func (this *Server) handleSocks5(reader *v2io.BufferedReader, writer *v2io.BufferedWriter, auth protocol.Socks5AuthenticationRequest) error {
  104. expectedAuthMethod := protocol.AuthNotRequired
  105. if this.config.AuthType == AuthTypePassword {
  106. expectedAuthMethod = protocol.AuthUserPass
  107. }
  108. if !auth.HasAuthMethod(expectedAuthMethod) {
  109. authResponse := protocol.NewAuthenticationResponse(protocol.AuthNoMatchingMethod)
  110. err := protocol.WriteAuthentication(writer, authResponse)
  111. writer.Flush()
  112. if err != nil {
  113. log.Error("Socks: failed to write authentication: ", err)
  114. return err
  115. }
  116. log.Warning("Socks: client doesn't support any allowed auth methods.")
  117. return ErrorUnsupportedAuthMethod
  118. }
  119. authResponse := protocol.NewAuthenticationResponse(expectedAuthMethod)
  120. err := protocol.WriteAuthentication(writer, authResponse)
  121. writer.Flush()
  122. if err != nil {
  123. log.Error("Socks: failed to write authentication: ", err)
  124. return err
  125. }
  126. if this.config.AuthType == AuthTypePassword {
  127. upRequest, err := protocol.ReadUserPassRequest(reader)
  128. if err != nil {
  129. log.Error("Socks: failed to read username and password: ", 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. writer.Flush()
  139. if err != nil {
  140. log.Error("Socks: failed to write user pass response: ", err)
  141. return err
  142. }
  143. if status != byte(0) {
  144. log.Warning("Socks: Invalid user account: ", upRequest.AuthDetail())
  145. return proxy.ErrorInvalidAuthentication
  146. }
  147. }
  148. request, err := protocol.ReadRequest(reader)
  149. if err != nil {
  150. log.Error("Socks: failed to read request: ", 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. response.Write(writer)
  162. writer.Flush()
  163. if err != nil {
  164. log.Error("Socks: failed to write response: ", err)
  165. return err
  166. }
  167. log.Warning("Socks: Unsupported socks command ", request.Command)
  168. return ErrorUnsupportedSocksCommand
  169. }
  170. response := protocol.NewSocks5Response()
  171. response.Error = protocol.ErrorSuccess
  172. // Some SOCKS software requires a value other than dest. Let's fake one:
  173. response.Port = v2net.Port(1717)
  174. response.SetIPv4([]byte{0, 0, 0, 0})
  175. response.Write(writer)
  176. if err != nil {
  177. log.Error("Socks: failed to write response: ", err)
  178. return err
  179. }
  180. reader.SetCached(false)
  181. writer.SetCached(false)
  182. dest := request.Destination()
  183. log.Info("Socks: TCP Connect request to ", dest)
  184. this.transport(reader, writer, dest)
  185. return nil
  186. }
  187. func (this *Server) handleUDP(reader io.Reader, writer *v2io.BufferedWriter) 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. response.Write(writer)
  201. err := writer.Flush()
  202. if err != nil {
  203. log.Error("Socks: failed to write response: ", err)
  204. return err
  205. }
  206. // The TCP connection closes after this method returns. We need to wait until
  207. // the client closes it.
  208. // TODO: get notified from UDP part
  209. <-time.After(5 * time.Minute)
  210. return nil
  211. }
  212. func (this *Server) handleSocks4(reader *v2io.BufferedReader, writer *v2io.BufferedWriter, auth protocol.Socks4AuthenticationRequest) error {
  213. result := protocol.Socks4RequestGranted
  214. if auth.Command == protocol.CmdBind {
  215. result = protocol.Socks4RequestRejected
  216. }
  217. socks4Response := protocol.NewSocks4AuthenticationResponse(result, auth.Port, auth.IP[:])
  218. socks4Response.Write(writer)
  219. if result == protocol.Socks4RequestRejected {
  220. log.Warning("Socks: Unsupported socks 4 command ", auth.Command)
  221. return ErrorUnsupportedSocksCommand
  222. }
  223. reader.SetCached(false)
  224. writer.SetCached(false)
  225. dest := v2net.TCPDestination(v2net.IPAddress(auth.IP[:]), auth.Port)
  226. this.transport(reader, writer, dest)
  227. return nil
  228. }
  229. func (this *Server) transport(reader io.Reader, writer io.Writer, destination v2net.Destination) {
  230. ray := this.packetDispatcher.DispatchToOutbound(destination)
  231. input := ray.InboundInput()
  232. output := ray.InboundOutput()
  233. var inputFinish, outputFinish sync.Mutex
  234. inputFinish.Lock()
  235. outputFinish.Lock()
  236. go func() {
  237. v2reader := v2io.NewAdaptiveReader(reader)
  238. defer v2reader.Release()
  239. v2io.Pipe(v2reader, input)
  240. inputFinish.Unlock()
  241. input.Close()
  242. }()
  243. go func() {
  244. v2writer := v2io.NewAdaptiveWriter(writer)
  245. defer v2writer.Release()
  246. v2io.Pipe(output, v2writer)
  247. outputFinish.Unlock()
  248. output.Release()
  249. }()
  250. outputFinish.Lock()
  251. }
  252. func init() {
  253. internal.MustRegisterInboundHandlerCreator("socks",
  254. func(space app.Space, rawConfig interface{}) (proxy.InboundHandler, error) {
  255. if !space.HasApp(dispatcher.APP_ID) {
  256. return nil, internal.ErrorBadConfiguration
  257. }
  258. return NewServer(
  259. rawConfig.(*Config),
  260. space.GetApp(dispatcher.APP_ID).(dispatcher.PacketDispatcher)), nil
  261. })
  262. }