server.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  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/internet"
  16. "github.com/v2ray/v2ray-core/transport/internet/udp"
  17. )
  18. var (
  19. ErrorUnsupportedSocksCommand = errors.New("Unsupported socks command.")
  20. ErrorUnsupportedAuthMethod = errors.New("Unsupported auth method.")
  21. )
  22. // Server is a SOCKS 5 proxy server
  23. type Server struct {
  24. tcpMutex sync.RWMutex
  25. udpMutex sync.RWMutex
  26. accepting bool
  27. packetDispatcher dispatcher.PacketDispatcher
  28. config *Config
  29. tcpListener *internet.TCPHub
  30. udpHub *udp.UDPHub
  31. udpAddress v2net.Destination
  32. udpServer *udp.UDPServer
  33. meta *proxy.InboundHandlerMeta
  34. }
  35. // NewServer creates a new Server object.
  36. func NewServer(config *Config, packetDispatcher dispatcher.PacketDispatcher, meta *proxy.InboundHandlerMeta) *Server {
  37. return &Server{
  38. config: config,
  39. packetDispatcher: packetDispatcher,
  40. meta: meta,
  41. }
  42. }
  43. // Port implements InboundHandler.Port().
  44. func (this *Server) Port() v2net.Port {
  45. return this.meta.Port
  46. }
  47. // Close implements InboundHandler.Close().
  48. func (this *Server) Close() {
  49. this.accepting = false
  50. if this.tcpListener != nil {
  51. this.tcpMutex.Lock()
  52. this.tcpListener.Close()
  53. this.tcpListener = nil
  54. this.tcpMutex.Unlock()
  55. }
  56. if this.udpHub != nil {
  57. this.udpMutex.Lock()
  58. this.udpHub.Close()
  59. this.udpHub = nil
  60. this.udpMutex.Unlock()
  61. }
  62. }
  63. // Listen implements InboundHandler.Listen().
  64. func (this *Server) Start() error {
  65. if this.accepting {
  66. return nil
  67. }
  68. listener, err := internet.ListenTCP(
  69. this.meta.Address,
  70. this.meta.Port,
  71. this.handleConnection,
  72. this.meta.StreamSettings)
  73. if err != nil {
  74. log.Error("Socks: failed to listen on ", this.meta.Address, ":", this.meta.Port, ": ", err)
  75. return err
  76. }
  77. this.accepting = true
  78. this.tcpMutex.Lock()
  79. this.tcpListener = listener
  80. this.tcpMutex.Unlock()
  81. if this.config.UDPEnabled {
  82. this.listenUDP()
  83. }
  84. return nil
  85. }
  86. func (this *Server) handleConnection(connection internet.Connection) {
  87. defer connection.Close()
  88. timedReader := v2net.NewTimeOutReader(120, connection)
  89. reader := v2io.NewBufferedReader(timedReader)
  90. defer reader.Release()
  91. writer := v2io.NewBufferedWriter(connection)
  92. defer writer.Release()
  93. auth, auth4, err := protocol.ReadAuthentication(reader)
  94. if err != nil && err != protocol.Socks4Downgrade {
  95. if err != io.EOF {
  96. log.Warning("Socks: failed to read authentication: ", err)
  97. }
  98. return
  99. }
  100. clientAddr := connection.RemoteAddr().String()
  101. if err != nil && err == protocol.Socks4Downgrade {
  102. this.handleSocks4(clientAddr, reader, writer, auth4)
  103. } else {
  104. this.handleSocks5(clientAddr, reader, writer, auth)
  105. }
  106. }
  107. func (this *Server) handleSocks5(clientAddr string, 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. log.Access(clientAddr, "", log.AccessRejected, proxy.ErrInvalidAuthentication)
  150. return proxy.ErrInvalidAuthentication
  151. }
  152. }
  153. request, err := protocol.ReadRequest(reader)
  154. if err != nil {
  155. log.Warning("Socks: failed to read request: ", err)
  156. return err
  157. }
  158. if request.Command == protocol.CmdUdpAssociate && this.config.UDPEnabled {
  159. return this.handleUDP(reader, writer)
  160. }
  161. if request.Command == protocol.CmdBind || request.Command == protocol.CmdUdpAssociate {
  162. response := protocol.NewSocks5Response()
  163. response.Error = protocol.ErrorCommandNotSupported
  164. response.Port = v2net.Port(0)
  165. response.SetIPv4([]byte{0, 0, 0, 0})
  166. response.Write(writer)
  167. writer.Flush()
  168. if err != nil {
  169. log.Error("Socks: failed to write response: ", err)
  170. return err
  171. }
  172. log.Warning("Socks: Unsupported socks command ", request.Command)
  173. return ErrorUnsupportedSocksCommand
  174. }
  175. response := protocol.NewSocks5Response()
  176. response.Error = protocol.ErrorSuccess
  177. // Some SOCKS software requires a value other than dest. Let's fake one:
  178. response.Port = v2net.Port(1717)
  179. response.SetIPv4([]byte{0, 0, 0, 0})
  180. response.Write(writer)
  181. if err != nil {
  182. log.Error("Socks: failed to write response: ", err)
  183. return err
  184. }
  185. reader.SetCached(false)
  186. writer.SetCached(false)
  187. dest := request.Destination()
  188. log.Info("Socks: TCP Connect request to ", dest)
  189. log.Access(clientAddr, dest, log.AccessAccepted, "")
  190. this.transport(reader, writer, dest)
  191. return nil
  192. }
  193. func (this *Server) handleUDP(reader io.Reader, writer *v2io.BufferedWriter) error {
  194. response := protocol.NewSocks5Response()
  195. response.Error = protocol.ErrorSuccess
  196. udpAddr := this.udpAddress
  197. response.Port = udpAddr.Port()
  198. switch {
  199. case udpAddr.Address().IsIPv4():
  200. response.SetIPv4(udpAddr.Address().IP())
  201. case udpAddr.Address().IsIPv6():
  202. response.SetIPv6(udpAddr.Address().IP())
  203. case udpAddr.Address().IsDomain():
  204. response.SetDomain(udpAddr.Address().Domain())
  205. }
  206. response.Write(writer)
  207. err := writer.Flush()
  208. if err != nil {
  209. log.Error("Socks: failed to write response: ", err)
  210. return err
  211. }
  212. // The TCP connection closes after this method returns. We need to wait until
  213. // the client closes it.
  214. // TODO: get notified from UDP part
  215. <-time.After(5 * time.Minute)
  216. return nil
  217. }
  218. func (this *Server) handleSocks4(clientAddr string, reader *v2io.BufferedReader, writer *v2io.BufferedWriter, auth protocol.Socks4AuthenticationRequest) error {
  219. result := protocol.Socks4RequestGranted
  220. if auth.Command == protocol.CmdBind {
  221. result = protocol.Socks4RequestRejected
  222. }
  223. socks4Response := protocol.NewSocks4AuthenticationResponse(result, auth.Port, auth.IP[:])
  224. socks4Response.Write(writer)
  225. if result == protocol.Socks4RequestRejected {
  226. log.Warning("Socks: Unsupported socks 4 command ", auth.Command)
  227. log.Access(clientAddr, "", log.AccessRejected, ErrorUnsupportedSocksCommand)
  228. return ErrorUnsupportedSocksCommand
  229. }
  230. reader.SetCached(false)
  231. writer.SetCached(false)
  232. dest := v2net.TCPDestination(v2net.IPAddress(auth.IP[:]), auth.Port)
  233. log.Access(clientAddr, dest, log.AccessAccepted, "")
  234. this.transport(reader, writer, dest)
  235. return nil
  236. }
  237. func (this *Server) transport(reader io.Reader, writer io.Writer, destination v2net.Destination) {
  238. ray := this.packetDispatcher.DispatchToOutbound(destination)
  239. input := ray.InboundInput()
  240. output := ray.InboundOutput()
  241. var inputFinish, outputFinish sync.Mutex
  242. inputFinish.Lock()
  243. outputFinish.Lock()
  244. go func() {
  245. v2reader := v2io.NewAdaptiveReader(reader)
  246. defer v2reader.Release()
  247. v2io.Pipe(v2reader, input)
  248. inputFinish.Unlock()
  249. input.Close()
  250. }()
  251. go func() {
  252. v2writer := v2io.NewAdaptiveWriter(writer)
  253. defer v2writer.Release()
  254. v2io.Pipe(output, v2writer)
  255. outputFinish.Unlock()
  256. output.Release()
  257. }()
  258. outputFinish.Lock()
  259. }
  260. type ServerFactory struct{}
  261. func (this *ServerFactory) StreamCapability() internet.StreamConnectionType {
  262. return internet.StreamConnectionTypeRawTCP
  263. }
  264. func (this *ServerFactory) Create(space app.Space, rawConfig interface{}, meta *proxy.InboundHandlerMeta) (proxy.InboundHandler, error) {
  265. if !space.HasApp(dispatcher.APP_ID) {
  266. return nil, internal.ErrBadConfiguration
  267. }
  268. return NewServer(
  269. rawConfig.(*Config),
  270. space.GetApp(dispatcher.APP_ID).(dispatcher.PacketDispatcher),
  271. meta), nil
  272. }
  273. func init() {
  274. internal.MustRegisterInboundHandlerCreator("socks", new(ServerFactory))
  275. }