http_proxy.go 5.3 KB

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