tls.go 1.4 KB

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