// Copyright 2010 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package req

import (
	
	
	
	
	
	
	

	
)

func isASCIILetter( byte) bool {
	 |= 0x20 // make lower case
	return 'a' <=  &&  <= 'z'
}

// TODO: This should be a distinguishable error (ErrMessageTooLarge)
// to allow mime/multipart to detect it.
var errMessageTooLarge = errors.New("message too large")

// A textprotoReader implements convenience methods for reading requests
// or responses from a text protocol network connection.
type textprotoReader struct {
	R        *bufio.Reader
	buf      []byte // a reusable buffer for readContinuedLineSlice
	readLine func() (line []byte, isPrefix bool, err error)
}

// NewReader returns a new textprotoReader reading from r.
//
// To avoid denial of service attacks, the provided bufio.Reader
// should be reading from an io.LimitReader or similar textprotoReader to bound
// the size of responses.
func newTextprotoReader( *bufio.Reader,  dump.Dumpers) *textprotoReader {
	commonHeaderOnce.Do(initCommonHeader)
	 := &textprotoReader{R: }

	if .ShouldDump() {
		.readLine = func() ( []byte,  bool,  error) {
			,  = .R.ReadSlice('\n')
			if len() == 0 {
				if  != nil {
					 = nil
				}
				return
			}
			 = nil
			.DumpResponseHeader()
			if [len()-1] == '\n' {
				 := 1
				if len() > 1 && [len()-2] == '\r' {
					 = 2
				}
				 = [:len()-]
			}
			return
		}
	} else {
		.readLine = .R.ReadLine
	}

	return 
}

// ReadLine reads a single line from r,
// eliding the final \n or \r\n from the returned string.
func ( *textprotoReader) () (string, error) {
	,  := .readLineSlice(-1)
	return string(), 
}

// readLineSlice reads a single line from r,
// up to lim bytes long (or unlimited if lim is less than 0),
// eliding the final \r or \r\n from the returned string.
func ( *textprotoReader) ( int64) ([]byte, error) {
	var  []byte

	for {
		, ,  := .readLine()
		if  != nil {
			return nil, 
		}
		if  >= 0 && int64(len())+int64(len()) >  {
			return nil, errMessageTooLarge
		}
		// Avoid the copy if the first call produced a full line.
		if  == nil && ! {
			return , nil
		}
		 = append(, ...)
		if ! {
			break
		}
	}
	return , nil
}

// trim returns s with leading and trailing spaces and tabs removed.
// It does not assume Unicode or UTF-8.
func trim( []byte) []byte {
	 := 0
	for  < len() && ([] == ' ' || [] == '\t') {
		++
	}
	 := len()
	for  >  && ([-1] == ' ' || [-1] == '\t') {
		--
	}
	return [:]
}

// readContinuedLineSlice reads continued lines from the reader buffer,
// returning a byte slice with all lines. The validateFirstLine function
// is run on the first read line, and if it returns an error then this
// error is returned from readContinuedLineSlice.
// It reads up to lim bytes of data (or unlimited if lim is less than 0).
func ( *textprotoReader) ( int64,  func([]byte) error) ([]byte, error) {
	if  == nil {
		return nil, fmt.Errorf("missing validateFirstLine func")
	}

	// Read the first line.
	,  := .readLineSlice()
	if  != nil {
		return nil, 
	}
	if len() == 0 { // blank line - no continuation
		return , nil
	}

	if  := ();  != nil {
		return nil, 
	}

	// Optimistically assume that we have started to buffer the next line
	// and it starts with an ASCII letter (the next header key), or a blank
	// line, so we can avoid copying that buffered data around in memory
	// and skipping over non-existent whitespace.
	if .R.Buffered() > 1 {
		,  := .R.Peek(2)
		if len() > 0 && (isASCIILetter([0]) || [0] == '\n') ||
			len() == 2 && [0] == '\r' && [1] == '\n' {
			return trim(), nil
		}
	}

	// ReadByte or the next readLineSlice will flush the read buffer;
	// copy the slice into buf.
	.buf = append(.buf[:0], trim()...)

	if  < 0 {
		 = math.MaxInt64
	}
	 -= int64(len(.buf))

	// Read continuation lines.
	for .skipSpace() > 0 {
		.buf = append(.buf, ' ')
		if int64(len(.buf)) >=  {
			return nil, errMessageTooLarge
		}
		,  := .readLineSlice( - int64(len(.buf)))
		if  != nil {
			break
		}
		.buf = append(.buf, trim()...)
	}
	return .buf, nil
}

// skipSpace skips R over all spaces and returns the number of bytes skipped.
func ( *textprotoReader) () int {
	 := 0
	for {
		,  := .R.ReadByte()
		if  != nil {
			// Bufio will keep err until next read.
			break
		}
		if  != ' ' &&  != '\t' {
			.R.UnreadByte()
			break
		}
		++
	}
	return 
}

// A protocolError describes a protocol violation such
// as an invalid response or a hung-up connection.
type protocolError string

func ( protocolError) () string {
	return string()
}

var colon = []byte(":")

// ReadMIMEHeader reads a MIME-style header from r.
// The header is a sequence of possibly continued Key: Value lines
// ending in a blank line.
// The returned map m maps [CanonicalMIMEHeaderKey](key) to a
// sequence of values in the same order encountered in the input.
//
// For example, consider this input:
//
//	My-Key: Value 1
//	Long-Key: Even
//	       Longer Value
//	My-Key: Value 2
//
// Given that input, ReadMIMEHeader returns the map:
//
//	map[string][]string{
//		"My-Key": {"Value 1", "Value 2"},
//		"Long-Key": {"Even Longer Value"},
//	}
func ( *textprotoReader) () (textproto.MIMEHeader, error) {
	return .readMIMEHeader(math.MaxInt64, math.MaxInt64)
}

// readMIMEHeader is a version of ReadMIMEHeader which takes a limit on the header size.
// It is called by the mime/multipart package.
func ( *textprotoReader) (,  int64) (textproto.MIMEHeader, error) {
	// Avoid lots of small slice allocations later by allocating one
	// large one ahead of time which we'll cut up into smaller
	// slices. If this isn't big enough later, we allocate small ones.
	var  []string
	 := .upcomingHeaderKeys()
	if  > 0 {
		if  > 1000 {
			 = 1000 // set a cap to avoid overallocation
		}
		 = make([]string, )
	}

	 := make(textproto.MIMEHeader, )

	// Account for 400 bytes of overhead for the MIMEHeader, plus 200 bytes per entry.
	// Benchmarking map creation as of go1.20, a one-entry MIMEHeader is 416 bytes and large
	// MIMEHeaders average about 200 bytes per entry.
	 -= 400
	const  = 200

	// The first line cannot start with a leading space.
	if ,  := .R.Peek(1);  == nil && ([0] == ' ' || [0] == '\t') {
		const  = 80 // arbitrary limit on how much of the line we'll quote
		,  := .readLineSlice()
		if  != nil {
			return , 
		}
		return , protocolError("malformed MIME header initial line: " + string())
	}

	for {
		,  := .readContinuedLineSlice(, mustHaveFieldNameColon)
		if len() == 0 {
			return , 
		}

		// Key ends at first colon.
		, ,  := bytes.Cut(, colon)
		if ! {
			return , protocolError("malformed MIME header line: " + string())
		}
		,  := canonicalMIMEHeaderKey()
		if ! {
			return , protocolError("malformed MIME header line: " + string())
		}
		for ,  := range  {
			if !validHeaderValueByte() {
				return , protocolError("malformed MIME header line: " + string())
			}
		}

		--
		if  < 0 {
			return nil, errMessageTooLarge
		}

		// Skip initial spaces in value.
		 := string(bytes.TrimLeft(, " \t"))

		 := []
		if  == nil {
			 -= int64(len())
			 -= 
		}
		 -= int64(len())
		if  < 0 {
			return , errMessageTooLarge
		}
		if  == nil && len() > 0 {
			// More than likely this will be a single-element key.
			// Most headers aren't multi-valued.
			// Set the capacity on strs[0] to 1, so any future append
			// won't extend the slice into the other strings.
			,  = [:1:1], [1:]
			[0] = 
			[] = 
		} else {
			[] = append(, )
		}

		if  != nil {
			return , 
		}
	}
}

// mustHaveFieldNameColon ensures that, per RFC 7230, the
// field-name is on a single line, so the first line must
// contain a colon.
func mustHaveFieldNameColon( []byte) error {
	if bytes.IndexByte(, ':') < 0 {
		return protocolError(fmt.Sprintf("malformed MIME header: missing colon: %q", ))
	}
	return nil
}

var nl = []byte("\n")

// upcomingHeaderKeys returns an approximation of the number of keys
// that will be in this header. If it gets confused, it returns 0.
func ( *textprotoReader) () ( int) {
	// Try to determine the 'hint' size.
	.R.Peek(1) // force a buffer load if empty
	 := .R.Buffered()
	if  == 0 {
		return
	}
	,  := .R.Peek()
	for len() > 0 &&  < 1000 {
		var  []byte
		, , _ = bytes.Cut(, nl)
		if len() == 0 || (len() == 1 && [0] == '\r') {
			// Blank line separating headers from the body.
			break
		}
		if [0] == ' ' || [0] == '\t' {
			// Folded continuation of the previous line.
			continue
		}
		++
	}
	return 
}

const toLower = 'a' - 'A'

// validHeaderFieldByte reports whether b is a valid byte in a header
// field name. RFC 7230 says:
//
//	header-field   = field-name ":" OWS field-value OWS
//	field-name     = token
//	tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" / "+" / "-" / "." /
//	        "^" / "_" / "`" / "|" / "~" / DIGIT / ALPHA
//	token = 1*tchar
func validHeaderFieldByte( byte) bool {
	return int() < len(isTokenTable) && isTokenTable[]
}

// canonicalMIMEHeaderKey is like CanonicalMIMEHeaderKey but is
// allowed to mutate the provided byte slice before returning the
// string.
//
// For invalid inputs (if a contains spaces or non-token bytes), a
// is unchanged and a string copy is returned.
//
// ok is true if the header key contains only valid characters and spaces.
// ReadMIMEHeader accepts header keys containing spaces, but does not
// canonicalize them.
func canonicalMIMEHeaderKey( []byte) ( string,  bool) {
	if len() == 0 {
		return "", false
	}

	// See if a looks like a header key. If not, return it unchanged.
	 := false
	for ,  := range  {
		if validHeaderFieldByte() {
			continue
		}
		// Don't canonicalize.
		if  == ' ' {
			// We accept invalid headers with a space before the
			// colon, but must not canonicalize them.
			// See https://go.dev/issue/34540.
			 = true
			continue
		}
		return string(), false
	}
	if  {
		return string(), true
	}

	 := true
	for ,  := range  {
		// Canonicalize: first letter upper case
		// and upper case after each dash.
		// (Host, User-Agent, If-Modified-Since).
		// MIME headers are ASCII only, so no Unicode issues.
		if  && 'a' <=  &&  <= 'z' {
			 -= toLower
		} else if ! && 'A' <=  &&  <= 'Z' {
			 += toLower
		}
		[] = 
		 =  == '-' // for next time
	}
	commonHeaderOnce.Do(initCommonHeader)
	// The compiler recognizes m[string(byteSlice)] as a special
	// case, so a copy of a's bytes into a new string does not
	// happen in this map lookup:
	if  := commonHeader[string()];  != "" {
		return , true
	}
	return string(), true
}

// validHeaderValueByte reports whether c is a valid byte in a header
// field value. RFC 7230 says:
//
//	field-content  = field-vchar [ 1*( SP / HTAB ) field-vchar ]
//	field-vchar    = VCHAR / obs-text
//	obs-text       = %x80-FF
//
// RFC 5234 says:
//
//	HTAB           =  %x09
//	SP             =  %x20
//	VCHAR          =  %x21-7E
func validHeaderValueByte( byte) bool {
	// mask is a 128-bit bitmap with 1s for allowed bytes,
	// so that the byte c can be tested with a shift and an and.
	// If c >= 128, then 1<<c and 1<<(c-64) will both be zero.
	// Since this is the obs-text range, we invert the mask to
	// create a bitmap with 1s for disallowed bytes.
	const  = 0 |
		(1<<(0x7f-0x21)-1)<<0x21 | // VCHAR: %x21-7E
		1<<0x20 | // SP: %x20
		1<<0x09 // HTAB: %x09
	return ((uint64(1)<<)&^(&(1<<64-1)) |
		(uint64(1)<<(-64))&^(>>64)) == 0
}

// commonHeader interns common header strings.
var commonHeader map[string]string

var commonHeaderOnce sync.Once

func initCommonHeader() {
	commonHeader = make(map[string]string)
	for ,  := range []string{
		"Accept",
		"Accept-Charset",
		"Accept-Encoding",
		"Accept-Language",
		"Accept-Ranges",
		"Cache-Control",
		"Cc",
		"Connection",
		"Content-Id",
		"Content-Language",
		"Content-Length",
		"Content-Transfer-Encoding",
		"Content-Type",
		"Cookie",
		"Date",
		"Dkim-Signature",
		"Etag",
		"Expires",
		"From",
		"Host",
		"If-Modified-Since",
		"If-None-Match",
		"In-Reply-To",
		"Last-Modified",
		"Location",
		"Message-Id",
		"Mime-Version",
		"Pragma",
		"Received",
		"Return-Path",
		"Server",
		"Set-Cookie",
		"Subject",
		"To",
		"User-Agent",
		"Via",
		"X-Forwarded-For",
		"X-Imforwards",
		"X-Powered-By",
	} {
		commonHeader[] = 
	}
}

// isTokenTable is a copy of net/http/lex.go's isTokenTable.
// See https://httpwg.github.io/specs/rfc7230.html#rule.token.separators
var isTokenTable = [127]bool{
	'!':  true,
	'#':  true,
	'$':  true,
	'%':  true,
	'&':  true,
	'\'': true,
	'*':  true,
	'+':  true,
	'-':  true,
	'.':  true,
	'0':  true,
	'1':  true,
	'2':  true,
	'3':  true,
	'4':  true,
	'5':  true,
	'6':  true,
	'7':  true,
	'8':  true,
	'9':  true,
	'A':  true,
	'B':  true,
	'C':  true,
	'D':  true,
	'E':  true,
	'F':  true,
	'G':  true,
	'H':  true,
	'I':  true,
	'J':  true,
	'K':  true,
	'L':  true,
	'M':  true,
	'N':  true,
	'O':  true,
	'P':  true,
	'Q':  true,
	'R':  true,
	'S':  true,
	'T':  true,
	'U':  true,
	'W':  true,
	'V':  true,
	'X':  true,
	'Y':  true,
	'Z':  true,
	'^':  true,
	'_':  true,
	'`':  true,
	'a':  true,
	'b':  true,
	'c':  true,
	'd':  true,
	'e':  true,
	'f':  true,
	'g':  true,
	'h':  true,
	'i':  true,
	'j':  true,
	'k':  true,
	'l':  true,
	'm':  true,
	'n':  true,
	'o':  true,
	'p':  true,
	'q':  true,
	'r':  true,
	's':  true,
	't':  true,
	'u':  true,
	'v':  true,
	'w':  true,
	'x':  true,
	'y':  true,
	'z':  true,
	'|':  true,
	'~':  true,
}