1
0

http_proxy.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  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) {
  92. var wrapConn frpNet.Conn
  93. if realConn, ok := conn.(frpNet.Conn); ok {
  94. wrapConn = realConn
  95. } else {
  96. wrapConn = frpNet.WrapReadWriteCloserToConn(conn, realConn)
  97. }
  98. sc, rd := frpNet.NewShareConn(wrapConn)
  99. request, err := http.ReadRequest(bufio.NewReader(rd))
  100. if err != nil {
  101. wrapConn.Close()
  102. return
  103. }
  104. if request.Method == http.MethodConnect {
  105. hp.handleConnectReq(request, frpIo.WrapReadWriteCloser(rd, wrapConn, nil))
  106. return
  107. }
  108. hp.l.PutConn(sc)
  109. return
  110. }
  111. func (hp *HttpProxy) Close() error {
  112. hp.s.Close()
  113. hp.l.Close()
  114. return nil
  115. }
  116. func (hp *HttpProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
  117. if ok := hp.Auth(req); !ok {
  118. rw.Header().Set("Proxy-Authenticate", "Basic")
  119. rw.WriteHeader(http.StatusProxyAuthRequired)
  120. return
  121. }
  122. if req.Method == http.MethodConnect {
  123. // deprecated
  124. // Connect request is handled in Handle function.
  125. hp.ConnectHandler(rw, req)
  126. } else {
  127. hp.HttpHandler(rw, req)
  128. }
  129. }
  130. func (hp *HttpProxy) HttpHandler(rw http.ResponseWriter, req *http.Request) {
  131. removeProxyHeaders(req)
  132. resp, err := http.DefaultTransport.RoundTrip(req)
  133. if err != nil {
  134. http.Error(rw, err.Error(), http.StatusInternalServerError)
  135. return
  136. }
  137. defer resp.Body.Close()
  138. copyHeaders(rw.Header(), resp.Header)
  139. rw.WriteHeader(resp.StatusCode)
  140. _, err = io.Copy(rw, resp.Body)
  141. if err != nil && err != io.EOF {
  142. return
  143. }
  144. }
  145. // deprecated
  146. // Hijack needs to SetReadDeadline on the Conn of the request, but if we use stream compression here,
  147. // we may always get i/o timeout error.
  148. func (hp *HttpProxy) ConnectHandler(rw http.ResponseWriter, req *http.Request) {
  149. hj, ok := rw.(http.Hijacker)
  150. if !ok {
  151. rw.WriteHeader(http.StatusInternalServerError)
  152. return
  153. }
  154. client, _, err := hj.Hijack()
  155. if err != nil {
  156. rw.WriteHeader(http.StatusInternalServerError)
  157. return
  158. }
  159. remote, err := net.Dial("tcp", req.URL.Host)
  160. if err != nil {
  161. http.Error(rw, "Failed", http.StatusBadRequest)
  162. client.Close()
  163. return
  164. }
  165. client.Write([]byte("HTTP/1.1 200 OK\r\n\r\n"))
  166. go frpIo.Join(remote, client)
  167. }
  168. func (hp *HttpProxy) Auth(req *http.Request) bool {
  169. if hp.AuthUser == "" && hp.AuthPasswd == "" {
  170. return true
  171. }
  172. s := strings.SplitN(req.Header.Get("Proxy-Authorization"), " ", 2)
  173. if len(s) != 2 {
  174. return false
  175. }
  176. b, err := base64.StdEncoding.DecodeString(s[1])
  177. if err != nil {
  178. return false
  179. }
  180. pair := strings.SplitN(string(b), ":", 2)
  181. if len(pair) != 2 {
  182. return false
  183. }
  184. if pair[0] != hp.AuthUser || pair[1] != hp.AuthPasswd {
  185. return false
  186. }
  187. return true
  188. }
  189. func (hp *HttpProxy) handleConnectReq(req *http.Request, rwc io.ReadWriteCloser) {
  190. defer rwc.Close()
  191. if ok := hp.Auth(req); !ok {
  192. res := getBadResponse()
  193. res.Write(rwc)
  194. return
  195. }
  196. remote, err := net.Dial("tcp", req.URL.Host)
  197. if err != nil {
  198. res := &http.Response{
  199. StatusCode: 400,
  200. Proto: "HTTP/1.1",
  201. ProtoMajor: 1,
  202. ProtoMinor: 1,
  203. }
  204. res.Write(rwc)
  205. return
  206. }
  207. rwc.Write([]byte("HTTP/1.1 200 OK\r\n\r\n"))
  208. frpIo.Join(remote, rwc)
  209. }
  210. func copyHeaders(dst, src http.Header) {
  211. for key, values := range src {
  212. for _, value := range values {
  213. dst.Add(key, value)
  214. }
  215. }
  216. }
  217. func removeProxyHeaders(req *http.Request) {
  218. req.RequestURI = ""
  219. req.Header.Del("Proxy-Connection")
  220. req.Header.Del("Connection")
  221. req.Header.Del("Proxy-Authenticate")
  222. req.Header.Del("Proxy-Authorization")
  223. req.Header.Del("TE")
  224. req.Header.Del("Trailers")
  225. req.Header.Del("Transfer-Encoding")
  226. req.Header.Del("Upgrade")
  227. }
  228. func getBadResponse() *http.Response {
  229. header := make(map[string][]string)
  230. header["Proxy-Authenticate"] = []string{"Basic"}
  231. res := &http.Response{
  232. Status: "407 Not authorized",
  233. StatusCode: 407,
  234. Proto: "HTTP/1.1",
  235. ProtoMajor: 1,
  236. ProtoMinor: 1,
  237. Header: header,
  238. }
  239. return res
  240. }