http2http.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. // Copyright 2024 The frp Authors
  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. "io"
  17. stdlog "log"
  18. "net"
  19. "net/http"
  20. "net/http/httputil"
  21. "github.com/fatedier/golib/pool"
  22. v1 "github.com/fatedier/frp/pkg/config/v1"
  23. "github.com/fatedier/frp/pkg/util/log"
  24. netpkg "github.com/fatedier/frp/pkg/util/net"
  25. )
  26. func init() {
  27. Register(v1.PluginHTTP2HTTP, NewHTTP2HTTPPlugin)
  28. }
  29. type HTTP2HTTPPlugin struct {
  30. opts *v1.HTTP2HTTPPluginOptions
  31. l *Listener
  32. s *http.Server
  33. }
  34. func NewHTTP2HTTPPlugin(options v1.ClientPluginOptions) (Plugin, error) {
  35. opts := options.(*v1.HTTP2HTTPPluginOptions)
  36. listener := NewProxyListener()
  37. p := &HTTP2HTTPPlugin{
  38. opts: opts,
  39. l: listener,
  40. }
  41. rp := &httputil.ReverseProxy{
  42. Rewrite: func(r *httputil.ProxyRequest) {
  43. req := r.Out
  44. req.URL.Scheme = "http"
  45. req.URL.Host = p.opts.LocalAddr
  46. if p.opts.HostHeaderRewrite != "" {
  47. req.Host = p.opts.HostHeaderRewrite
  48. }
  49. for k, v := range p.opts.RequestHeaders.Set {
  50. req.Header.Set(k, v)
  51. }
  52. },
  53. BufferPool: pool.NewBuffer(32 * 1024),
  54. ErrorLog: stdlog.New(log.NewWriteLogger(log.WarnLevel, 2), "", 0),
  55. }
  56. p.s = &http.Server{
  57. Handler: rp,
  58. ReadHeaderTimeout: 0,
  59. }
  60. go func() {
  61. _ = p.s.Serve(listener)
  62. }()
  63. return p, nil
  64. }
  65. func (p *HTTP2HTTPPlugin) Handle(conn io.ReadWriteCloser, realConn net.Conn, _ *ExtraInfo) {
  66. wrapConn := netpkg.WrapReadWriteCloserToConn(conn, realConn)
  67. _ = p.l.PutConn(wrapConn)
  68. }
  69. func (p *HTTP2HTTPPlugin) Name() string {
  70. return v1.PluginHTTP2HTTP
  71. }
  72. func (p *HTTP2HTTPPlugin) Close() error {
  73. return p.s.Close()
  74. }