Source file src/net/url/url.go

     1  // Copyright 2009 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Package url parses URLs and implements query escaping.
     6  //
     7  // See RFC 3986. This package generally follows RFC 3986, except where
     8  // it deviates for compatibility reasons.
     9  // RFC 6874 followed for IPv6 zone literals.
    10  
    11  //go:generate go run gen_encoding_table.go
    12  
    13  package url
    14  
    15  // When sending changes, first  search old issues for history on decisions.
    16  // Unit tests should also contain references to issue numbers with details.
    17  
    18  import (
    19  	"errors"
    20  	"fmt"
    21  	"internal/godebug"
    22  	"net/netip"
    23  	"path"
    24  	"slices"
    25  	"strconv"
    26  	"strings"
    27  	_ "unsafe" // for linkname
    28  )
    29  
    30  var urlstrictcolons = godebug.New("urlstrictcolons")
    31  
    32  // Error reports an error and the operation and URL that caused it.
    33  type Error struct {
    34  	Op  string
    35  	URL string
    36  	Err error
    37  }
    38  
    39  func (e *Error) Unwrap() error { return e.Err }
    40  func (e *Error) Error() string { return fmt.Sprintf("%s %q: %s", e.Op, e.URL, e.Err) }
    41  
    42  func (e *Error) Timeout() bool {
    43  	t, ok := e.Err.(interface {
    44  		Timeout() bool
    45  	})
    46  	return ok && t.Timeout()
    47  }
    48  
    49  func (e *Error) Temporary() bool {
    50  	t, ok := e.Err.(interface {
    51  		Temporary() bool
    52  	})
    53  	return ok && t.Temporary()
    54  }
    55  
    56  const upperhex = "0123456789ABCDEF"
    57  
    58  func ishex(c byte) bool {
    59  	return table[c]&hexChar != 0
    60  }
    61  
    62  // Precondition: ishex(c) is true.
    63  func unhex(c byte) byte {
    64  	return 9*(c>>6) + (c & 15)
    65  }
    66  
    67  type EscapeError string
    68  
    69  func (e EscapeError) Error() string {
    70  	return "invalid URL escape " + strconv.Quote(string(e))
    71  }
    72  
    73  type InvalidHostError string
    74  
    75  func (e InvalidHostError) Error() string {
    76  	return "invalid character " + strconv.Quote(string(e)) + " in host name"
    77  }
    78  
    79  // See the reference implementation in gen_encoding_table.go.
    80  func shouldEscape(c byte, mode encoding) bool {
    81  	return table[c]&mode == 0
    82  }
    83  
    84  // QueryUnescape does the inverse transformation of [QueryEscape],
    85  // converting each 3-byte encoded substring of the form "%AB" into the
    86  // hex-decoded byte 0xAB.
    87  // It returns an error if any % is not followed by two hexadecimal
    88  // digits.
    89  func QueryUnescape(s string) (string, error) {
    90  	return unescape(s, encodeQueryComponent)
    91  }
    92  
    93  // PathUnescape does the inverse transformation of [PathEscape],
    94  // converting each 3-byte encoded substring of the form "%AB" into the
    95  // hex-decoded byte 0xAB. It returns an error if any % is not followed
    96  // by two hexadecimal digits.
    97  //
    98  // PathUnescape is identical to [QueryUnescape] except that it does not
    99  // unescape '+' to ' ' (space).
   100  func PathUnescape(s string) (string, error) {
   101  	return unescape(s, encodePathSegment)
   102  }
   103  
   104  // unescape unescapes a string; the mode specifies
   105  // which section of the URL string is being unescaped.
   106  func unescape(s string, mode encoding) (string, error) {
   107  	// Count %, check that they're well-formed.
   108  	n := 0
   109  	hasPlus := false
   110  	for i := 0; i < len(s); {
   111  		switch s[i] {
   112  		case '%':
   113  			n++
   114  			if i+2 >= len(s) || !ishex(s[i+1]) || !ishex(s[i+2]) {
   115  				s = s[i:]
   116  				if len(s) > 3 {
   117  					s = s[:3]
   118  				}
   119  				return "", EscapeError(s)
   120  			}
   121  			// Per https://tools.ietf.org/html/rfc3986#page-21
   122  			// in the host component %-encoding can only be used
   123  			// for non-ASCII bytes.
   124  			// But https://tools.ietf.org/html/rfc6874#section-2
   125  			// introduces %25 being allowed to escape a percent sign
   126  			// in IPv6 scoped-address literals. Yay.
   127  			if mode == encodeHost && unhex(s[i+1]) < 8 && s[i:i+3] != "%25" {
   128  				return "", EscapeError(s[i : i+3])
   129  			}
   130  			if mode == encodeZone {
   131  				// RFC 6874 says basically "anything goes" for zone identifiers
   132  				// and that even non-ASCII can be redundantly escaped,
   133  				// but it seems prudent to restrict %-escaped bytes here to those
   134  				// that are valid host name bytes in their unescaped form.
   135  				// That is, you can use escaping in the zone identifier but not
   136  				// to introduce bytes you couldn't just write directly.
   137  				// But Windows puts spaces here! Yay.
   138  				v := unhex(s[i+1])<<4 | unhex(s[i+2])
   139  				if s[i:i+3] != "%25" && v != ' ' && shouldEscape(v, encodeHost) {
   140  					return "", EscapeError(s[i : i+3])
   141  				}
   142  			}
   143  			i += 3
   144  		case '+':
   145  			hasPlus = mode == encodeQueryComponent
   146  			i++
   147  		default:
   148  			if (mode == encodeHost || mode == encodeZone) && s[i] < 0x80 && shouldEscape(s[i], mode) {
   149  				return "", InvalidHostError(s[i : i+1])
   150  			}
   151  			i++
   152  		}
   153  	}
   154  
   155  	if n == 0 && !hasPlus {
   156  		return s, nil
   157  	}
   158  
   159  	var unescapedPlusSign byte
   160  	switch mode {
   161  	case encodeQueryComponent:
   162  		unescapedPlusSign = ' '
   163  	default:
   164  		unescapedPlusSign = '+'
   165  	}
   166  	var t strings.Builder
   167  	t.Grow(len(s) - 2*n)
   168  	for i := 0; i < len(s); i++ {
   169  		switch s[i] {
   170  		case '%':
   171  			// In the loop above, we established that unhex's precondition is
   172  			// fulfilled for both s[i+1] and s[i+2].
   173  			t.WriteByte(unhex(s[i+1])<<4 | unhex(s[i+2]))
   174  			i += 2
   175  		case '+':
   176  			t.WriteByte(unescapedPlusSign)
   177  		default:
   178  			t.WriteByte(s[i])
   179  		}
   180  	}
   181  	return t.String(), nil
   182  }
   183  
   184  // QueryEscape escapes the string so it can be safely placed
   185  // inside a [URL] query.
   186  func QueryEscape(s string) string {
   187  	return escape(s, encodeQueryComponent)
   188  }
   189  
   190  // PathEscape escapes the string so it can be safely placed inside a [URL] path segment,
   191  // replacing special characters (including /) with %XX sequences as needed.
   192  func PathEscape(s string) string {
   193  	return escape(s, encodePathSegment)
   194  }
   195  
   196  func escape(s string, mode encoding) string {
   197  	spaceCount, hexCount := 0, 0
   198  	for _, c := range []byte(s) {
   199  		if shouldEscape(c, mode) {
   200  			if c == ' ' && mode == encodeQueryComponent {
   201  				spaceCount++
   202  			} else {
   203  				hexCount++
   204  			}
   205  		}
   206  	}
   207  
   208  	if spaceCount == 0 && hexCount == 0 {
   209  		return s
   210  	}
   211  
   212  	var buf [64]byte
   213  	var t []byte
   214  
   215  	required := len(s) + 2*hexCount
   216  	if required <= len(buf) {
   217  		t = buf[:required]
   218  	} else {
   219  		t = make([]byte, required)
   220  	}
   221  
   222  	if hexCount == 0 {
   223  		copy(t, s)
   224  		for i := 0; i < len(s); i++ {
   225  			if s[i] == ' ' {
   226  				t[i] = '+'
   227  			}
   228  		}
   229  		return string(t)
   230  	}
   231  
   232  	j := 0
   233  	for _, c := range []byte(s) {
   234  		switch {
   235  		case c == ' ' && mode == encodeQueryComponent:
   236  			t[j] = '+'
   237  			j++
   238  		case shouldEscape(c, mode):
   239  			t[j] = '%'
   240  			t[j+1] = upperhex[c>>4]
   241  			t[j+2] = upperhex[c&15]
   242  			j += 3
   243  		default:
   244  			t[j] = c
   245  			j++
   246  		}
   247  	}
   248  	return string(t)
   249  }
   250  
   251  // A URL represents a parsed URL (technically, a URI reference).
   252  //
   253  // The general form represented is:
   254  //
   255  //	[scheme:][//[userinfo@]host][/]path[?query][#fragment]
   256  //
   257  // URLs that do not start with a slash after the scheme are interpreted as:
   258  //
   259  //	scheme:opaque[?query][#fragment]
   260  //
   261  // The Host field contains the host and port subcomponents of the URL.
   262  // When the port is present, it is separated from the host with a colon.
   263  // When the host is an IPv6 address, it must be enclosed in square brackets:
   264  // "[fe80::1]:80". The [net.JoinHostPort] function combines a host and port
   265  // into a string suitable for the Host field, adding square brackets to
   266  // the host when necessary.
   267  //
   268  // Note that the Path field is stored in decoded form: /%47%6f%2f becomes /Go/.
   269  // A consequence is that it is impossible to tell which slashes in the Path were
   270  // slashes in the raw URL and which were %2f. This distinction is rarely important,
   271  // but when it is, the code should use the [URL.EscapedPath] method, which preserves
   272  // the original encoding of Path. The Fragment field is also stored in decoded form,
   273  // use [URL.EscapedFragment] to retrieve the original encoding.
   274  //
   275  // The [URL.String] method uses the [URL.EscapedPath] method to obtain the path.
   276  type URL struct {
   277  	Scheme   string
   278  	Opaque   string    // encoded opaque data
   279  	User     *Userinfo // username and password information
   280  	Host     string    // "host" or "host:port" (see Hostname and Port methods)
   281  	Path     string    // path (relative paths may omit leading slash)
   282  	Fragment string    // fragment for references (without '#')
   283  
   284  	// RawQuery contains the encoded query values, without the initial '?'.
   285  	// Use URL.Query to decode the query.
   286  	RawQuery string
   287  
   288  	// RawPath is an optional field containing an encoded path hint.
   289  	// See the EscapedPath method for more details.
   290  	//
   291  	// In general, code should call EscapedPath instead of reading RawPath.
   292  	RawPath string
   293  
   294  	// RawFragment is an optional field containing an encoded fragment hint.
   295  	// See the EscapedFragment method for more details.
   296  	//
   297  	// In general, code should call EscapedFragment instead of reading RawFragment.
   298  	RawFragment string
   299  
   300  	// ForceQuery indicates whether the original URL contained a query ('?') character.
   301  	// When set, the String method will include a trailing '?', even when RawQuery is empty.
   302  	ForceQuery bool
   303  
   304  	// OmitHost indicates the URL has an empty host (authority).
   305  	// When set, the String method will not include the host when it is empty.
   306  	OmitHost bool
   307  }
   308  
   309  // User returns a [Userinfo] containing the provided username
   310  // and no password set.
   311  func User(username string) *Userinfo {
   312  	return &Userinfo{username, "", false}
   313  }
   314  
   315  // UserPassword returns a [Userinfo] containing the provided username
   316  // and password.
   317  //
   318  // This functionality should only be used with legacy web sites.
   319  // RFC 2396 warns that interpreting Userinfo this way
   320  // “is NOT RECOMMENDED, because the passing of authentication
   321  // information in clear text (such as URI) has proven to be a
   322  // security risk in almost every case where it has been used.”
   323  func UserPassword(username, password string) *Userinfo {
   324  	return &Userinfo{username, password, true}
   325  }
   326  
   327  // The Userinfo type is an immutable encapsulation of username and
   328  // password details for a [URL]. An existing Userinfo value is guaranteed
   329  // to have a username set (potentially empty, as allowed by RFC 2396),
   330  // and optionally a password.
   331  type Userinfo struct {
   332  	username    string
   333  	password    string
   334  	passwordSet bool
   335  }
   336  
   337  // Username returns the username.
   338  func (u *Userinfo) Username() string {
   339  	if u == nil {
   340  		return ""
   341  	}
   342  	return u.username
   343  }
   344  
   345  // Password returns the password in case it is set, and whether it is set.
   346  func (u *Userinfo) Password() (string, bool) {
   347  	if u == nil {
   348  		return "", false
   349  	}
   350  	return u.password, u.passwordSet
   351  }
   352  
   353  // String returns the encoded userinfo information in the standard form
   354  // of "username[:password]".
   355  func (u *Userinfo) String() string {
   356  	if u == nil {
   357  		return ""
   358  	}
   359  	s := escape(u.username, encodeUserPassword)
   360  	if u.passwordSet {
   361  		s += ":" + escape(u.password, encodeUserPassword)
   362  	}
   363  	return s
   364  }
   365  
   366  // Maybe rawURL is of the form scheme:path.
   367  // (Scheme must be [a-zA-Z][a-zA-Z0-9+.-]*)
   368  // If so, return scheme, path; else return "", rawURL.
   369  func getScheme(rawURL string) (scheme, path string, err error) {
   370  	for i := 0; i < len(rawURL); i++ {
   371  		c := rawURL[i]
   372  		switch {
   373  		case 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z':
   374  		// do nothing
   375  		case '0' <= c && c <= '9' || c == '+' || c == '-' || c == '.':
   376  			if i == 0 {
   377  				return "", rawURL, nil
   378  			}
   379  		case c == ':':
   380  			if i == 0 {
   381  				return "", "", errors.New("missing protocol scheme")
   382  			}
   383  			return rawURL[:i], rawURL[i+1:], nil
   384  		default:
   385  			// we have encountered an invalid character,
   386  			// so there is no valid scheme
   387  			return "", rawURL, nil
   388  		}
   389  	}
   390  	return "", rawURL, nil
   391  }
   392  
   393  // Parse parses a raw url into a [URL] structure.
   394  //
   395  // The url may be relative (a path, without a host) or absolute
   396  // (starting with a scheme). Trying to parse a hostname and path
   397  // without a scheme is invalid but may not necessarily return an
   398  // error, due to parsing ambiguities.
   399  func Parse(rawURL string) (*URL, error) {
   400  	// Cut off #frag
   401  	u, frag, _ := strings.Cut(rawURL, "#")
   402  	url, err := parse(u, false)
   403  	if err != nil {
   404  		return nil, &Error{"parse", u, err}
   405  	}
   406  	if frag == "" {
   407  		return url, nil
   408  	}
   409  	if err = url.setFragment(frag); err != nil {
   410  		return nil, &Error{"parse", rawURL, err}
   411  	}
   412  	return url, nil
   413  }
   414  
   415  // ParseRequestURI parses a raw url into a [URL] structure. It assumes that
   416  // url was received in an HTTP request, so the url is interpreted
   417  // only as an absolute URI or an absolute path.
   418  // The string url is assumed not to have a #fragment suffix.
   419  // (Web browsers strip #fragment before sending the URL to a web server.)
   420  func ParseRequestURI(rawURL string) (*URL, error) {
   421  	url, err := parse(rawURL, true)
   422  	if err != nil {
   423  		return nil, &Error{"parse", rawURL, err}
   424  	}
   425  	return url, nil
   426  }
   427  
   428  // parse parses a URL from a string in one of two contexts. If
   429  // viaRequest is true, the URL is assumed to have arrived via an HTTP request,
   430  // in which case only absolute URLs or path-absolute relative URLs are allowed.
   431  // If viaRequest is false, all forms of relative URLs are allowed.
   432  func parse(rawURL string, viaRequest bool) (*URL, error) {
   433  	var rest string
   434  	var err error
   435  
   436  	if stringContainsCTLByte(rawURL) {
   437  		return nil, errors.New("net/url: invalid control character in URL")
   438  	}
   439  
   440  	if rawURL == "" && viaRequest {
   441  		return nil, errors.New("empty url")
   442  	}
   443  	url := new(URL)
   444  
   445  	if rawURL == "*" {
   446  		url.Path = "*"
   447  		return url, nil
   448  	}
   449  
   450  	// Split off possible leading "http:", "mailto:", etc.
   451  	// Cannot contain escaped characters.
   452  	if url.Scheme, rest, err = getScheme(rawURL); err != nil {
   453  		return nil, err
   454  	}
   455  	url.Scheme = strings.ToLower(url.Scheme)
   456  
   457  	if strings.HasSuffix(rest, "?") && strings.Count(rest, "?") == 1 {
   458  		url.ForceQuery = true
   459  		rest = rest[:len(rest)-1]
   460  	} else {
   461  		rest, url.RawQuery, _ = strings.Cut(rest, "?")
   462  	}
   463  
   464  	if !strings.HasPrefix(rest, "/") {
   465  		if url.Scheme != "" {
   466  			// We consider rootless paths per RFC 3986 as opaque.
   467  			url.Opaque = rest
   468  			return url, nil
   469  		}
   470  		if viaRequest {
   471  			return nil, errors.New("invalid URI for request")
   472  		}
   473  
   474  		// Avoid confusion with malformed schemes, like cache_object:foo/bar.
   475  		// See golang.org/issue/16822.
   476  		//
   477  		// RFC 3986, §3.3:
   478  		// In addition, a URI reference (Section 4.1) may be a relative-path reference,
   479  		// in which case the first path segment cannot contain a colon (":") character.
   480  		if segment, _, _ := strings.Cut(rest, "/"); strings.Contains(segment, ":") {
   481  			// First path segment has colon. Not allowed in relative URL.
   482  			return nil, errors.New("first path segment in URL cannot contain colon")
   483  		}
   484  	}
   485  
   486  	if (url.Scheme != "" || !viaRequest && !strings.HasPrefix(rest, "///")) && strings.HasPrefix(rest, "//") {
   487  		var authority string
   488  		authority, rest = rest[2:], ""
   489  		if i := strings.Index(authority, "/"); i >= 0 {
   490  			authority, rest = authority[:i], authority[i:]
   491  		}
   492  		url.User, url.Host, err = parseAuthority(url.Scheme, authority)
   493  		if err != nil {
   494  			return nil, err
   495  		}
   496  	} else if url.Scheme != "" && strings.HasPrefix(rest, "/") {
   497  		// OmitHost is set to true when rawURL has an empty host (authority).
   498  		// See golang.org/issue/46059.
   499  		url.OmitHost = true
   500  	}
   501  
   502  	// Set Path and, optionally, RawPath.
   503  	// RawPath is a hint of the encoding of Path. We don't want to set it if
   504  	// the default escaping of Path is equivalent, to help make sure that people
   505  	// don't rely on it in general.
   506  	if err := url.setPath(rest); err != nil {
   507  		return nil, err
   508  	}
   509  	return url, nil
   510  }
   511  
   512  func parseAuthority(scheme, authority string) (user *Userinfo, host string, err error) {
   513  	i := strings.LastIndex(authority, "@")
   514  	if i < 0 {
   515  		host, err = parseHost(scheme, authority)
   516  	} else {
   517  		host, err = parseHost(scheme, authority[i+1:])
   518  	}
   519  	if err != nil {
   520  		return nil, "", err
   521  	}
   522  	if i < 0 {
   523  		return nil, host, nil
   524  	}
   525  	userinfo := authority[:i]
   526  	if !validUserinfo(userinfo) {
   527  		return nil, "", errors.New("net/url: invalid userinfo")
   528  	}
   529  	if !strings.Contains(userinfo, ":") {
   530  		if userinfo, err = unescape(userinfo, encodeUserPassword); err != nil {
   531  			return nil, "", err
   532  		}
   533  		user = User(userinfo)
   534  	} else {
   535  		username, password, _ := strings.Cut(userinfo, ":")
   536  		if username, err = unescape(username, encodeUserPassword); err != nil {
   537  			return nil, "", err
   538  		}
   539  		if password, err = unescape(password, encodeUserPassword); err != nil {
   540  			return nil, "", err
   541  		}
   542  		user = UserPassword(username, password)
   543  	}
   544  	return user, host, nil
   545  }
   546  
   547  // parseHost parses host as an authority without user
   548  // information. That is, as host[:port].
   549  func parseHost(scheme, host string) (string, error) {
   550  	if openBracketIdx := strings.LastIndex(host, "["); openBracketIdx != -1 {
   551  		// Parse an IP-Literal in RFC 3986 and RFC 6874.
   552  		// E.g., "[fe80::1]", "[fe80::1%25en0]", "[fe80::1]:80".
   553  		closeBracketIdx := strings.LastIndex(host, "]")
   554  		if closeBracketIdx < 0 {
   555  			return "", errors.New("missing ']' in host")
   556  		}
   557  
   558  		colonPort := host[closeBracketIdx+1:]
   559  		if !validOptionalPort(colonPort) {
   560  			return "", fmt.Errorf("invalid port %q after host", colonPort)
   561  		}
   562  		unescapedColonPort, err := unescape(colonPort, encodeHost)
   563  		if err != nil {
   564  			return "", err
   565  		}
   566  
   567  		hostname := host[openBracketIdx+1 : closeBracketIdx]
   568  		var unescapedHostname string
   569  		// RFC 6874 defines that %25 (%-encoded percent) introduces
   570  		// the zone identifier, and the zone identifier can use basically
   571  		// any %-encoding it likes. That's different from the host, which
   572  		// can only %-encode non-ASCII bytes.
   573  		// We do impose some restrictions on the zone, to avoid stupidity
   574  		// like newlines.
   575  		zoneIdx := strings.Index(hostname, "%25")
   576  		if zoneIdx >= 0 {
   577  			hostPart, err := unescape(hostname[:zoneIdx], encodeHost)
   578  			if err != nil {
   579  				return "", err
   580  			}
   581  			zonePart, err := unescape(hostname[zoneIdx:], encodeZone)
   582  			if err != nil {
   583  				return "", err
   584  			}
   585  			unescapedHostname = hostPart + zonePart
   586  		} else {
   587  			var err error
   588  			unescapedHostname, err = unescape(hostname, encodeHost)
   589  			if err != nil {
   590  				return "", err
   591  			}
   592  		}
   593  
   594  		// Per RFC 3986, only a host identified by a valid
   595  		// IPv6 address can be enclosed by square brackets.
   596  		// This excludes any IPv4, but notably not IPv4-mapped addresses.
   597  		addr, err := netip.ParseAddr(unescapedHostname)
   598  		if err != nil {
   599  			return "", fmt.Errorf("invalid host: %w", err)
   600  		}
   601  		if addr.Is4() {
   602  			return "", errors.New("invalid IP-literal")
   603  		}
   604  		return "[" + unescapedHostname + "]" + unescapedColonPort, nil
   605  	} else if i := strings.Index(host, ":"); i != -1 {
   606  		lastColon := strings.LastIndex(host, ":")
   607  		if lastColon != i {
   608  			if scheme == "postgresql" || scheme == "postgres" {
   609  				// PostgreSQL relies on non-RFC-3986 parsing to accept
   610  				// a comma-separated list of hosts (with optional ports)
   611  				// in the host subcomponent:
   612  				// https://www.postgresql.org/docs/11/libpq-connect.html#LIBPQ-MULTIPLE-HOSTS
   613  				//
   614  				// Since we historically permitted colons to appear in the host,
   615  				// continue to permit it for postgres:// URLs only.
   616  				// https://go.dev/issue/75223
   617  				i = lastColon
   618  			} else if urlstrictcolons.Value() == "0" {
   619  				urlstrictcolons.IncNonDefault()
   620  				i = lastColon
   621  			}
   622  		}
   623  		colonPort := host[i:]
   624  		if !validOptionalPort(colonPort) {
   625  			return "", fmt.Errorf("invalid port %q after host", colonPort)
   626  		}
   627  	}
   628  
   629  	var err error
   630  	if host, err = unescape(host, encodeHost); err != nil {
   631  		return "", err
   632  	}
   633  	return host, nil
   634  }
   635  
   636  // setPath sets the Path and RawPath fields of the URL based on the provided
   637  // escaped path p. It maintains the invariant that RawPath is only specified
   638  // when it differs from the default encoding of the path.
   639  // For example:
   640  // - setPath("/foo/bar")   will set Path="/foo/bar" and RawPath=""
   641  // - setPath("/foo%2fbar") will set Path="/foo/bar" and RawPath="/foo%2fbar"
   642  // setPath will return an error only if the provided path contains an invalid
   643  // escaping.
   644  //
   645  // setPath should be an internal detail,
   646  // but widely used packages access it using linkname.
   647  // Notable members of the hall of shame include:
   648  //   - github.com/sagernet/sing
   649  //
   650  // Do not remove or change the type signature.
   651  // See go.dev/issue/67401.
   652  //
   653  //go:linkname badSetPath net/url.(*URL).setPath
   654  func (u *URL) setPath(p string) error {
   655  	path, err := unescape(p, encodePath)
   656  	if err != nil {
   657  		return err
   658  	}
   659  	u.Path = path
   660  	if escp := escape(path, encodePath); p == escp {
   661  		// Default encoding is fine.
   662  		u.RawPath = ""
   663  	} else {
   664  		u.RawPath = p
   665  	}
   666  	return nil
   667  }
   668  
   669  // for linkname because we cannot linkname methods directly
   670  func badSetPath(*URL, string) error
   671  
   672  // EscapedPath returns the escaped form of u.Path.
   673  // In general there are multiple possible escaped forms of any path.
   674  // EscapedPath returns u.RawPath when it is a valid escaping of u.Path.
   675  // Otherwise EscapedPath ignores u.RawPath and computes an escaped
   676  // form on its own.
   677  // The [URL.String] and [URL.RequestURI] methods use EscapedPath to construct
   678  // their results.
   679  // In general, code should call EscapedPath instead of
   680  // reading u.RawPath directly.
   681  func (u *URL) EscapedPath() string {
   682  	if u.RawPath != "" && validEncoded(u.RawPath, encodePath) {
   683  		p, err := unescape(u.RawPath, encodePath)
   684  		if err == nil && p == u.Path {
   685  			return u.RawPath
   686  		}
   687  	}
   688  	if u.Path == "*" {
   689  		return "*" // don't escape (Issue 11202)
   690  	}
   691  	return escape(u.Path, encodePath)
   692  }
   693  
   694  // validEncoded reports whether s is a valid encoded path or fragment,
   695  // according to mode.
   696  // It must not contain any bytes that require escaping during encoding.
   697  func validEncoded(s string, mode encoding) bool {
   698  	for i := 0; i < len(s); i++ {
   699  		// RFC 3986, Appendix A.
   700  		// pchar = unreserved / pct-encoded / sub-delims / ":" / "@".
   701  		// shouldEscape is not quite compliant with the RFC,
   702  		// so we check the sub-delims ourselves and let
   703  		// shouldEscape handle the others.
   704  		switch s[i] {
   705  		case '!', '$', '&', '\'', '(', ')', '*', '+', ',', ';', '=', ':', '@':
   706  			// ok
   707  		case '[', ']':
   708  			// ok - not specified in RFC 3986 but left alone by modern browsers
   709  		case '%':
   710  			// ok - percent encoded, will decode
   711  		default:
   712  			if shouldEscape(s[i], mode) {
   713  				return false
   714  			}
   715  		}
   716  	}
   717  	return true
   718  }
   719  
   720  // setFragment is like setPath but for Fragment/RawFragment.
   721  func (u *URL) setFragment(f string) error {
   722  	frag, err := unescape(f, encodeFragment)
   723  	if err != nil {
   724  		return err
   725  	}
   726  	u.Fragment = frag
   727  	if escf := escape(frag, encodeFragment); f == escf {
   728  		// Default encoding is fine.
   729  		u.RawFragment = ""
   730  	} else {
   731  		u.RawFragment = f
   732  	}
   733  	return nil
   734  }
   735  
   736  // EscapedFragment returns the escaped form of u.Fragment.
   737  // In general there are multiple possible escaped forms of any fragment.
   738  // EscapedFragment returns u.RawFragment when it is a valid escaping of u.Fragment.
   739  // Otherwise EscapedFragment ignores u.RawFragment and computes an escaped
   740  // form on its own.
   741  // The [URL.String] method uses EscapedFragment to construct its result.
   742  // In general, code should call EscapedFragment instead of
   743  // reading u.RawFragment directly.
   744  func (u *URL) EscapedFragment() string {
   745  	if u.RawFragment != "" && validEncoded(u.RawFragment, encodeFragment) {
   746  		f, err := unescape(u.RawFragment, encodeFragment)
   747  		if err == nil && f == u.Fragment {
   748  			return u.RawFragment
   749  		}
   750  	}
   751  	return escape(u.Fragment, encodeFragment)
   752  }
   753  
   754  // validOptionalPort reports whether port is either an empty string
   755  // or matches /^:\d*$/
   756  func validOptionalPort(port string) bool {
   757  	if port == "" {
   758  		return true
   759  	}
   760  	if port[0] != ':' {
   761  		return false
   762  	}
   763  	for _, b := range port[1:] {
   764  		if b < '0' || b > '9' {
   765  			return false
   766  		}
   767  	}
   768  	return true
   769  }
   770  
   771  // String reassembles the [URL] into a valid URL string.
   772  // The general form of the result is one of:
   773  //
   774  //	scheme:opaque?query#fragment
   775  //	scheme://userinfo@host/path?query#fragment
   776  //
   777  // If u.Opaque is non-empty, String uses the first form;
   778  // otherwise it uses the second form.
   779  // Any non-ASCII characters in host are escaped.
   780  // To obtain the path, String uses u.EscapedPath().
   781  //
   782  // In the second form, the following rules apply:
   783  //   - if u.Scheme is empty, scheme: is omitted.
   784  //   - if u.User is nil, userinfo@ is omitted.
   785  //   - if u.Host is empty, host/ is omitted.
   786  //   - if u.Scheme and u.Host are empty and u.User is nil,
   787  //     the entire scheme://userinfo@host/ is omitted.
   788  //   - if u.Host is non-empty and u.Path begins with a /,
   789  //     the form host/path does not add its own /.
   790  //   - if u.RawQuery is empty, ?query is omitted.
   791  //   - if u.Fragment is empty, #fragment is omitted.
   792  func (u *URL) String() string {
   793  	var buf strings.Builder
   794  
   795  	n := len(u.Scheme)
   796  	if u.Opaque != "" {
   797  		n += len(u.Opaque)
   798  	} else {
   799  		if !u.OmitHost && (u.Scheme != "" || u.Host != "" || u.User != nil) {
   800  			username := u.User.Username()
   801  			password, _ := u.User.Password()
   802  			n += len(username) + len(password) + len(u.Host)
   803  		}
   804  		n += len(u.Path)
   805  	}
   806  	n += len(u.RawQuery) + len(u.RawFragment)
   807  	n += len(":" + "//" + "//" + ":" + "@" + "/" + "./" + "?" + "#")
   808  	buf.Grow(n)
   809  
   810  	if u.Scheme != "" {
   811  		buf.WriteString(u.Scheme)
   812  		buf.WriteByte(':')
   813  	}
   814  	if u.Opaque != "" {
   815  		buf.WriteString(u.Opaque)
   816  	} else {
   817  		if u.Scheme != "" || u.Host != "" || u.User != nil {
   818  			if u.OmitHost && u.Host == "" && u.User == nil {
   819  				// omit empty host
   820  			} else {
   821  				if u.Host != "" || u.Path != "" || u.User != nil {
   822  					buf.WriteString("//")
   823  				}
   824  				if ui := u.User; ui != nil {
   825  					buf.WriteString(ui.String())
   826  					buf.WriteByte('@')
   827  				}
   828  				if h := u.Host; h != "" {
   829  					buf.WriteString(escape(h, encodeHost))
   830  				}
   831  			}
   832  		}
   833  		path := u.EscapedPath()
   834  		if path != "" && path[0] != '/' && u.Host != "" {
   835  			buf.WriteByte('/')
   836  		}
   837  		if buf.Len() == 0 {
   838  			// RFC 3986 §4.2
   839  			// A path segment that contains a colon character (e.g., "this:that")
   840  			// cannot be used as the first segment of a relative-path reference, as
   841  			// it would be mistaken for a scheme name. Such a segment must be
   842  			// preceded by a dot-segment (e.g., "./this:that") to make a relative-
   843  			// path reference.
   844  			if segment, _, _ := strings.Cut(path, "/"); strings.Contains(segment, ":") {
   845  				buf.WriteString("./")
   846  			}
   847  		}
   848  		buf.WriteString(path)
   849  	}
   850  	if u.ForceQuery || u.RawQuery != "" {
   851  		buf.WriteByte('?')
   852  		buf.WriteString(u.RawQuery)
   853  	}
   854  	if u.Fragment != "" {
   855  		buf.WriteByte('#')
   856  		buf.WriteString(u.EscapedFragment())
   857  	}
   858  	return buf.String()
   859  }
   860  
   861  // Redacted is like [URL.String] but replaces any password with "xxxxx".
   862  // Only the password in u.User is redacted.
   863  func (u *URL) Redacted() string {
   864  	if u == nil {
   865  		return ""
   866  	}
   867  
   868  	ru := *u
   869  	if _, has := ru.User.Password(); has {
   870  		ru.User = UserPassword(ru.User.Username(), "xxxxx")
   871  	}
   872  	return ru.String()
   873  }
   874  
   875  // Values maps a string key to a list of values.
   876  // It is typically used for query parameters and form values.
   877  // Unlike in the http.Header map, the keys in a Values map
   878  // are case-sensitive.
   879  type Values map[string][]string
   880  
   881  // Get gets the first value associated with the given key.
   882  // If there are no values associated with the key, Get returns
   883  // the empty string. To access multiple values, use the map
   884  // directly.
   885  func (v Values) Get(key string) string {
   886  	vs := v[key]
   887  	if len(vs) == 0 {
   888  		return ""
   889  	}
   890  	return vs[0]
   891  }
   892  
   893  // Set sets the key to value. It replaces any existing
   894  // values.
   895  func (v Values) Set(key, value string) {
   896  	v[key] = []string{value}
   897  }
   898  
   899  // Add adds the value to key. It appends to any existing
   900  // values associated with key.
   901  func (v Values) Add(key, value string) {
   902  	v[key] = append(v[key], value)
   903  }
   904  
   905  // Del deletes the values associated with key.
   906  func (v Values) Del(key string) {
   907  	delete(v, key)
   908  }
   909  
   910  // Has checks whether a given key is set.
   911  func (v Values) Has(key string) bool {
   912  	_, ok := v[key]
   913  	return ok
   914  }
   915  
   916  // ParseQuery parses the URL-encoded query string and returns
   917  // a map listing the values specified for each key.
   918  // ParseQuery always returns a non-nil map containing all the
   919  // valid query parameters found; err describes the first decoding error
   920  // encountered, if any.
   921  //
   922  // Query is expected to be a list of key=value settings separated by ampersands.
   923  // A setting without an equals sign is interpreted as a key set to an empty
   924  // value.
   925  // Settings containing a non-URL-encoded semicolon are considered invalid.
   926  func ParseQuery(query string) (Values, error) {
   927  	m := make(Values)
   928  	err := parseQuery(m, query)
   929  	return m, err
   930  }
   931  
   932  func parseQuery(m Values, query string) (err error) {
   933  	for query != "" {
   934  		var key string
   935  		key, query, _ = strings.Cut(query, "&")
   936  		if strings.Contains(key, ";") {
   937  			err = fmt.Errorf("invalid semicolon separator in query")
   938  			continue
   939  		}
   940  		if key == "" {
   941  			continue
   942  		}
   943  		key, value, _ := strings.Cut(key, "=")
   944  		key, err1 := QueryUnescape(key)
   945  		if err1 != nil {
   946  			if err == nil {
   947  				err = err1
   948  			}
   949  			continue
   950  		}
   951  		value, err1 = QueryUnescape(value)
   952  		if err1 != nil {
   953  			if err == nil {
   954  				err = err1
   955  			}
   956  			continue
   957  		}
   958  		m[key] = append(m[key], value)
   959  	}
   960  	return err
   961  }
   962  
   963  // Encode encodes the values into “URL encoded” form
   964  // ("bar=baz&foo=quux") sorted by key.
   965  func (v Values) Encode() string {
   966  	if len(v) == 0 {
   967  		return ""
   968  	}
   969  	var buf strings.Builder
   970  	// To minimize allocations, we eschew iterators and pre-size the slice in
   971  	// which we collect v's keys.
   972  	keys := make([]string, len(v))
   973  	var i int
   974  	for k := range v {
   975  		keys[i] = k
   976  		i++
   977  	}
   978  	slices.Sort(keys)
   979  	for _, k := range keys {
   980  		vs := v[k]
   981  		keyEscaped := QueryEscape(k)
   982  		for _, v := range vs {
   983  			if buf.Len() > 0 {
   984  				buf.WriteByte('&')
   985  			}
   986  			buf.WriteString(keyEscaped)
   987  			buf.WriteByte('=')
   988  			buf.WriteString(QueryEscape(v))
   989  		}
   990  	}
   991  	return buf.String()
   992  }
   993  
   994  // resolvePath applies special path segments from refs and applies
   995  // them to base, per RFC 3986.
   996  func resolvePath(base, ref string) string {
   997  	var full string
   998  	if ref == "" {
   999  		full = base
  1000  	} else if ref[0] != '/' {
  1001  		i := strings.LastIndex(base, "/")
  1002  		full = base[:i+1] + ref
  1003  	} else {
  1004  		full = ref
  1005  	}
  1006  	if full == "" {
  1007  		return ""
  1008  	}
  1009  
  1010  	var (
  1011  		elem string
  1012  		dst  strings.Builder
  1013  	)
  1014  	first := true
  1015  	remaining := full
  1016  	// We want to return a leading '/', so write it now.
  1017  	dst.WriteByte('/')
  1018  	found := true
  1019  	for found {
  1020  		elem, remaining, found = strings.Cut(remaining, "/")
  1021  		if elem == "." {
  1022  			first = false
  1023  			// drop
  1024  			continue
  1025  		}
  1026  
  1027  		if elem == ".." {
  1028  			// Ignore the leading '/' we already wrote.
  1029  			str := dst.String()[1:]
  1030  			index := strings.LastIndexByte(str, '/')
  1031  
  1032  			dst.Reset()
  1033  			dst.WriteByte('/')
  1034  			if index == -1 {
  1035  				first = true
  1036  			} else {
  1037  				dst.WriteString(str[:index])
  1038  			}
  1039  		} else {
  1040  			if !first {
  1041  				dst.WriteByte('/')
  1042  			}
  1043  			dst.WriteString(elem)
  1044  			first = false
  1045  		}
  1046  	}
  1047  
  1048  	if elem == "." || elem == ".." {
  1049  		dst.WriteByte('/')
  1050  	}
  1051  
  1052  	// We wrote an initial '/', but we don't want two.
  1053  	r := dst.String()
  1054  	if len(r) > 1 && r[1] == '/' {
  1055  		r = r[1:]
  1056  	}
  1057  	return r
  1058  }
  1059  
  1060  // IsAbs reports whether the [URL] is absolute.
  1061  // Absolute means that it has a non-empty scheme.
  1062  func (u *URL) IsAbs() bool {
  1063  	return u.Scheme != ""
  1064  }
  1065  
  1066  // Parse parses a [URL] in the context of the receiver. The provided URL
  1067  // may be relative or absolute. Parse returns nil, err on parse
  1068  // failure, otherwise its return value is the same as [URL.ResolveReference].
  1069  func (u *URL) Parse(ref string) (*URL, error) {
  1070  	refURL, err := Parse(ref)
  1071  	if err != nil {
  1072  		return nil, err
  1073  	}
  1074  	return u.ResolveReference(refURL), nil
  1075  }
  1076  
  1077  // ResolveReference resolves a URI reference to an absolute URI from
  1078  // an absolute base URI u, per RFC 3986 Section 5.2. The URI reference
  1079  // may be relative or absolute. ResolveReference always returns a new
  1080  // [URL] instance, even if the returned URL is identical to either the
  1081  // base or reference. If ref is an absolute URL, then ResolveReference
  1082  // ignores base and returns a copy of ref.
  1083  func (u *URL) ResolveReference(ref *URL) *URL {
  1084  	url := *ref
  1085  	if ref.Scheme == "" {
  1086  		url.Scheme = u.Scheme
  1087  	}
  1088  	if ref.Scheme != "" || ref.Host != "" || ref.User != nil {
  1089  		// The "absoluteURI" or "net_path" cases.
  1090  		// We can ignore the error from setPath since we know we provided a
  1091  		// validly-escaped path.
  1092  		url.setPath(resolvePath(ref.EscapedPath(), ""))
  1093  		return &url
  1094  	}
  1095  	if ref.Opaque != "" {
  1096  		url.User = nil
  1097  		url.Host = ""
  1098  		url.Path = ""
  1099  		return &url
  1100  	}
  1101  	if ref.Path == "" && !ref.ForceQuery && ref.RawQuery == "" {
  1102  		url.RawQuery = u.RawQuery
  1103  		if ref.Fragment == "" {
  1104  			url.Fragment = u.Fragment
  1105  			url.RawFragment = u.RawFragment
  1106  		}
  1107  	}
  1108  	if ref.Path == "" && u.Opaque != "" {
  1109  		url.Opaque = u.Opaque
  1110  		url.User = nil
  1111  		url.Host = ""
  1112  		url.Path = ""
  1113  		return &url
  1114  	}
  1115  	// The "abs_path" or "rel_path" cases.
  1116  	url.Host = u.Host
  1117  	url.User = u.User
  1118  	url.setPath(resolvePath(u.EscapedPath(), ref.EscapedPath()))
  1119  	return &url
  1120  }
  1121  
  1122  // Query parses RawQuery and returns the corresponding values.
  1123  // It silently discards malformed value pairs.
  1124  // To check errors use [ParseQuery].
  1125  func (u *URL) Query() Values {
  1126  	v, _ := ParseQuery(u.RawQuery)
  1127  	return v
  1128  }
  1129  
  1130  // RequestURI returns the encoded path?query or opaque?query
  1131  // string that would be used in an HTTP request for u.
  1132  func (u *URL) RequestURI() string {
  1133  	result := u.Opaque
  1134  	if result == "" {
  1135  		result = u.EscapedPath()
  1136  		if result == "" {
  1137  			result = "/"
  1138  		}
  1139  	} else {
  1140  		if strings.HasPrefix(result, "//") {
  1141  			result = u.Scheme + ":" + result
  1142  		}
  1143  	}
  1144  	if u.ForceQuery || u.RawQuery != "" {
  1145  		result += "?" + u.RawQuery
  1146  	}
  1147  	return result
  1148  }
  1149  
  1150  // Hostname returns u.Host, stripping any valid port number if present.
  1151  //
  1152  // If the result is enclosed in square brackets, as literal IPv6 addresses are,
  1153  // the square brackets are removed from the result.
  1154  func (u *URL) Hostname() string {
  1155  	host, _ := splitHostPort(u.Host)
  1156  	return host
  1157  }
  1158  
  1159  // Port returns the port part of u.Host, without the leading colon.
  1160  //
  1161  // If u.Host doesn't contain a valid numeric port, Port returns an empty string.
  1162  func (u *URL) Port() string {
  1163  	_, port := splitHostPort(u.Host)
  1164  	return port
  1165  }
  1166  
  1167  // splitHostPort separates host and port. If the port is not valid, it returns
  1168  // the entire input as host, and it doesn't check the validity of the host.
  1169  // Unlike net.SplitHostPort, but per RFC 3986, it requires ports to be numeric.
  1170  func splitHostPort(hostPort string) (host, port string) {
  1171  	host = hostPort
  1172  
  1173  	colon := strings.LastIndexByte(host, ':')
  1174  	if colon != -1 && validOptionalPort(host[colon:]) {
  1175  		host, port = host[:colon], host[colon+1:]
  1176  	}
  1177  
  1178  	if strings.HasPrefix(host, "[") && strings.HasSuffix(host, "]") {
  1179  		host = host[1 : len(host)-1]
  1180  	}
  1181  
  1182  	return
  1183  }
  1184  
  1185  // Marshaling interface implementations.
  1186  // Would like to implement MarshalText/UnmarshalText but that will change the JSON representation of URLs.
  1187  
  1188  func (u *URL) MarshalBinary() (text []byte, err error) {
  1189  	return u.AppendBinary(nil)
  1190  }
  1191  
  1192  func (u *URL) AppendBinary(b []byte) ([]byte, error) {
  1193  	return append(b, u.String()...), nil
  1194  }
  1195  
  1196  func (u *URL) UnmarshalBinary(text []byte) error {
  1197  	u1, err := Parse(string(text))
  1198  	if err != nil {
  1199  		return err
  1200  	}
  1201  	*u = *u1
  1202  	return nil
  1203  }
  1204  
  1205  // JoinPath returns a new [URL] with the provided path elements joined to
  1206  // any existing path and the resulting path cleaned of any ./ or ../ elements.
  1207  // Any sequences of multiple / characters will be reduced to a single /.
  1208  // Path elements must already be in escaped form, as produced by [PathEscape].
  1209  func (u *URL) JoinPath(elem ...string) *URL {
  1210  	url, _ := u.joinPath(elem...)
  1211  	return url
  1212  }
  1213  
  1214  func (u *URL) joinPath(elem ...string) (*URL, error) {
  1215  	elem = append([]string{u.EscapedPath()}, elem...)
  1216  	var p string
  1217  	if !strings.HasPrefix(elem[0], "/") {
  1218  		// Return a relative path if u is relative,
  1219  		// but ensure that it contains no ../ elements.
  1220  		elem[0] = "/" + elem[0]
  1221  		p = path.Join(elem...)[1:]
  1222  	} else {
  1223  		p = path.Join(elem...)
  1224  	}
  1225  	// path.Join will remove any trailing slashes.
  1226  	// Preserve at least one.
  1227  	if strings.HasSuffix(elem[len(elem)-1], "/") && !strings.HasSuffix(p, "/") {
  1228  		p += "/"
  1229  	}
  1230  	url := *u
  1231  	err := url.setPath(p)
  1232  	return &url, err
  1233  }
  1234  
  1235  // validUserinfo reports whether s is a valid userinfo string per RFC 3986
  1236  // Section 3.2.1:
  1237  //
  1238  //	userinfo    = *( unreserved / pct-encoded / sub-delims / ":" )
  1239  //	unreserved  = ALPHA / DIGIT / "-" / "." / "_" / "~"
  1240  //	sub-delims  = "!" / "$" / "&" / "'" / "(" / ")"
  1241  //	              / "*" / "+" / "," / ";" / "="
  1242  //
  1243  // It doesn't validate pct-encoded. The caller does that via func unescape.
  1244  func validUserinfo(s string) bool {
  1245  	for _, r := range s {
  1246  		if 'A' <= r && r <= 'Z' {
  1247  			continue
  1248  		}
  1249  		if 'a' <= r && r <= 'z' {
  1250  			continue
  1251  		}
  1252  		if '0' <= r && r <= '9' {
  1253  			continue
  1254  		}
  1255  		switch r {
  1256  		case '-', '.', '_', ':', '~', '!', '$', '&', '\'',
  1257  			'(', ')', '*', '+', ',', ';', '=', '%':
  1258  			continue
  1259  		case '@':
  1260  			// `RFC 3986 section 3.2.1` does not allow '@' in userinfo.
  1261  			// It is a delimiter between userinfo and host.
  1262  			// However, URLs are diverse, and in some cases,
  1263  			// the userinfo may contain an '@' character,
  1264  			// for example, in "http://username:p@ssword@google.com",
  1265  			// the string "username:p@ssword" should be treated as valid userinfo.
  1266  			// Ref:
  1267  			//   https://go.dev/issue/3439
  1268  			//   https://go.dev/issue/22655
  1269  			continue
  1270  		default:
  1271  			return false
  1272  		}
  1273  	}
  1274  	return true
  1275  }
  1276  
  1277  // stringContainsCTLByte reports whether s contains any ASCII control character.
  1278  func stringContainsCTLByte(s string) bool {
  1279  	for i := 0; i < len(s); i++ {
  1280  		b := s[i]
  1281  		if b < ' ' || b == 0x7f {
  1282  			return true
  1283  		}
  1284  	}
  1285  	return false
  1286  }
  1287  
  1288  // JoinPath returns a [URL] string with the provided path elements joined to
  1289  // the existing path of base and the resulting path cleaned of any ./ or ../ elements.
  1290  // Path elements must already be in escaped form, as produced by [PathEscape].
  1291  func JoinPath(base string, elem ...string) (result string, err error) {
  1292  	url, err := Parse(base)
  1293  	if err != nil {
  1294  		return
  1295  	}
  1296  	res, err := url.joinPath(elem...)
  1297  	if err != nil {
  1298  		return "", err
  1299  	}
  1300  	return res.String(), nil
  1301  }
  1302  

View as plain text