server.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. package socks
  2. import (
  3. "errors"
  4. "io"
  5. "sync"
  6. "time"
  7. "v2ray.com/core/app"
  8. "v2ray.com/core/app/dispatcher"
  9. v2io "v2ray.com/core/common/io"
  10. "v2ray.com/core/common/loader"
  11. "v2ray.com/core/common/log"
  12. v2net "v2ray.com/core/common/net"
  13. "v2ray.com/core/proxy"
  14. "v2ray.com/core/proxy/registry"
  15. "v2ray.com/core/proxy/socks/protocol"
  16. "v2ray.com/core/transport/internet"
  17. "v2ray.com/core/transport/internet/udp"
  18. )
  19. var (
  20. ErrUnsupportedSocksCommand = errors.New("Unsupported socks command.")
  21. ErrUnsupportedAuthMethod = errors.New("Unsupported auth method.")
  22. )
  23. // Server is a SOCKS 5 proxy server
  24. type Server struct {
  25. tcpMutex sync.RWMutex
  26. udpMutex sync.RWMutex
  27. accepting bool
  28. packetDispatcher dispatcher.PacketDispatcher
  29. config *ServerConfig
  30. tcpListener *internet.TCPHub
  31. udpHub *udp.UDPHub
  32. udpAddress v2net.Destination
  33. udpServer *udp.UDPServer
  34. meta *proxy.InboundHandlerMeta
  35. }
  36. // NewServer creates a new Server object.
  37. func NewServer(config *ServerConfig, space app.Space, meta *proxy.InboundHandlerMeta) *Server {
  38. s := &Server{
  39. config: config,
  40. meta: meta,
  41. }
  42. space.InitializeApplication(func() error {
  43. if !space.HasApp(dispatcher.APP_ID) {
  44. log.Error("Socks|Server: Dispatcher is not found in the space.")
  45. return app.ErrMissingApplication
  46. }
  47. s.packetDispatcher = space.GetApp(dispatcher.APP_ID).(dispatcher.PacketDispatcher)
  48. return nil
  49. })
  50. return s
  51. }
  52. // Port implements InboundHandler.Port().
  53. func (this *Server) Port() v2net.Port {
  54. return this.meta.Port
  55. }
  56. // Close implements InboundHandler.Close().
  57. func (this *Server) Close() {
  58. this.accepting = false
  59. if this.tcpListener != nil {
  60. this.tcpMutex.Lock()
  61. this.tcpListener.Close()
  62. this.tcpListener = nil
  63. this.tcpMutex.Unlock()
  64. }
  65. if this.udpHub != nil {
  66. this.udpMutex.Lock()
  67. this.udpHub.Close()
  68. this.udpHub = nil
  69. this.udpMutex.Unlock()
  70. }
  71. }
  72. // Listen implements InboundHandler.Listen().
  73. func (this *Server) Start() error {
  74. if this.accepting {
  75. return nil
  76. }
  77. listener, err := internet.ListenTCP(
  78. this.meta.Address,
  79. this.meta.Port,
  80. this.handleConnection,
  81. this.meta.StreamSettings)
  82. if err != nil {
  83. log.Error("Socks: failed to listen on ", this.meta.Address, ":", this.meta.Port, ": ", err)
  84. return err
  85. }
  86. this.accepting = true
  87. this.tcpMutex.Lock()
  88. this.tcpListener = listener
  89. this.tcpMutex.Unlock()
  90. if this.config.UdpEnabled {
  91. this.listenUDP()
  92. }
  93. return nil
  94. }
  95. func (this *Server) handleConnection(connection internet.Connection) {
  96. defer connection.Close()
  97. timedReader := v2net.NewTimeOutReader(this.config.Timeout, connection)
  98. reader := v2io.NewBufferedReader(timedReader)
  99. defer reader.Release()
  100. writer := v2io.NewBufferedWriter(connection)
  101. defer writer.Release()
  102. auth, auth4, err := protocol.ReadAuthentication(reader)
  103. if err != nil && err != protocol.Socks4Downgrade {
  104. if err != io.EOF {
  105. log.Warning("Socks: failed to read authentication: ", err)
  106. }
  107. return
  108. }
  109. clientAddr := v2net.DestinationFromAddr(connection.RemoteAddr())
  110. if err != nil && err == protocol.Socks4Downgrade {
  111. this.handleSocks4(clientAddr, reader, writer, auth4)
  112. } else {
  113. this.handleSocks5(clientAddr, reader, writer, auth)
  114. }
  115. }
  116. func (this *Server) handleSocks5(clientAddr v2net.Destination, reader *v2io.BufferedReader, writer *v2io.BufferedWriter, auth protocol.Socks5AuthenticationRequest) error {
  117. expectedAuthMethod := protocol.AuthNotRequired
  118. if this.config.AuthType == AuthType_PASSWORD {
  119. expectedAuthMethod = protocol.AuthUserPass
  120. }
  121. if !auth.HasAuthMethod(expectedAuthMethod) {
  122. authResponse := protocol.NewAuthenticationResponse(protocol.AuthNoMatchingMethod)
  123. err := protocol.WriteAuthentication(writer, authResponse)
  124. writer.Flush()
  125. if err != nil {
  126. log.Warning("Socks: failed to write authentication: ", err)
  127. return err
  128. }
  129. log.Warning("Socks: client doesn't support any allowed auth methods.")
  130. return ErrUnsupportedAuthMethod
  131. }
  132. authResponse := protocol.NewAuthenticationResponse(expectedAuthMethod)
  133. protocol.WriteAuthentication(writer, authResponse)
  134. err := writer.Flush()
  135. if err != nil {
  136. log.Error("Socks: failed to write authentication: ", err)
  137. return err
  138. }
  139. if this.config.AuthType == AuthType_PASSWORD {
  140. upRequest, err := protocol.ReadUserPassRequest(reader)
  141. if err != nil {
  142. log.Warning("Socks: failed to read username and password: ", err)
  143. return err
  144. }
  145. status := byte(0)
  146. if !this.config.HasAccount(upRequest.Username(), upRequest.Password()) {
  147. status = byte(0xFF)
  148. }
  149. upResponse := protocol.NewSocks5UserPassResponse(status)
  150. err = protocol.WriteUserPassResponse(writer, upResponse)
  151. writer.Flush()
  152. if err != nil {
  153. log.Error("Socks: failed to write user pass response: ", err)
  154. return err
  155. }
  156. if status != byte(0) {
  157. log.Warning("Socks: Invalid user account: ", upRequest.AuthDetail())
  158. log.Access(clientAddr, "", log.AccessRejected, proxy.ErrInvalidAuthentication)
  159. return proxy.ErrInvalidAuthentication
  160. }
  161. }
  162. request, err := protocol.ReadRequest(reader)
  163. if err != nil {
  164. log.Warning("Socks: failed to read request: ", err)
  165. return err
  166. }
  167. if request.Command == protocol.CmdUdpAssociate && this.config.UdpEnabled {
  168. return this.handleUDP(reader, writer)
  169. }
  170. if request.Command == protocol.CmdBind || request.Command == protocol.CmdUdpAssociate {
  171. response := protocol.NewSocks5Response()
  172. response.Error = protocol.ErrorCommandNotSupported
  173. response.Port = v2net.Port(0)
  174. response.SetIPv4([]byte{0, 0, 0, 0})
  175. response.Write(writer)
  176. writer.Flush()
  177. if err != nil {
  178. log.Error("Socks: failed to write response: ", err)
  179. return err
  180. }
  181. log.Warning("Socks: Unsupported socks command ", request.Command)
  182. return ErrUnsupportedSocksCommand
  183. }
  184. response := protocol.NewSocks5Response()
  185. response.Error = protocol.ErrorSuccess
  186. // Some SOCKS software requires a value other than dest. Let's fake one:
  187. response.Port = v2net.Port(1717)
  188. response.SetIPv4([]byte{0, 0, 0, 0})
  189. response.Write(writer)
  190. if err != nil {
  191. log.Error("Socks: failed to write response: ", err)
  192. return err
  193. }
  194. reader.SetCached(false)
  195. writer.SetCached(false)
  196. dest := request.Destination()
  197. session := &proxy.SessionInfo{
  198. Source: clientAddr,
  199. Destination: dest,
  200. }
  201. log.Info("Socks: TCP Connect request to ", dest)
  202. log.Access(clientAddr, dest, log.AccessAccepted, "")
  203. this.transport(reader, writer, session)
  204. return nil
  205. }
  206. func (this *Server) handleUDP(reader io.Reader, writer *v2io.BufferedWriter) error {
  207. response := protocol.NewSocks5Response()
  208. response.Error = protocol.ErrorSuccess
  209. udpAddr := this.udpAddress
  210. response.Port = udpAddr.Port
  211. switch udpAddr.Address.Family() {
  212. case v2net.AddressFamilyIPv4:
  213. response.SetIPv4(udpAddr.Address.IP())
  214. case v2net.AddressFamilyIPv6:
  215. response.SetIPv6(udpAddr.Address.IP())
  216. case v2net.AddressFamilyDomain:
  217. response.SetDomain(udpAddr.Address.Domain())
  218. }
  219. response.Write(writer)
  220. err := writer.Flush()
  221. if err != nil {
  222. log.Error("Socks: failed to write response: ", err)
  223. return err
  224. }
  225. // The TCP connection closes after this method returns. We need to wait until
  226. // the client closes it.
  227. // TODO: get notified from UDP part
  228. <-time.After(5 * time.Minute)
  229. return nil
  230. }
  231. func (this *Server) handleSocks4(clientAddr v2net.Destination, reader *v2io.BufferedReader, writer *v2io.BufferedWriter, auth protocol.Socks4AuthenticationRequest) error {
  232. result := protocol.Socks4RequestGranted
  233. if auth.Command == protocol.CmdBind {
  234. result = protocol.Socks4RequestRejected
  235. }
  236. socks4Response := protocol.NewSocks4AuthenticationResponse(result, auth.Port, auth.IP[:])
  237. socks4Response.Write(writer)
  238. if result == protocol.Socks4RequestRejected {
  239. log.Warning("Socks: Unsupported socks 4 command ", auth.Command)
  240. log.Access(clientAddr, "", log.AccessRejected, ErrUnsupportedSocksCommand)
  241. return ErrUnsupportedSocksCommand
  242. }
  243. reader.SetCached(false)
  244. writer.SetCached(false)
  245. dest := v2net.TCPDestination(v2net.IPAddress(auth.IP[:]), auth.Port)
  246. session := &proxy.SessionInfo{
  247. Source: clientAddr,
  248. Destination: dest,
  249. }
  250. log.Access(clientAddr, dest, log.AccessAccepted, "")
  251. this.transport(reader, writer, session)
  252. return nil
  253. }
  254. func (this *Server) transport(reader io.Reader, writer io.Writer, session *proxy.SessionInfo) {
  255. ray := this.packetDispatcher.DispatchToOutbound(this.meta, session)
  256. input := ray.InboundInput()
  257. output := ray.InboundOutput()
  258. defer input.Close()
  259. defer output.Release()
  260. go func() {
  261. v2reader := v2io.NewAdaptiveReader(reader)
  262. defer v2reader.Release()
  263. v2io.Pipe(v2reader, input)
  264. input.Close()
  265. }()
  266. v2writer := v2io.NewAdaptiveWriter(writer)
  267. defer v2writer.Release()
  268. v2io.Pipe(output, v2writer)
  269. output.Release()
  270. }
  271. type ServerFactory struct{}
  272. func (this *ServerFactory) StreamCapability() v2net.NetworkList {
  273. return v2net.NetworkList{
  274. Network: []v2net.Network{v2net.Network_RawTCP},
  275. }
  276. }
  277. func (this *ServerFactory) Create(space app.Space, rawConfig interface{}, meta *proxy.InboundHandlerMeta) (proxy.InboundHandler, error) {
  278. return NewServer(rawConfig.(*ServerConfig), space, meta), nil
  279. }
  280. func init() {
  281. registry.MustRegisterInboundHandlerCreator(loader.GetType(new(ServerConfig)), new(ServerFactory))
  282. }