tcp.go 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  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. )
  24. type TcpListener struct {
  25. net.Addr
  26. listener net.Listener
  27. accept chan Conn
  28. closeFlag bool
  29. }
  30. func ListenTcp(bindAddr string, bindPort int64) (l *TcpListener, err error) {
  31. tcpAddr, err := net.ResolveTCPAddr("tcp", fmt.Sprintf("%s:%d", bindAddr, bindPort))
  32. if err != nil {
  33. return l, err
  34. }
  35. listener, err := net.ListenTCP("tcp", tcpAddr)
  36. if err != nil {
  37. return l, err
  38. }
  39. l = &TcpListener{
  40. Addr: listener.Addr(),
  41. listener: listener,
  42. accept: make(chan Conn),
  43. closeFlag: false,
  44. }
  45. go func() {
  46. for {
  47. conn, err := listener.AcceptTCP()
  48. if err != nil {
  49. if l.closeFlag {
  50. close(l.accept)
  51. return
  52. }
  53. continue
  54. }
  55. c := NewTcpConn(conn)
  56. l.accept <- c
  57. }
  58. }()
  59. return l, err
  60. }
  61. // Wait util get one new connection or listener is closed
  62. // if listener is closed, err returned.
  63. func (l *TcpListener) Accept() (Conn, error) {
  64. conn, ok := <-l.accept
  65. if !ok {
  66. return conn, fmt.Errorf("channel for tcp listener closed")
  67. }
  68. return conn, nil
  69. }
  70. func (l *TcpListener) Close() error {
  71. if !l.closeFlag {
  72. l.closeFlag = true
  73. l.listener.Close()
  74. }
  75. return nil
  76. }
  77. // Wrap for TCPConn.
  78. type TcpConn struct {
  79. net.Conn
  80. log.Logger
  81. }
  82. func NewTcpConn(conn *net.TCPConn) (c *TcpConn) {
  83. c = &TcpConn{
  84. Conn: conn,
  85. Logger: log.NewPrefixLogger(""),
  86. }
  87. return
  88. }
  89. func ConnectTcpServer(addr string) (c Conn, err error) {
  90. servertAddr, err := net.ResolveTCPAddr("tcp", addr)
  91. if err != nil {
  92. return
  93. }
  94. conn, err := net.DialTCP("tcp", nil, servertAddr)
  95. if err != nil {
  96. return
  97. }
  98. c = NewTcpConn(conn)
  99. return
  100. }
  101. // ConnectTcpServerByHttpProxy try to connect remote server by http proxy.
  102. // If httpProxy is empty, it will connect server directly.
  103. func ConnectTcpServerByHttpProxy(httpProxy string, serverAddr string) (c Conn, err error) {
  104. if httpProxy == "" {
  105. return ConnectTcpServer(serverAddr)
  106. }
  107. var proxyUrl *url.URL
  108. if proxyUrl, err = url.Parse(httpProxy); err != nil {
  109. return
  110. }
  111. var proxyAuth string
  112. if proxyUrl.User != nil {
  113. proxyAuth = "Basic " + base64.StdEncoding.EncodeToString([]byte(proxyUrl.User.String()))
  114. }
  115. if proxyUrl.Scheme != "http" {
  116. err = fmt.Errorf("Proxy URL scheme must be http, not [%s]", proxyUrl.Scheme)
  117. return
  118. }
  119. if c, err = ConnectTcpServer(proxyUrl.Host); err != nil {
  120. return
  121. }
  122. req, err := http.NewRequest("CONNECT", "http://"+serverAddr, nil)
  123. if err != nil {
  124. return
  125. }
  126. if proxyAuth != "" {
  127. req.Header.Set("Proxy-Authorization", proxyAuth)
  128. }
  129. req.Header.Set("User-Agent", "Mozilla/5.0")
  130. req.Write(c)
  131. resp, err := http.ReadResponse(bufio.NewReader(c), req)
  132. if err != nil {
  133. return
  134. }
  135. resp.Body.Close()
  136. if resp.StatusCode != 200 {
  137. err = fmt.Errorf("ConnectTcpServer using proxy error, StatusCode [%d]", resp.StatusCode)
  138. return
  139. }
  140. return
  141. }