tls.go 1.4 KB

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