http_proxy.go 5.3 KB

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