http_proxy.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. // Copyright 2017 frp team
  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 plugin
  15. import (
  16. "bufio"
  17. "encoding/base64"
  18. "fmt"
  19. "io"
  20. "net"
  21. "net/http"
  22. "strings"
  23. "sync"
  24. "github.com/fatedier/frp/utils/errors"
  25. frpIo "github.com/fatedier/frp/utils/io"
  26. frpNet "github.com/fatedier/frp/utils/net"
  27. )
  28. const PluginHttpProxy = "http_proxy"
  29. func init() {
  30. Register(PluginHttpProxy, NewHttpProxyPlugin)
  31. }
  32. type Listener struct {
  33. conns chan net.Conn
  34. closed bool
  35. mu sync.Mutex
  36. }
  37. func NewProxyListener() *Listener {
  38. return &Listener{
  39. conns: make(chan net.Conn, 64),
  40. }
  41. }
  42. func (l *Listener) Accept() (net.Conn, error) {
  43. conn, ok := <-l.conns
  44. if !ok {
  45. return nil, fmt.Errorf("listener closed")
  46. }
  47. return conn, nil
  48. }
  49. func (l *Listener) PutConn(conn net.Conn) error {
  50. err := errors.PanicToError(func() {
  51. l.conns <- conn
  52. })
  53. return err
  54. }
  55. func (l *Listener) Close() error {
  56. l.mu.Lock()
  57. defer l.mu.Unlock()
  58. if !l.closed {
  59. close(l.conns)
  60. l.closed = true
  61. }
  62. return nil
  63. }
  64. func (l *Listener) Addr() net.Addr {
  65. return (*net.TCPAddr)(nil)
  66. }
  67. type HttpProxy struct {
  68. l *Listener
  69. s *http.Server
  70. AuthUser string
  71. AuthPasswd string
  72. }
  73. func NewHttpProxyPlugin(params map[string]string) (Plugin, error) {
  74. user := params["plugin_http_user"]
  75. passwd := params["plugin_http_passwd"]
  76. listener := NewProxyListener()
  77. hp := &HttpProxy{
  78. l: listener,
  79. AuthUser: user,
  80. AuthPasswd: passwd,
  81. }
  82. hp.s = &http.Server{
  83. Handler: hp,
  84. }
  85. go hp.s.Serve(listener)
  86. return hp, nil
  87. }
  88. func (hp *HttpProxy) Name() string {
  89. return PluginHttpProxy
  90. }
  91. func (hp *HttpProxy) Handle(conn io.ReadWriteCloser, realConn frpNet.Conn) {
  92. wrapConn := frpNet.WrapReadWriteCloserToConn(conn, realConn)
  93. sc, rd := frpNet.NewShareConn(wrapConn)
  94. request, err := http.ReadRequest(bufio.NewReader(rd))
  95. if err != nil {
  96. wrapConn.Close()
  97. return
  98. }
  99. if request.Method == http.MethodConnect {
  100. hp.handleConnectReq(request, frpIo.WrapReadWriteCloser(rd, wrapConn, nil))
  101. return
  102. }
  103. hp.l.PutConn(sc)
  104. return
  105. }
  106. func (hp *HttpProxy) Close() error {
  107. hp.s.Close()
  108. hp.l.Close()
  109. return nil
  110. }
  111. func (hp *HttpProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
  112. if ok := hp.Auth(req); !ok {
  113. rw.Header().Set("Proxy-Authenticate", "Basic")
  114. rw.WriteHeader(http.StatusProxyAuthRequired)
  115. return
  116. }
  117. if req.Method == http.MethodConnect {
  118. // deprecated
  119. // Connect request is handled in Handle function.
  120. hp.ConnectHandler(rw, req)
  121. } else {
  122. hp.HttpHandler(rw, req)
  123. }
  124. }
  125. func (hp *HttpProxy) HttpHandler(rw http.ResponseWriter, req *http.Request) {
  126. removeProxyHeaders(req)
  127. resp, err := http.DefaultTransport.RoundTrip(req)
  128. if err != nil {
  129. http.Error(rw, err.Error(), http.StatusInternalServerError)
  130. return
  131. }
  132. defer resp.Body.Close()
  133. copyHeaders(rw.Header(), resp.Header)
  134. rw.WriteHeader(resp.StatusCode)
  135. _, err = io.Copy(rw, resp.Body)
  136. if err != nil && err != io.EOF {
  137. return
  138. }
  139. }
  140. // deprecated
  141. // Hijack needs to SetReadDeadline on the Conn of the request, but if we use stream compression here,
  142. // we may always get i/o timeout error.
  143. func (hp *HttpProxy) ConnectHandler(rw http.ResponseWriter, req *http.Request) {
  144. hj, ok := rw.(http.Hijacker)
  145. if !ok {
  146. rw.WriteHeader(http.StatusInternalServerError)
  147. return
  148. }
  149. client, _, err := hj.Hijack()
  150. if err != nil {
  151. rw.WriteHeader(http.StatusInternalServerError)
  152. return
  153. }
  154. remote, err := net.Dial("tcp", req.URL.Host)
  155. if err != nil {
  156. http.Error(rw, "Failed", http.StatusBadRequest)
  157. client.Close()
  158. return
  159. }
  160. client.Write([]byte("HTTP/1.1 200 OK\r\n\r\n"))
  161. go frpIo.Join(remote, client)
  162. }
  163. func (hp *HttpProxy) Auth(req *http.Request) bool {
  164. if hp.AuthUser == "" && hp.AuthPasswd == "" {
  165. return true
  166. }
  167. s := strings.SplitN(req.Header.Get("Proxy-Authorization"), " ", 2)
  168. if len(s) != 2 {
  169. return false
  170. }
  171. b, err := base64.StdEncoding.DecodeString(s[1])
  172. if err != nil {
  173. return false
  174. }
  175. pair := strings.SplitN(string(b), ":", 2)
  176. if len(pair) != 2 {
  177. return false
  178. }
  179. if pair[0] != hp.AuthUser || pair[1] != hp.AuthPasswd {
  180. return false
  181. }
  182. return true
  183. }
  184. func (hp *HttpProxy) handleConnectReq(req *http.Request, rwc io.ReadWriteCloser) {
  185. defer rwc.Close()
  186. if ok := hp.Auth(req); !ok {
  187. res := getBadResponse()
  188. res.Write(rwc)
  189. return
  190. }
  191. remote, err := net.Dial("tcp", req.URL.Host)
  192. if err != nil {
  193. res := &http.Response{
  194. StatusCode: 400,
  195. Proto: "HTTP/1.1",
  196. ProtoMajor: 1,
  197. ProtoMinor: 1,
  198. }
  199. res.Write(rwc)
  200. return
  201. }
  202. rwc.Write([]byte("HTTP/1.1 200 OK\r\n\r\n"))
  203. frpIo.Join(remote, rwc)
  204. }
  205. func copyHeaders(dst, src http.Header) {
  206. for key, values := range src {
  207. for _, value := range values {
  208. dst.Add(key, value)
  209. }
  210. }
  211. }
  212. func removeProxyHeaders(req *http.Request) {
  213. req.RequestURI = ""
  214. req.Header.Del("Proxy-Connection")
  215. req.Header.Del("Connection")
  216. req.Header.Del("Proxy-Authenticate")
  217. req.Header.Del("Proxy-Authorization")
  218. req.Header.Del("TE")
  219. req.Header.Del("Trailers")
  220. req.Header.Del("Transfer-Encoding")
  221. req.Header.Del("Upgrade")
  222. }
  223. func getBadResponse() *http.Response {
  224. header := make(map[string][]string)
  225. header["Proxy-Authenticate"] = []string{"Basic"}
  226. res := &http.Response{
  227. Status: "407 Not authorized",
  228. StatusCode: 407,
  229. Proto: "HTTP/1.1",
  230. ProtoMajor: 1,
  231. ProtoMinor: 1,
  232. Header: header,
  233. }
  234. return res
  235. }