| 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 | |
| 15 | package net |
| 16 | |
| 17 | import ( |
| 18 | "crypto/tls" |
| 19 | "fmt" |
| 20 | "net" |
| 21 | "time" |
| 22 | |
| 23 | libnet "github.com/fatedier/golib/net" |
| 24 | ) |
| 25 | |
| 26 | var FRPTLSHeadByte = 0x17 |
| 27 | |
| 28 | func CheckAndEnableTLSServerConnWithTimeout( |
| 29 | c net.Conn, tlsConfig *tls.Config, tlsOnly bool, timeout time.Duration, |
| 30 | ) (out net.Conn, isTLS bool, custom bool, err error) { |
| 31 | sc, r := libnet.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 | |
| 41 | switch { |
| 42 | case n == 1 && int(buf[0]) == FRPTLSHeadByte: |
| 43 | out = tls.Server(c, tlsConfig) |
| 44 | isTLS = true |
| 45 | custom = true |
| 46 | case n == 1 && int(buf[0]) == 0x16: |
| 47 | out = tls.Server(sc, tlsConfig) |
| 48 | isTLS = true |
| 49 | default: |
| 50 | if tlsOnly { |
| 51 | err = fmt.Errorf("non-TLS connection received on a TlsOnly server") |
| 52 | return |
| 53 | } |
| 54 | out = sc |
| 55 | } |
| 56 | return |
| 57 | } |