1
0

tls.go 1.6 KB

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