package pgconn

import (
	
	
	
	
)

// This file parses PostgreSQL connection URIs using a parser designed to
// exactly match libpq's URI parser behavior (conninfo_uri_parse_options,
// conninfo_uri_parse_params, and conninfo_uri_decode in
// src/interfaces/libpq/fe-connect.c), so that pgx accepts and rejects exactly
// the same URIs as libpq, including libpq's multiple-host extension
// (postgresql://host1:port1,host2:port2/db), which is not valid RFC 3986 syntax.
//
// Deliberate differences from libpq:
//
//   - Query parameters that libpq does not recognize are accepted. They become
//     runtime parameters or pgx-specific options (e.g. pool_max_conns) instead
//     of failing the parse.
//   - Error messages avoid quoting the unredacted connection string and mask
//     recognizable password fields on a best-effort basis. Invalid connection
//     strings can be structurally ambiguous, so password redaction cannot be
//     guaranteed for every malformed input. libpq quotes the failing input
//     verbatim, which can leak a password into error messages and logs.
//   - Literal NUL bytes are rejected. libpq never sees them because C strings
//     end at the first NUL; a Go string can carry one into the startup packet,
//     where it would act as a protocol delimiter and inject extra parameters.

// parseURLMeta reports provenance facts about a parsed URI that
// ParseConfigWithOptions needs for ConnStringAllowedKeys validation and that
// cannot be recovered from the settings map itself.
type parseURLMeta struct {
	// impliedEmptyPortList: the "port" entry is an all-empty list synthesized
	// from the host list (postgres://h1,h2 yields port=",") with no port
	// bytes supplied by the user. Determined from the raw port syntax, not
	// the decoded value: a port of literal spaces (postgres://h: /db)
	// decodes to empty but was user-supplied.
	impliedEmptyPortList bool
	// sawRawSSLKey / sawSSLTrueAlias / sawExplicitSSLModeKey record which
	// spellings of the ssl and sslmode query keys appeared anywhere in the
	// URI -- including occurrences later superseded under last-occurrence-
	// wins. The ssl=true alias rewrite and ordinary repeated-key handling can
	// remove those occurrences from the final settings map, so
	// ConnStringAllowedKeys cannot fail closed from that map alone; it must see
	// every key the user actually wrote.
	sawRawSSLKey          bool // key "ssl" with a value other than "true"
	sawSSLTrueAlias       bool // key "ssl" with value "true" (stored as sslmode=require)
	sawExplicitSSLModeKey bool // key "sslmode"
}

// parseURLSettings parses a connection URI into a settings map. connString
// must start with "postgres://" or "postgresql://".
//
// Multiple hosts are represented in the returned map the same way libpq
// represents them internally: settings["host"] and settings["port"] are
// comma-separated lists that are positionally aligned, with empty elements
// meaning "use the default". The lists are split in ParseConfigWithOptions.
func ( string) ( map[string]string,  parseURLMeta,  error) {
	 = make(map[string]string)

	if strings.IndexByte(, 0) >= 0 {
		return nil, , errors.New("forbidden NUL byte in connection string")
	}

	,  := strings.CutPrefix(, "postgresql://")
	if ! {
		,  = strings.CutPrefix(, "postgres://")
	}
	if ! {
		return nil, , errors.New("invalid URI propagated to internal parser routine")
	}

	// Look ahead for a possible user credentials designator. Like libpq, only
	// a '/' stops the search, so a '@' anywhere before the path -- even inside
	// what looks like a query string -- is treated as the userinfo terminator.
	if  := strings.IndexAny(, "@/");  >= 0 && [] == '@' {
		, ,  := strings.Cut([:], ":")
		 = [+1:]
		if  != "" {
			,  := uriDecode(, "")
			if  != nil {
				return nil, , 
			}
			["user"] = 
		}
		if  &&  != "" {
			,  := uriDecode(, "password")
			if  != nil {
				return nil, , 
			}
			["password"] = 
		}
	}

	// Parse the comma-separated list of netloc[:port] specifications. Hosts
	// and ports accumulate into positionally aligned comma-joined lists: every
	// separator appends a comma to both, so postgres://h1,h2:5433 yields
	// host="h1,h2" port=",5433".
	var ,  strings.Builder

	for {
		if peekByte() == '[' {
			// IPv6 address. The bracket contents are not validated, matching libpq.
			 := strings.IndexByte(, ']')
			if  < 0 {
				return nil, , errors.New(`end of string reached when looking for matching "]" in IPv6 host address in URI`)
			}
			if  == 1 {
				return nil, , errors.New("IPv6 host address may not be empty in URI")
			}
			.WriteString([1:])
			 = [+1:]
			if  := peekByte();  != 0 &&  != ':' &&  != '/' &&  != '?' &&  != ',' {
				return nil, , fmt.Errorf(`unexpected character "%c" at position %d in URI (expected ":" or "/")`, , len()-len()+1)
			}
		} else {
			// DNS-named or IPv4 netloc: everything up to a ':', '/', '?', or ','.
			 := strings.IndexAny(, ":/?,")
			if  < 0 {
				 = len()
			}
			.WriteString([:])
			 = [:]
		}

		if peekByte() == ':' {
			 = [1:]
			 := strings.IndexAny(, "/?,")
			if  < 0 {
				 = len()
			}
			.WriteString([:])
			 = [:]
		}

		if peekByte() != ',' {
			break
		}
		 = [1:]
		.WriteByte(',')
		.WriteByte(',')
	}

	// The joined lists are percent-decoded as a unit, after joining. This
	// means %2C decodes to a comma that later splits like a real separator --
	// a host name containing a literal comma is inexpressible, as in libpq.
	if .Len() > 0 {
		,  := uriDecode(.String(), "")
		if  != nil {
			return nil, , 
		}
		["host"] = 
	}
	// Like libpq, the port list is stored even when every element is empty
	// (postgres://h1,h2 yields port=","). This matters: a connection string
	// port shadows PGPORT during settings merge, so with PGPORT=1,2 a
	// three-host URI without ports must use the default port for every host,
	// not fail the port/host count check. Such an implied all-empty list
	// carries no user-supplied port text, which is what
	// meta.impliedEmptyPortList reports -- judged on the raw bytes, before
	// percent-decoding trims spaces, so a port the user actually typed never
	// counts as implied even when it decodes to empty.
	if .Len() > 0 {
		.impliedEmptyPortList = strings.Trim(.String(), ",") == ""
		,  := uriDecode(.String(), "")
		if  != nil {
			return nil, , 
		}
		["port"] = 
	}

	if peekByte() == '/' {
		 = [1:]
		 := 
		 = ""
		if  := strings.IndexByte(, '?');  >= 0 {
			 = [:]
			 = [:]
		}
		// Like libpq, an empty path component leaves dbname unset so the
		// default stays in effect.
		if  != "" {
			,  := uriDecode(, "")
			if  != nil {
				return nil, , 
			}
			["database"] = 
		}
	}

	if peekByte() == '?' {
		// Query parameters land in their own map first: an explicit ?port=
		// overrides the netloc-derived port list and is user-supplied port
		// text, so it cancels the implied-list exemption even when its value
		// is empty.
		 := make(map[string]string)
		if  := parseURLQueryParams([1:], , &);  != nil {
			return nil, , 
		}
		if ,  := ["port"];  {
			.impliedEmptyPortList = false
		}
		maps.Copy(, )
	}

	return , , nil
}

// peekByte returns the first byte of s, or 0 if s is empty. A NUL byte is a
// safe end-of-input sentinel because parseURLSettings rejects literal NULs.
func ( string) byte {
	if len() == 0 {
		return 0
	}
	return [0]
}

// parseURLQueryParams parses the query part of a connection URI into settings,
// mirroring libpq's conninfo_uri_parse_params: '&'-separated pairs, exactly
// one raw '=' per pair, both halves percent-decoded, last occurrence wins. It
// records in meta which spellings of the ssl/sslmode keys it saw (see
// parseURLMeta).
func ( string,  map[string]string,  *parseURLMeta) error {
	// sslWasLast records whether ssl or sslmode was encountered most recently.
	// This matters if the final repeated ssl value is "true": the alias wins
	// only when it occurs after the final explicit sslmode.
	 := false

	for  != "" {
		 := 
		if  := strings.IndexByte(, '&');  >= 0 {
			 = [:]
			 = [+1:]
		} else {
			 = ""
		}

		, ,  := strings.Cut(, "=")
		if ! {
			return fmt.Errorf(`missing key/value separator "=" in URI query parameter: "%s"`, )
		}
		if strings.IndexByte(, '=') >= 0 {
			return fmt.Errorf(`extra key/value separator "=" in URI query parameter: "%s"`, )
		}

		,  := uriDecode(, "")
		if  != nil {
			return 
		}
		 = canonicalConnStringKey()

		 := ""
		if  == "password" ||  == "sslpassword" {
			 = 
		}
		,  := uriDecode(, )
		if  != nil {
			return 
		}

		// Resolve repeated ssl values under their raw key before applying the
		// JDBC compatibility alias. Otherwise ssl=true would overwrite an
		// independent explicit sslmode that must reappear if a later ssl value
		// supersedes the alias. The alias is URI-only and applies only to the
		// literal value "true".
		switch  {
		case "ssl":
			 = true
			if  == "true" {
				.sawSSLTrueAlias = true
			} else {
				.sawRawSSLKey = true
			}
		case "sslmode":
			 = false
			.sawExplicitSSLModeKey = true
		}

		[] = 
	}

	if ,  := ["ssl"];  &&  == "true" {
		delete(, "ssl")
		if  {
			["sslmode"] = "require"
		}
	}

	return nil
}

// uriDecode percent-decodes a URI component with the same rules as libpq's
// conninfo_uri_decode: '%' followed by exactly two case-insensitive hex
// digits, %00 forbidden, leading and trailing ASCII spaces skipped, interior
// spaces rejected. Decoded bytes are emitted raw with no character set
// validation.
//
// If secretName is non-empty, error messages identify that component by name
// instead of quoting its raw value. This prevents the known component's raw
// contents from being copied into the decode error; it does not make the
// separate, best-effort redaction of an invalid connection string complete.
func (,  string) (string, error) {
	// The component may be a secret; every error must be built by fail so the
	// quote-the-raw-value-or-not redaction decision lives in exactly one place.
	 := func(,  string) (string, error) {
		if  != "" {
			return "", fmt.Errorf(, )
		}
		return "", fmt.Errorf(, )
	}

	var  strings.Builder
	.Grow(len())

	 := 0
	for  < len() && [] == ' ' {
		++
	}
	for  < len() && [] != ' ' {
		if [] != '%' {
			.WriteByte([])
			++
			continue
		}

		var ,  byte
		var ,  bool
		if +1 < len() {
			,  = hexDigit([+1])
		}
		if +2 < len() {
			,  = hexDigit([+2])
		}
		if ! || ! {
			return ("invalid percent-encoded token in %s", `invalid percent-encoded token: "%s"`)
		}

		 := <<4 | 
		if  == 0 {
			return ("forbidden value %%00 in percent-encoded value in %s", `forbidden value %%00 in percent-encoded value: "%s"`)
		}
		.WriteByte()
		 += 3
	}
	for  < len() && [] == ' ' {
		++
	}
	if  < len() {
		return ("unexpected spaces found in %s, use percent-encoded spaces (%%20) instead", `unexpected spaces found in "%s", use percent-encoded spaces (%%20) instead`)
	}

	return .String(), nil
}

// uriDecodeLenient is a non-failing variant of uriDecode used for best-effort
// redaction: valid percent-encodings are decoded, anything uriDecode would
// reject passes through unchanged. Redaction processing itself must not fail,
// and it must see the same key spelling the parser would (pass%77ord decodes
// to password), so encoded password keys are recognized even in connection
// strings that do not parse. This helps recognize keys but cannot make
// redaction complete when malformed input has ambiguous component boundaries.
func ( string) string {
	 = strings.Trim(, " ")

	var  strings.Builder
	.Grow(len())

	for  := 0;  < len(); {
		if [] == '%' && +2 < len() {
			,  := hexDigit([+1])
			,  := hexDigit([+2])
			if  &&  {
				.WriteByte(<<4 | )
				 += 3
				continue
			}
		}
		.WriteByte([])
		++
	}

	return .String()
}

func ( byte) (byte, bool) {
	switch {
	case  >= '0' &&  <= '9':
		return  - '0', true
	case  >= 'A' &&  <= 'F':
		return  - 'A' + 10, true
	case  >= 'a' &&  <= 'f':
		return  - 'a' + 10, true
	}
	return 0, false
}