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