http_proxy.go 5.2 KB

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