tcp.go 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. // Copyright 2016 fatedier, fatedier@gmail.com
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package net
  15. import (
  16. "bufio"
  17. "encoding/base64"
  18. "fmt"
  19. "net"
  20. "net/http"
  21. "net/url"
  22. "github.com/fatedier/frp/utils/log"
  23. "golang.org/x/net/proxy"
  24. )
  25. type TcpListener struct {
  26. net.Addr
  27. listener net.Listener
  28. accept chan Conn
  29. closeFlag bool
  30. log.Logger
  31. }
  32. func ListenTcp(bindAddr string, bindPort int) (l *TcpListener, err error) {
  33. tcpAddr, err := net.ResolveTCPAddr("tcp", fmt.Sprintf("%s:%d", bindAddr, bindPort))
  34. if err != nil {
  35. return l, err
  36. }
  37. listener, err := net.ListenTCP("tcp", tcpAddr)
  38. if err != nil {
  39. return l, err
  40. }
  41. l = &TcpListener{
  42. Addr: listener.Addr(),
  43. listener: listener,
  44. accept: make(chan Conn),
  45. closeFlag: false,
  46. Logger: log.NewPrefixLogger(""),
  47. }
  48. go func() {
  49. for {
  50. conn, err := listener.AcceptTCP()
  51. if err != nil {
  52. if l.closeFlag {
  53. close(l.accept)
  54. return
  55. }
  56. continue
  57. }
  58. c := NewTcpConn(conn)
  59. l.accept <- c
  60. }
  61. }()
  62. return l, err
  63. }
  64. // Wait util get one new connection or listener is closed
  65. // if listener is closed, err returned.
  66. func (l *TcpListener) Accept() (Conn, error) {
  67. conn, ok := <-l.accept
  68. if !ok {
  69. return conn, fmt.Errorf("channel for tcp listener closed")
  70. }
  71. return conn, nil
  72. }
  73. func (l *TcpListener) Close() error {
  74. if !l.closeFlag {
  75. l.closeFlag = true
  76. l.listener.Close()
  77. }
  78. return nil
  79. }
  80. // Wrap for TCPConn.
  81. type TcpConn struct {
  82. net.Conn
  83. log.Logger
  84. }
  85. func NewTcpConn(conn net.Conn) (c *TcpConn) {
  86. c = &TcpConn{
  87. Conn: conn,
  88. Logger: log.NewPrefixLogger(""),
  89. }
  90. return
  91. }
  92. func ConnectTcpServer(addr string) (c Conn, err error) {
  93. servertAddr, err := net.ResolveTCPAddr("tcp", addr)
  94. if err != nil {
  95. return
  96. }
  97. conn, err := net.DialTCP("tcp", nil, servertAddr)
  98. if err != nil {
  99. return
  100. }
  101. c = NewTcpConn(conn)
  102. return
  103. }
  104. // ConnectTcpServerByProxy try to connect remote server by proxy.
  105. func ConnectTcpServerByProxy(proxyStr string, serverAddr string) (c Conn, err error) {
  106. if proxyStr == "" {
  107. return ConnectTcpServer(serverAddr)
  108. }
  109. var (
  110. proxyUrl *url.URL
  111. username string
  112. passwd string
  113. )
  114. if proxyUrl, err = url.Parse(proxyStr); err != nil {
  115. return
  116. }
  117. if proxyUrl.User != nil {
  118. username = proxyUrl.User.Username()
  119. passwd, _ = proxyUrl.User.Password()
  120. }
  121. switch proxyUrl.Scheme {
  122. case "http":
  123. return ConnectTcpServerByHttpProxy(proxyUrl, username, passwd, serverAddr)
  124. case "socks5":
  125. return ConnectTcpServerBySocks5Proxy(proxyUrl, username, passwd, serverAddr)
  126. default:
  127. err = fmt.Errorf("Proxy URL scheme must be http or socks5, not [%s]", proxyUrl.Scheme)
  128. return
  129. }
  130. }
  131. // ConnectTcpServerByHttpProxy try to connect remote server by http proxy.
  132. func ConnectTcpServerByHttpProxy(proxyUrl *url.URL, user string, passwd string, serverAddr string) (c Conn, err error) {
  133. var proxyAuth string
  134. if proxyUrl.User != nil {
  135. proxyAuth = "Basic " + base64.StdEncoding.EncodeToString([]byte(user+":"+passwd))
  136. }
  137. if c, err = ConnectTcpServer(proxyUrl.Host); err != nil {
  138. return
  139. }
  140. req, err := http.NewRequest("CONNECT", "http://"+serverAddr, nil)
  141. if err != nil {
  142. return
  143. }
  144. if proxyAuth != "" {
  145. req.Header.Set("Proxy-Authorization", proxyAuth)
  146. }
  147. req.Header.Set("User-Agent", "Mozilla/5.0")
  148. req.Write(c)
  149. resp, err := http.ReadResponse(bufio.NewReader(c), req)
  150. if err != nil {
  151. return
  152. }
  153. resp.Body.Close()
  154. if resp.StatusCode != 200 {
  155. err = fmt.Errorf("ConnectTcpServer using proxy error, StatusCode [%d]", resp.StatusCode)
  156. return
  157. }
  158. return
  159. }
  160. func ConnectTcpServerBySocks5Proxy(proxyUrl *url.URL, user string, passwd string, serverAddr string) (c Conn, err error) {
  161. var auth *proxy.Auth
  162. if proxyUrl.User != nil {
  163. auth = &proxy.Auth{
  164. User: user,
  165. Password: passwd,
  166. }
  167. }
  168. dialer, err := proxy.SOCKS5("tcp", proxyUrl.Host, auth, nil)
  169. if err != nil {
  170. return nil, err
  171. }
  172. var conn net.Conn
  173. if conn, err = dialer.Dial("tcp", serverAddr); err != nil {
  174. return
  175. }
  176. c = NewTcpConn(conn)
  177. return
  178. }