1
0

http_proxy.go 5.0 KB

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