// Copyright 2016 The CMux Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.

package cmux

import (
	
	
	
	
	
	

	
	
)

// Any is a Matcher that matches any connection.
func () Matcher {
	return func( io.Reader) bool { return true }
}

// PrefixMatcher returns a matcher that matches a connection if it
// starts with any of the strings in strs.
func ( ...string) Matcher {
	 := newPatriciaTreeString(...)
	return .matchPrefix
}

func prefixByteMatcher( ...[]byte) Matcher {
	 := newPatriciaTree(...)
	return .matchPrefix
}

var defaultHTTPMethods = []string{
	"OPTIONS",
	"GET",
	"HEAD",
	"POST",
	"PUT",
	"DELETE",
	"TRACE",
	"CONNECT",
}

// HTTP1Fast only matches the methods in the HTTP request.
//
// This matcher is very optimistic: if it returns true, it does not mean that
// the request is a valid HTTP response. If you want a correct but slower HTTP1
// matcher, use HTTP1 instead.
func ( ...string) Matcher {
	return PrefixMatcher(append(defaultHTTPMethods, ...)...)
}

// TLS matches HTTPS requests.
//
// By default, any TLS handshake packet is matched. An optional whitelist
// of versions can be passed in to restrict the matcher, for example:
//  TLS(tls.VersionTLS11, tls.VersionTLS12)
func ( ...int) Matcher {
	if len() == 0 {
		 = []int{
			tls.VersionSSL30,
			tls.VersionTLS10,
			tls.VersionTLS11,
			tls.VersionTLS12,
		}
	}
	 := [][]byte{}
	for ,  := range  {
		 = append(, []byte{22, byte( >> 8 & 0xff), byte( & 0xff)})
	}
	return prefixByteMatcher(...)
}

const maxHTTPRead = 4096

// HTTP1 parses the first line or upto 4096 bytes of the request to see if
// the conection contains an HTTP request.
func () Matcher {
	return func( io.Reader) bool {
		 := bufio.NewReader(&io.LimitedReader{R: , N: maxHTTPRead})
		, ,  := .ReadLine()
		if  != nil ||  {
			return false
		}

		, , ,  := parseRequestLine(string())
		if ! {
			return false
		}

		, ,  := http.ParseHTTPVersion()
		return  &&  == 1
	}
}

// grabbed from net/http.
func parseRequestLine( string) (, ,  string,  bool) {
	 := strings.Index(, " ")
	 := strings.Index([+1:], " ")
	if  < 0 ||  < 0 {
		return
	}
	 +=  + 1
	return [:], [+1 : ], [+1:], true
}

// HTTP2 parses the frame header of the first frame to detect whether the
// connection is an HTTP2 connection.
func () Matcher {
	return hasHTTP2Preface
}

// HTTP1HeaderField returns a matcher matching the header fields of the first
// request of an HTTP 1 connection.
func (,  string) Matcher {
	return func( io.Reader) bool {
		return matchHTTP1Field(, , func( string) bool {
			return  == 
		})
	}
}

// HTTP1HeaderFieldPrefix returns a matcher matching the header fields of the
// first request of an HTTP 1 connection. If the header with key name has a
// value prefixed with valuePrefix, this will match.
func (,  string) Matcher {
	return func( io.Reader) bool {
		return matchHTTP1Field(, , func( string) bool {
			return strings.HasPrefix(, )
		})
	}
}

// HTTP2HeaderField returns a matcher matching the header fields of the first
// headers frame.
func (,  string) Matcher {
	return func( io.Reader) bool {
		return matchHTTP2Field(ioutil.Discard, , , func( string) bool {
			return  == 
		})
	}
}

// HTTP2HeaderFieldPrefix returns a matcher matching the header fields of the
// first headers frame. If the header with key name has a value prefixed with
// valuePrefix, this will match.
func (,  string) Matcher {
	return func( io.Reader) bool {
		return matchHTTP2Field(ioutil.Discard, , , func( string) bool {
			return strings.HasPrefix(, )
		})
	}
}

// HTTP2MatchHeaderFieldSendSettings matches the header field and writes the
// settings to the server. Prefer HTTP2HeaderField over this one, if the client
// does not block on receiving a SETTING frame.
func (,  string) MatchWriter {
	return func( io.Writer,  io.Reader) bool {
		return matchHTTP2Field(, , , func( string) bool {
			return  == 
		})
	}
}

// HTTP2MatchHeaderFieldPrefixSendSettings matches the header field prefix
// and writes the settings to the server. Prefer HTTP2HeaderFieldPrefix over
// this one, if the client does not block on receiving a SETTING frame.
func (,  string) MatchWriter {
	return func( io.Writer,  io.Reader) bool {
		return matchHTTP2Field(, , , func( string) bool {
			return strings.HasPrefix(, )
		})
	}
}

func hasHTTP2Preface( io.Reader) bool {
	var  [len(http2.ClientPreface)]byte
	 := 0

	for {
		,  := .Read([:])
		if  != nil {
			return false
		}

		 += 
		 := string([:]) == http2.ClientPreface[:]
		if  == len(http2.ClientPreface) {
			return 
		}
		if ! {
			return false
		}
	}
}

func matchHTTP1Field( io.Reader,  string,  func(string) bool) ( bool) {
	,  := http.ReadRequest(bufio.NewReader())
	if  != nil {
		return false
	}

	return (.Header.Get())
}

func matchHTTP2Field( io.Writer,  io.Reader,  string,  func(string) bool) ( bool) {
	if !hasHTTP2Preface() {
		return false
	}

	 := false
	 := http2.NewFramer(, )
	 := hpack.NewDecoder(uint32(4<<10), func( hpack.HeaderField) {
		if .Name ==  {
			 = true
			if (.Value) {
				 = true
			}
		}
	})
	for {
		,  := .ReadFrame()
		if  != nil {
			return false
		}

		switch f := .(type) {
		case *http2.SettingsFrame:
			// Sender acknoweldged the SETTINGS frame. No need to write
			// SETTINGS again.
			if .IsAck() {
				break
			}
			if  := .WriteSettings();  != nil {
				return false
			}
		case *http2.ContinuationFrame:
			if ,  := .Write(.HeaderBlockFragment());  != nil {
				return false
			}
			 =  || .FrameHeader.Flags&http2.FlagHeadersEndHeaders != 0
		case *http2.HeadersFrame:
			if ,  := .Write(.HeaderBlockFragment());  != nil {
				return false
			}
			 =  || .FrameHeader.Flags&http2.FlagHeadersEndHeaders != 0
		}

		if  {
			return 
		}
	}
}