tls2raw.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. "crypto/tls"
  19. "io"
  20. "net"
  21. libio "github.com/fatedier/golib/io"
  22. v1 "github.com/fatedier/frp/pkg/config/v1"
  23. "github.com/fatedier/frp/pkg/transport"
  24. netpkg "github.com/fatedier/frp/pkg/util/net"
  25. "github.com/fatedier/frp/pkg/util/xlog"
  26. )
  27. func init() {
  28. Register(v1.PluginTLS2Raw, NewTLS2RawPlugin)
  29. }
  30. type TLS2RawPlugin struct {
  31. opts *v1.TLS2RawPluginOptions
  32. tlsConfig *tls.Config
  33. }
  34. func NewTLS2RawPlugin(options v1.ClientPluginOptions) (Plugin, error) {
  35. opts := options.(*v1.TLS2RawPluginOptions)
  36. p := &TLS2RawPlugin{
  37. opts: opts,
  38. }
  39. tlsConfig, err := transport.NewServerTLSConfig(p.opts.CrtPath, p.opts.KeyPath, "")
  40. if err != nil {
  41. return nil, err
  42. }
  43. p.tlsConfig = tlsConfig
  44. return p, nil
  45. }
  46. func (p *TLS2RawPlugin) Handle(ctx context.Context, conn io.ReadWriteCloser, realConn net.Conn, _ *ExtraInfo) {
  47. xl := xlog.FromContextSafe(ctx)
  48. wrapConn := netpkg.WrapReadWriteCloserToConn(conn, realConn)
  49. tlsConn := tls.Server(wrapConn, p.tlsConfig)
  50. if err := tlsConn.Handshake(); err != nil {
  51. xl.Warnf("tls handshake error: %v", err)
  52. return
  53. }
  54. rawConn, err := net.Dial("tcp", p.opts.LocalAddr)
  55. if err != nil {
  56. xl.Warnf("dial to local addr error: %v", err)
  57. return
  58. }
  59. libio.Join(tlsConn, rawConn)
  60. }
  61. func (p *TLS2RawPlugin) Name() string {
  62. return v1.PluginTLS2Raw
  63. }
  64. func (p *TLS2RawPlugin) Close() error {
  65. return nil
  66. }