http2https.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. // Copyright 2019 fatedier, fatedier@gmail.com
  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. "crypto/tls"
  17. "io"
  18. "net"
  19. "net/http"
  20. "net/http/httputil"
  21. v1 "github.com/fatedier/frp/pkg/config/v1"
  22. utilnet "github.com/fatedier/frp/pkg/util/net"
  23. )
  24. func init() {
  25. Register(v1.PluginHTTP2HTTPS, NewHTTP2HTTPSPlugin)
  26. }
  27. type HTTP2HTTPSPlugin struct {
  28. opts *v1.HTTP2HTTPSPluginOptions
  29. l *Listener
  30. s *http.Server
  31. }
  32. func NewHTTP2HTTPSPlugin(options v1.ClientPluginOptions) (Plugin, error) {
  33. opts := options.(*v1.HTTP2HTTPSPluginOptions)
  34. listener := NewProxyListener()
  35. p := &HTTP2HTTPSPlugin{
  36. opts: opts,
  37. l: listener,
  38. }
  39. tr := &http.Transport{
  40. TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
  41. }
  42. rp := &httputil.ReverseProxy{
  43. Director: func(req *http.Request) {
  44. req.URL.Scheme = "https"
  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. Transport: tr,
  54. }
  55. p.s = &http.Server{
  56. Handler: rp,
  57. ReadHeaderTimeout: 0,
  58. }
  59. go func() {
  60. _ = p.s.Serve(listener)
  61. }()
  62. return p, nil
  63. }
  64. func (p *HTTP2HTTPSPlugin) Handle(conn io.ReadWriteCloser, realConn net.Conn, _ *ExtraInfo) {
  65. wrapConn := utilnet.WrapReadWriteCloserToConn(conn, realConn)
  66. _ = p.l.PutConn(wrapConn)
  67. }
  68. func (p *HTTP2HTTPSPlugin) Name() string {
  69. return v1.PluginHTTP2HTTPS
  70. }
  71. func (p *HTTP2HTTPSPlugin) Close() error {
  72. return p.s.Close()
  73. }