http2http.go 2.1 KB

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