server.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  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. meta *proxy.InboundHandlerMeta
  33. }
  34. // NewServer creates a new Server object.
  35. func NewServer(config *Config, packetDispatcher dispatcher.PacketDispatcher, meta *proxy.InboundHandlerMeta) *Server {
  36. return &Server{
  37. config: config,
  38. packetDispatcher: packetDispatcher,
  39. meta: meta,
  40. }
  41. }
  42. // Port implements InboundHandler.Port().
  43. func (this *Server) Port() v2net.Port {
  44. return this.meta.Port
  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) Start() error {
  64. if this.accepting {
  65. return nil
  66. }
  67. listener, err := hub.ListenTCP(
  68. this.meta.Address,
  69. this.meta.Port,
  70. this.handleConnection,
  71. nil)
  72. if err != nil {
  73. log.Error("Socks: failed to listen on ", this.meta.Address, ":", this.meta.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()
  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. if err != io.EOF {
  95. log.Warning("Socks: failed to read authentication: ", err)
  96. }
  97. return
  98. }
  99. clientAddr := connection.RemoteAddr().String()
  100. if err != nil && err == protocol.Socks4Downgrade {
  101. this.handleSocks4(clientAddr, reader, writer, auth4)
  102. } else {
  103. this.handleSocks5(clientAddr, reader, writer, auth)
  104. }
  105. }
  106. func (this *Server) handleSocks5(clientAddr string, reader *v2io.BufferedReader, writer *v2io.BufferedWriter, auth protocol.Socks5AuthenticationRequest) error {
  107. expectedAuthMethod := protocol.AuthNotRequired
  108. if this.config.AuthType == AuthTypePassword {
  109. expectedAuthMethod = protocol.AuthUserPass
  110. }
  111. if !auth.HasAuthMethod(expectedAuthMethod) {
  112. authResponse := protocol.NewAuthenticationResponse(protocol.AuthNoMatchingMethod)
  113. err := protocol.WriteAuthentication(writer, authResponse)
  114. writer.Flush()
  115. if err != nil {
  116. log.Warning("Socks: failed to write authentication: ", err)
  117. return err
  118. }
  119. log.Warning("Socks: client doesn't support any allowed auth methods.")
  120. return ErrorUnsupportedAuthMethod
  121. }
  122. authResponse := protocol.NewAuthenticationResponse(expectedAuthMethod)
  123. protocol.WriteAuthentication(writer, authResponse)
  124. err := writer.Flush()
  125. if err != nil {
  126. log.Error("Socks: failed to write authentication: ", err)
  127. return err
  128. }
  129. if this.config.AuthType == AuthTypePassword {
  130. upRequest, err := protocol.ReadUserPassRequest(reader)
  131. if err != nil {
  132. log.Warning("Socks: failed to read username and password: ", err)
  133. return err
  134. }
  135. status := byte(0)
  136. if !this.config.HasAccount(upRequest.Username(), upRequest.Password()) {
  137. status = byte(0xFF)
  138. }
  139. upResponse := protocol.NewSocks5UserPassResponse(status)
  140. err = protocol.WriteUserPassResponse(writer, upResponse)
  141. writer.Flush()
  142. if err != nil {
  143. log.Error("Socks: failed to write user pass response: ", err)
  144. return err
  145. }
  146. if status != byte(0) {
  147. log.Warning("Socks: Invalid user account: ", upRequest.AuthDetail())
  148. log.Access(clientAddr, "", log.AccessRejected, proxy.ErrorInvalidAuthentication)
  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. log.Access(clientAddr, dest, log.AccessAccepted, "")
  189. this.transport(reader, writer, dest)
  190. return nil
  191. }
  192. func (this *Server) handleUDP(reader io.Reader, writer *v2io.BufferedWriter) error {
  193. response := protocol.NewSocks5Response()
  194. response.Error = protocol.ErrorSuccess
  195. udpAddr := this.udpAddress
  196. response.Port = udpAddr.Port()
  197. switch {
  198. case udpAddr.Address().IsIPv4():
  199. response.SetIPv4(udpAddr.Address().IP())
  200. case udpAddr.Address().IsIPv6():
  201. response.SetIPv6(udpAddr.Address().IP())
  202. case udpAddr.Address().IsDomain():
  203. response.SetDomain(udpAddr.Address().Domain())
  204. }
  205. response.Write(writer)
  206. err := writer.Flush()
  207. if err != nil {
  208. log.Error("Socks: failed to write response: ", err)
  209. return err
  210. }
  211. // The TCP connection closes after this method returns. We need to wait until
  212. // the client closes it.
  213. // TODO: get notified from UDP part
  214. <-time.After(5 * time.Minute)
  215. return nil
  216. }
  217. func (this *Server) handleSocks4(clientAddr string, reader *v2io.BufferedReader, writer *v2io.BufferedWriter, auth protocol.Socks4AuthenticationRequest) error {
  218. result := protocol.Socks4RequestGranted
  219. if auth.Command == protocol.CmdBind {
  220. result = protocol.Socks4RequestRejected
  221. }
  222. socks4Response := protocol.NewSocks4AuthenticationResponse(result, auth.Port, auth.IP[:])
  223. socks4Response.Write(writer)
  224. if result == protocol.Socks4RequestRejected {
  225. log.Warning("Socks: Unsupported socks 4 command ", auth.Command)
  226. log.Access(clientAddr, "", log.AccessRejected, ErrorUnsupportedSocksCommand)
  227. return ErrorUnsupportedSocksCommand
  228. }
  229. reader.SetCached(false)
  230. writer.SetCached(false)
  231. dest := v2net.TCPDestination(v2net.IPAddress(auth.IP[:]), auth.Port)
  232. log.Access(clientAddr, dest, log.AccessAccepted, "")
  233. this.transport(reader, writer, dest)
  234. return nil
  235. }
  236. func (this *Server) transport(reader io.Reader, writer io.Writer, destination v2net.Destination) {
  237. ray := this.packetDispatcher.DispatchToOutbound(destination)
  238. input := ray.InboundInput()
  239. output := ray.InboundOutput()
  240. var inputFinish, outputFinish sync.Mutex
  241. inputFinish.Lock()
  242. outputFinish.Lock()
  243. go func() {
  244. v2reader := v2io.NewAdaptiveReader(reader)
  245. defer v2reader.Release()
  246. v2io.Pipe(v2reader, input)
  247. inputFinish.Unlock()
  248. input.Close()
  249. }()
  250. go func() {
  251. v2writer := v2io.NewAdaptiveWriter(writer)
  252. defer v2writer.Release()
  253. v2io.Pipe(output, v2writer)
  254. outputFinish.Unlock()
  255. output.Release()
  256. }()
  257. outputFinish.Lock()
  258. }
  259. func init() {
  260. internal.MustRegisterInboundHandlerCreator("socks",
  261. func(space app.Space, rawConfig interface{}, meta *proxy.InboundHandlerMeta) (proxy.InboundHandler, error) {
  262. if !space.HasApp(dispatcher.APP_ID) {
  263. return nil, internal.ErrorBadConfiguration
  264. }
  265. return NewServer(
  266. rawConfig.(*Config),
  267. space.GetApp(dispatcher.APP_ID).(dispatcher.PacketDispatcher),
  268. meta), nil
  269. })
  270. }