tls.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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 net
  15. import (
  16. "crypto/tls"
  17. "net"
  18. gnet "github.com/fatedier/golib/net"
  19. )
  20. var (
  21. FRP_TLS_HEAD_BYTE = 0x17
  22. )
  23. func WrapTLSClientConn(c net.Conn, tlsConfig *tls.Config) (out Conn) {
  24. c.Write([]byte{byte(FRP_TLS_HEAD_BYTE)})
  25. out = WrapConn(tls.Client(c, tlsConfig))
  26. return
  27. }
  28. func CheckAndEnableTLSServerConn(c net.Conn, tlsConfig *tls.Config) (out Conn) {
  29. sc, r := gnet.NewSharedConnSize(c, 1)
  30. buf := make([]byte, 1)
  31. n, _ := r.Read(buf)
  32. if n == 1 && int(buf[0]) == FRP_TLS_HEAD_BYTE {
  33. out = WrapConn(tls.Server(c, tlsConfig))
  34. } else {
  35. out = WrapConn(sc)
  36. }
  37. return
  38. }