tls.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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. "time"
  19. gnet "github.com/fatedier/golib/net"
  20. )
  21. var (
  22. FRP_TLS_HEAD_BYTE = 0x17
  23. )
  24. func WrapTLSClientConn(c net.Conn, tlsConfig *tls.Config) (out net.Conn) {
  25. c.Write([]byte{byte(FRP_TLS_HEAD_BYTE)})
  26. out = tls.Client(c, tlsConfig)
  27. return
  28. }
  29. func CheckAndEnableTLSServerConnWithTimeout(c net.Conn, tlsConfig *tls.Config, timeout time.Duration) (out net.Conn, err error) {
  30. sc, r := gnet.NewSharedConnSize(c, 2)
  31. buf := make([]byte, 1)
  32. var n int
  33. c.SetReadDeadline(time.Now().Add(timeout))
  34. n, err = r.Read(buf)
  35. c.SetReadDeadline(time.Time{})
  36. if err != nil {
  37. return
  38. }
  39. if n == 1 && int(buf[0]) == FRP_TLS_HEAD_BYTE {
  40. out = tls.Server(c, tlsConfig)
  41. } else {
  42. out = sc
  43. }
  44. return
  45. }