vitess.io/vitess@v0.16.2/go/vt/grpcoptionaltls/tls_detector.go (about) 1 /* 2 Copyright 2019 The Vitess Authors. 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 grpcoptionaltls 16 17 import "io" 18 19 const TLSPeekedBytes = 6 20 21 func looksLikeTLS(bytes []byte) bool { 22 if len(bytes) < TLSPeekedBytes { 23 return false 24 } 25 // TLS starts as 26 // 0: 0x16 - handshake protocol magic 27 // 1: 0x03 - SSL version major 28 // 2: 0x00 to 0x03 - SSL version minor (SSLv3 or TLS1.0 through TLS1.3) 29 // 3-4: length (2 bytes) 30 // 5: 0x01 - handshake type (ClientHello) 31 // 6-8: handshake len (3 bytes), equals value from offset 3-4 minus 4 32 // HTTP2 initial frame bytes 33 // https://tools.ietf.org/html/rfc7540#section-3.4 34 35 // Definitely not TLS 36 if bytes[0] != 0x16 || bytes[1] != 0x03 || bytes[5] != 0x01 { 37 return false 38 } 39 return true 40 } 41 42 // DetectTLS reads necessary number of bytes from io.Reader 43 // returns result, bytes read from Reader and error 44 // No matter if error happens or what flag value is 45 // returned bytes should be checked 46 func DetectTLS(r io.Reader) (bool, []byte, error) { 47 var bytes = make([]byte, TLSPeekedBytes) 48 if n, err := io.ReadFull(r, bytes); err != nil { 49 return false, bytes[:n], err 50 } 51 return looksLikeTLS(bytes), bytes, nil 52 }