Debian Codegraph @

src/net/url/url.go

raw
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 //go:generate go run gen_encoding_table.go
6
7 // Package url parses URLs and implements query escaping.
8 //
9 // See RFC 3986. This package generally follows RFC 3986, except where
10 // it deviates for compatibility reasons.
11 // RFC 6874 followed for IPv6 zone literals.
12 package url
13
14 // When sending changes, first search old issues for history on decisions.
15 // Unit tests should also contain references to issue numbers with details.
16
17 import (
18 "bytes"
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 > 0 {
551 return "", errors.New("invalid IP-literal")
552 } else if openBracketIdx == 0 {
553 // Parse an IP-Literal in RFC 3986 and RFC 6874.
554 // E.g., "[fe80::1]", "[fe80::1%25en0]", "[fe80::1]:80".
555 closeBracketIdx := strings.LastIndex(host, "]")
556 if closeBracketIdx < 0 {
557 return "", errors.New("missing ']' in host")
558 }
559
560 colonPort := host[closeBracketIdx+1:]
561 if !validOptionalPort(colonPort) {
562 return "", fmt.Errorf("invalid port %q after host", colonPort)
563 }
564 unescapedColonPort, err := unescape(colonPort, encodeHost)
565 if err != nil {
566 return "", err
567 }
568
569 hostname := host[openBracketIdx+1 : closeBracketIdx]
570 var unescapedHostname string
571 // RFC 6874 defines that %25 (%-encoded percent) introduces
572 // the zone identifier, and the zone identifier can use basically
573 // any %-encoding it likes. That's different from the host, which
574 // can only %-encode non-ASCII bytes.
575 // We do impose some restrictions on the zone, to avoid stupidity
576 // like newlines.
577 zoneIdx := strings.Index(hostname, "%25")
578 if zoneIdx >= 0 {
579 hostPart, err := unescape(hostname[:zoneIdx], encodeHost)
580 if err != nil {
581 return "", err
582 }
583 zonePart, err := unescape(hostname[zoneIdx:], encodeZone)
584 if err != nil {
585 return "", err
586 }
587 unescapedHostname = hostPart + zonePart
588 } else {
589 var err error
590 unescapedHostname, err = unescape(hostname, encodeHost)
591 if err != nil {
592 return "", err
593 }
594 }
595
596 // Per RFC 3986, only a host identified by a valid
597 // IPv6 address can be enclosed by square brackets.
598 // This excludes any IPv4, but notably not IPv4-mapped addresses.
599 addr, err := netip.ParseAddr(unescapedHostname)
600 if err != nil {
601 return "", fmt.Errorf("invalid host: %w", err)
602 }
603 if addr.Is4() {
604 return "", errors.New("invalid IP-literal")
605 }
606 return "[" + unescapedHostname + "]" + unescapedColonPort, nil
607 } else if i := strings.Index(host, ":"); i != -1 {
608 lastColon := strings.LastIndex(host, ":")
609 if lastColon != i {
610 // RFC 3986 does not allow colons to appear in the host subcomponent.
611 //
612 // However, a number of databases including PostgreSQL and MongoDB
613 // permit a comma-separated list of hosts (with optional ports) in the
614 // host subcomponent.
615 //
616 // Since we historically permitted colons to appear in the host,
617 // enforce strict colons only for http and https URLs.
618 //
619 // See https://go.dev/issue/75223 and https://go.dev/issue/78077.
620 if scheme == "http" || scheme == "https" {
621 if urlstrictcolons.Value() == "0" {
622 urlstrictcolons.IncNonDefault()
623 i = lastColon
624 }
625 } else {
626 i = lastColon
627 }
628 }
629 colonPort := host[i:]
630 if !validOptionalPort(colonPort) {
631 return "", fmt.Errorf("invalid port %q after host", colonPort)
632 }
633 }
634
635 var err error
636 if host, err = unescape(host, encodeHost); err != nil {
637 return "", err
638 }
639 return host, nil
640 }
641
642 // setPath sets the Path and RawPath fields of the URL based on the provided
643 // escaped path p. It maintains the invariant that RawPath is only specified
644 // when it differs from the default encoding of the path.
645 // For example:
646 // - setPath("/foo/bar") will set Path="/foo/bar" and RawPath=""
647 // - setPath("/foo%2fbar") will set Path="/foo/bar" and RawPath="/foo%2fbar"
648 // setPath will return an error only if the provided path contains an invalid
649 // escaping.
650 //
651 // setPath should be an internal detail,
652 // but widely used packages access it using linkname.
653 // Notable members of the hall of shame include:
654 // - github.com/sagernet/sing
655 //
656 // Do not remove or change the type signature.
657 // See go.dev/issue/67401.
658 //
659 //go:linkname badSetPath net/url.(*URL).setPath
660 func (u *URL) setPath(p string) error {
661 path, err := unescape(p, encodePath)
662 if err != nil {
663 return err
664 }
665 u.Path = path
666 if escp := escape(path, encodePath); p == escp {
667 // Default encoding is fine.
668 u.RawPath = ""
669 } else {
670 u.RawPath = p
671 }
672 return nil
673 }
674
675 // for linkname because we cannot linkname methods directly
676 func badSetPath(*URL, string) error
677
678 // EscapedPath returns the escaped form of u.Path.
679 // In general there are multiple possible escaped forms of any path.
680 // EscapedPath returns u.RawPath when it is a valid escaping of u.Path.
681 // Otherwise EscapedPath ignores u.RawPath and computes an escaped
682 // form on its own.
683 // The [URL.String] and [URL.RequestURI] methods use EscapedPath to construct
684 // their results.
685 // In general, code should call EscapedPath instead of
686 // reading u.RawPath directly.
687 func (u *URL) EscapedPath() string {
688 if u.RawPath != "" && validEncoded(u.RawPath, encodePath) {
689 p, err := unescape(u.RawPath, encodePath)
690 if err == nil && p == u.Path {
691 return u.RawPath
692 }
693 }
694 if u.Path == "*" {
695 return "*" // don't escape (Issue 11202)
696 }
697 return escape(u.Path, encodePath)
698 }
699
700 // validEncoded reports whether s is a valid encoded path or fragment,
701 // according to mode.
702 // It must not contain any bytes that require escaping during encoding.
703 func validEncoded(s string, mode encoding) bool {
704 for i := 0; i < len(s); i++ {
705 // RFC 3986, Appendix A.
706 // pchar = unreserved / pct-encoded / sub-delims / ":" / "@".
707 // shouldEscape is not quite compliant with the RFC,
708 // so we check the sub-delims ourselves and let
709 // shouldEscape handle the others.
710 switch s[i] {
711 case '!', '$', '&', '\'', '(', ')', '*', '+', ',', ';', '=', ':', '@':
712 // ok
713 case '[', ']':
714 // ok - not specified in RFC 3986 but left alone by modern browsers
715 case '%':
716 // ok - percent encoded, will decode
717 default:
718 if shouldEscape(s[i], mode) {
719 return false
720 }
721 }
722 }
723 return true
724 }
725
726 // setFragment is like setPath but for Fragment/RawFragment.
727 func (u *URL) setFragment(f string) error {
728 frag, err := unescape(f, encodeFragment)
729 if err != nil {
730 return err
731 }
732 u.Fragment = frag
733 if escf := escape(frag, encodeFragment); f == escf {
734 // Default encoding is fine.
735 u.RawFragment = ""
736 } else {
737 u.RawFragment = f
738 }
739 return nil
740 }
741
742 // EscapedFragment returns the escaped form of u.Fragment.
743 // In general there are multiple possible escaped forms of any fragment.
744 // EscapedFragment returns u.RawFragment when it is a valid escaping of u.Fragment.
745 // Otherwise EscapedFragment ignores u.RawFragment and computes an escaped
746 // form on its own.
747 // The [URL.String] method uses EscapedFragment to construct its result.
748 // In general, code should call EscapedFragment instead of
749 // reading u.RawFragment directly.
750 func (u *URL) EscapedFragment() string {
751 if u.RawFragment != "" && validEncoded(u.RawFragment, encodeFragment) {
752 f, err := unescape(u.RawFragment, encodeFragment)
753 if err == nil && f == u.Fragment {
754 return u.RawFragment
755 }
756 }
757 return escape(u.Fragment, encodeFragment)
758 }
759
760 // validOptionalPort reports whether port is either an empty string
761 // or matches /^:\d*$/
762 func validOptionalPort(port string) bool {
763 if port == "" {
764 return true
765 }
766 if port[0] != ':' {
767 return false
768 }
769 for _, b := range port[1:] {
770 if b < '0' || b > '9' {
771 return false
772 }
773 }
774 return true
775 }
776
777 // String reassembles the [URL] into a valid URL string.
778 // The general form of the result is one of:
779 //
780 // scheme:opaque?query#fragment
781 // scheme://userinfo@host/path?query#fragment
782 //
783 // If u.Opaque is non-empty, String uses the first form;
784 // otherwise it uses the second form.
785 // Any non-ASCII characters in host are escaped.
786 // To obtain the path, String uses u.EscapedPath().
787 //
788 // In the second form, the following rules apply:
789 // - if u.Scheme is empty, scheme: is omitted.
790 // - if u.User is nil, userinfo@ is omitted.
791 // - if u.Host is empty, host/ is omitted.
792 // - if u.Scheme and u.Host are empty and u.User is nil,
793 // the entire scheme://userinfo@host/ is omitted.
794 // - if u.Host is non-empty and u.Path begins with a /,
795 // the form host/path does not add its own /.
796 // - if u.RawQuery is empty, ?query is omitted.
797 // - if u.Fragment is empty, #fragment is omitted.
798 func (u *URL) String() string {
799 var buf strings.Builder
800
801 n := len(u.Scheme)
802 if u.Opaque != "" {
803 n += len(u.Opaque)
804 } else {
805 if !u.OmitHost && (u.Scheme != "" || u.Host != "" || u.User != nil) {
806 username := u.User.Username()
807 password, _ := u.User.Password()
808 n += len(username) + len(password) + len(u.Host)
809 }
810 n += len(u.Path)
811 }
812 n += len(u.RawQuery) + len(u.RawFragment)
813 n += len(":" + "//" + "//" + ":" + "@" + "/" + "./" + "?" + "#")
814 buf.Grow(n)
815
816 if u.Scheme != "" {
817 buf.WriteString(u.Scheme)
818 buf.WriteByte(':')
819 }
820 if u.Opaque != "" {
821 buf.WriteString(u.Opaque)
822 } else {
823 if u.Scheme != "" || u.Host != "" || u.User != nil {
824 if u.OmitHost && u.Host == "" && u.User == nil {
825 // omit empty host
826 } else {
827 if u.Host != "" || u.Path != "" || u.User != nil {
828 buf.WriteString("//")
829 }
830 if ui := u.User; ui != nil {
831 buf.WriteString(ui.String())
832 buf.WriteByte('@')
833 }
834 if h := u.Host; h != "" {
835 buf.WriteString(escape(h, encodeHost))
836 }
837 }
838 }
839 path := u.EscapedPath()
840 if path != "" && path[0] != '/' && u.Host != "" {
841 buf.WriteByte('/')
842 }
843 if buf.Len() == 0 {
844 // RFC 3986 §4.2
845 // A path segment that contains a colon character (e.g., "this:that")
846 // cannot be used as the first segment of a relative-path reference, as
847 // it would be mistaken for a scheme name. Such a segment must be
848 // preceded by a dot-segment (e.g., "./this:that") to make a relative-
849 // path reference.
850 if segment, _, _ := strings.Cut(path, "/"); strings.Contains(segment, ":") {
851 buf.WriteString("./")
852 }
853 }
854 buf.WriteString(path)
855 }
856 if u.ForceQuery || u.RawQuery != "" {
857 buf.WriteByte('?')
858 buf.WriteString(u.RawQuery)
859 }
860 if u.Fragment != "" {
861 buf.WriteByte('#')
862 buf.WriteString(u.EscapedFragment())
863 }
864 return buf.String()
865 }
866
867 // Redacted is like [URL.String] but replaces any password with "xxxxx".
868 // Only the password in u.User is redacted.
869 func (u *URL) Redacted() string {
870 if u == nil {
871 return ""
872 }
873
874 ru := *u
875 if _, has := ru.User.Password(); has {
876 ru.User = UserPassword(ru.User.Username(), "xxxxx")
877 }
878 return ru.String()
879 }
880
881 // Values maps a string key to a list of values.
882 // It is typically used for query parameters and form values.
883 // Unlike in the http.Header map, the keys in a Values map
884 // are case-sensitive.
885 type Values map[string][]string
886
887 // Get gets the first value associated with the given key.
888 // If there are no values associated with the key, Get returns
889 // the empty string. To access multiple values, use the map
890 // directly.
891 func (v Values) Get(key string) string {
892 vs := v[key]
893 if len(vs) == 0 {
894 return ""
895 }
896 return vs[0]
897 }
898
899 // Set sets the key to value. It replaces any existing
900 // values.
901 func (v Values) Set(key, value string) {
902 v[key] = []string{value}
903 }
904
905 // Add adds the value to key. It appends to any existing
906 // values associated with key.
907 func (v Values) Add(key, value string) {
908 v[key] = append(v[key], value)
909 }
910
911 // Del deletes the values associated with key.
912 func (v Values) Del(key string) {
913 delete(v, key)
914 }
915
916 // Has checks whether a given key is set.
917 func (v Values) Has(key string) bool {
918 _, ok := v[key]
919 return ok
920 }
921
922 // ParseQuery parses the URL-encoded query string and returns
923 // a map listing the values specified for each key.
924 // ParseQuery always returns a non-nil map containing all the
925 // valid query parameters found; err describes the first decoding error
926 // encountered, if any.
927 //
928 // Query is expected to be a list of key=value settings separated by ampersands.
929 // A setting without an equals sign is interpreted as a key set to an empty
930 // value.
931 // Settings containing a non-URL-encoded semicolon are considered invalid.
932 func ParseQuery(query string) (Values, error) {
933 m := make(Values)
934 err := parseQuery(m, query)
935 return m, err
936 }
937
938 var urlmaxqueryparams = godebug.New("urlmaxqueryparams")
939
940 // Keep this in sync with net/http/httputil.
941 const defaultMaxParams = 10000
942
943 func urlParamsWithinMax(params int) bool {
944 withinDefaultMax := params <= defaultMaxParams
945 if urlmaxqueryparams.Value() == "" {
946 return withinDefaultMax
947 }
948 customMax, err := strconv.Atoi(urlmaxqueryparams.Value())
949 if err != nil {
950 return withinDefaultMax
951 }
952 withinCustomMax := customMax == 0 || params < customMax
953 if withinDefaultMax != withinCustomMax {
954 urlmaxqueryparams.IncNonDefault()
955 }
956 return withinCustomMax
957 }
958
959 func parseQuery(m Values, query string) (err error) {
960 if !urlParamsWithinMax(strings.Count(query, "&") + 1) {
961 return errors.New("number of URL query parameters exceeded limit")
962 }
963 for query != "" {
964 var key string
965 key, query, _ = strings.Cut(query, "&")
966 if strings.Contains(key, ";") {
967 err = fmt.Errorf("invalid semicolon separator in query")
968 continue
969 }
970 if key == "" {
971 continue
972 }
973 key, value, _ := strings.Cut(key, "=")
974 key, err1 := QueryUnescape(key)
975 if err1 != nil {
976 if err == nil {
977 err = err1
978 }
979 continue
980 }
981 value, err1 = QueryUnescape(value)
982 if err1 != nil {
983 if err == nil {
984 err = err1
985 }
986 continue
987 }
988 m[key] = append(m[key], value)
989 }
990 return err
991 }
992
993 // Encode encodes the values into “URL encoded” form
994 // ("bar=baz&foo=quux") sorted by key.
995 func (v Values) Encode() string {
996 if len(v) == 0 {
997 return ""
998 }
999 var buf strings.Builder
1000 // To minimize allocations, we eschew iterators and pre-size the slice in
1001 // which we collect v's keys.
1002 keys := make([]string, len(v))
1003 var i int
1004 for k := range v {
1005 keys[i] = k
1006 i++
1007 }
1008 slices.Sort(keys)
1009 for _, k := range keys {
1010 vs := v[k]
1011 keyEscaped := QueryEscape(k)
1012 for _, v := range vs {
1013 if buf.Len() > 0 {
1014 buf.WriteByte('&')
1015 }
1016 buf.WriteString(keyEscaped)
1017 buf.WriteByte('=')
1018 buf.WriteString(QueryEscape(v))
1019 }
1020 }
1021 return buf.String()
1022 }
1023
1024 // resolvePath applies special path segments from refs and applies
1025 // them to base, per RFC 3986.
1026 func resolvePath(base, ref string) string {
1027 var full string
1028 if ref == "" {
1029 full = base
1030 } else if ref[0] != '/' {
1031 i := strings.LastIndex(base, "/")
1032 full = base[:i+1] + ref
1033 } else {
1034 full = ref
1035 }
1036 if full == "" {
1037 return ""
1038 }
1039
1040 dst := make([]byte, 0, len(full)+1)
1041 dst = append(dst, '/')
1042 elem := ""
1043 remaining := full
1044 found := true
1045 first := true
1046 for found {
1047 elem, remaining, found = strings.Cut(remaining, "/")
1048 switch elem {
1049 case ".":
1050 first = false
1051 continue
1052 case "..":
1053 if i := bytes.LastIndexByte(dst[1:], '/'); i >= 0 {
1054 dst = dst[:i+1]
1055 } else {
1056 dst = dst[:1]
1057 }
1058 first = len(dst) == 1
1059 default:
1060 if !first {
1061 dst = append(dst, '/')
1062 }
1063 dst = append(dst, elem...)
1064 first = false
1065 }
1066 }
1067
1068 if elem == "." || elem == ".." {
1069 dst = append(dst, '/')
1070 }
1071
1072 // We wrote an initial '/', but we don't want two.
1073 if len(dst) > 1 && dst[1] == '/' {
1074 return string(dst[1:])
1075 }
1076 return string(dst)
1077 }
1078
1079 // IsAbs reports whether the [URL] is absolute.
1080 // Absolute means that it has a non-empty scheme.
1081 func (u *URL) IsAbs() bool {
1082 return u.Scheme != ""
1083 }
1084
1085 // Parse parses a [URL] in the context of the receiver. The provided URL
1086 // may be relative or absolute. Parse returns nil, err on parse
1087 // failure, otherwise its return value is the same as [URL.ResolveReference].
1088 func (u *URL) Parse(ref string) (*URL, error) {
1089 refURL, err := Parse(ref)
1090 if err != nil {
1091 return nil, err
1092 }
1093 return u.ResolveReference(refURL), nil
1094 }
1095
1096 // ResolveReference resolves a URI reference to an absolute URI from
1097 // an absolute base URI u, per RFC 3986 Section 5.2. The URI reference
1098 // may be relative or absolute. ResolveReference always returns a new
1099 // [URL] instance, even if the returned URL is identical to either the
1100 // base or reference. If ref is an absolute URL, then ResolveReference
1101 // ignores base and returns a copy of ref.
1102 func (u *URL) ResolveReference(ref *URL) *URL {
1103 url := *ref
1104 if ref.Scheme == "" {
1105 url.Scheme = u.Scheme
1106 }
1107 if ref.Scheme != "" || ref.Host != "" || ref.User != nil {
1108 // The "absoluteURI" or "net_path" cases.
1109 // We can ignore the error from setPath since we know we provided a
1110 // validly-escaped path.
1111 url.setPath(resolvePath(ref.EscapedPath(), ""))
1112 return &url
1113 }
1114 if ref.Opaque != "" {
1115 url.User = nil
1116 url.Host = ""
1117 url.Path = ""
1118 return &url
1119 }
1120 if ref.Path == "" && !ref.ForceQuery && ref.RawQuery == "" {
1121 url.RawQuery = u.RawQuery
1122 if ref.Fragment == "" {
1123 url.Fragment = u.Fragment
1124 url.RawFragment = u.RawFragment
1125 }
1126 }
1127 if ref.Path == "" && u.Opaque != "" {
1128 url.Opaque = u.Opaque
1129 url.User = nil
1130 url.Host = ""
1131 url.Path = ""
1132 return &url
1133 }
1134 // The "abs_path" or "rel_path" cases.
1135 url.Host = u.Host
1136 url.User = u.User
1137 url.setPath(resolvePath(u.EscapedPath(), ref.EscapedPath()))
1138 return &url
1139 }
1140
1141 // Query parses RawQuery and returns the corresponding values.
1142 // It silently discards malformed value pairs.
1143 // To check errors use [ParseQuery].
1144 func (u *URL) Query() Values {
1145 v, _ := ParseQuery(u.RawQuery)
1146 return v
1147 }
1148
1149 // RequestURI returns the encoded path?query or opaque?query
1150 // string that would be used in an HTTP request for u.
1151 func (u *URL) RequestURI() string {
1152 result := u.Opaque
1153 if result == "" {
1154 result = u.EscapedPath()
1155 if result == "" {
1156 result = "/"
1157 }
1158 } else {
1159 if strings.HasPrefix(result, "//") {
1160 result = u.Scheme + ":" + result
1161 }
1162 }
1163 if u.ForceQuery || u.RawQuery != "" {
1164 result += "?" + u.RawQuery
1165 }
1166 return result
1167 }
1168
1169 // Hostname returns u.Host, stripping any valid port number if present.
1170 //
1171 // If the result is enclosed in square brackets, as literal IPv6 addresses are,
1172 // the square brackets are removed from the result.
1173 func (u *URL) Hostname() string {
1174 host, _ := splitHostPort(u.Host)
1175 return host
1176 }
1177
1178 // Port returns the port part of u.Host, without the leading colon.
1179 //
1180 // If u.Host doesn't contain a valid numeric port, Port returns an empty string.
1181 func (u *URL) Port() string {
1182 _, port := splitHostPort(u.Host)
1183 return port
1184 }
1185
1186 // splitHostPort separates host and port. If the port is not valid, it returns
1187 // the entire input as host, and it doesn't check the validity of the host.
1188 // Unlike net.SplitHostPort, but per RFC 3986, it requires ports to be numeric.
1189 func splitHostPort(hostPort string) (host, port string) {
1190 host = hostPort
1191
1192 colon := strings.LastIndexByte(host, ':')
1193 if colon != -1 && validOptionalPort(host[colon:]) {
1194 host, port = host[:colon], host[colon+1:]
1195 }
1196
1197 if strings.HasPrefix(host, "[") && strings.HasSuffix(host, "]") {
1198 host = host[1 : len(host)-1]
1199 }
1200
1201 return
1202 }
1203
1204 // Marshaling interface implementations.
1205 // Would like to implement MarshalText/UnmarshalText but that will change the JSON representation of URLs.
1206
1207 func (u *URL) MarshalBinary() (text []byte, err error) {
1208 return u.AppendBinary(nil)
1209 }
1210
1211 func (u *URL) AppendBinary(b []byte) ([]byte, error) {
1212 return append(b, u.String()...), nil
1213 }
1214
1215 func (u *URL) UnmarshalBinary(text []byte) error {
1216 u1, err := Parse(string(text))
1217 if err != nil {
1218 return err
1219 }
1220 *u = *u1
1221 return nil
1222 }
1223
1224 // JoinPath returns a new [URL] with the provided path elements joined to
1225 // any existing path and the resulting path cleaned of any ./ or ../ elements.
1226 // Any sequences of multiple / characters will be reduced to a single /.
1227 // Path elements must already be in escaped form, as produced by [PathEscape].
1228 func (u *URL) JoinPath(elem ...string) *URL {
1229 url, _ := u.joinPath(elem...)
1230 return url
1231 }
1232
1233 func (u *URL) joinPath(elem ...string) (*URL, error) {
1234 elem = append([]string{u.EscapedPath()}, elem...)
1235 var p string
1236 if !strings.HasPrefix(elem[0], "/") {
1237 // Return a relative path if u is relative,
1238 // but ensure that it contains no ../ elements.
1239 elem[0] = "/" + elem[0]
1240 p = path.Join(elem...)[1:]
1241 } else {
1242 p = path.Join(elem...)
1243 }
1244 // path.Join will remove any trailing slashes.
1245 // Preserve at least one.
1246 if strings.HasSuffix(elem[len(elem)-1], "/") && !strings.HasSuffix(p, "/") {
1247 p += "/"
1248 }
1249 url := *u
1250 err := url.setPath(p)
1251 return &url, err
1252 }
1253
1254 // validUserinfo reports whether s is a valid userinfo string per RFC 3986
1255 // Section 3.2.1:
1256 //
1257 // userinfo = *( unreserved / pct-encoded / sub-delims / ":" )
1258 // unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
1259 // sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
1260 // / "*" / "+" / "," / ";" / "="
1261 //
1262 // It doesn't validate pct-encoded. The caller does that via func unescape.
1263 func validUserinfo(s string) bool {
1264 for _, r := range s {
1265 if 'A' <= r && r <= 'Z' {
1266 continue
1267 }
1268 if 'a' <= r && r <= 'z' {
1269 continue
1270 }
1271 if '0' <= r && r <= '9' {
1272 continue
1273 }
1274 switch r {
1275 case '-', '.', '_', ':', '~', '!', '$', '&', '\'',
1276 '(', ')', '*', '+', ',', ';', '=', '%':
1277 continue
1278 case '@':
1279 // `RFC 3986 section 3.2.1` does not allow '@' in userinfo.
1280 // It is a delimiter between userinfo and host.
1281 // However, URLs are diverse, and in some cases,
1282 // the userinfo may contain an '@' character,
1283 // for example, in "http://username:p@[email protected]",
1284 // the string "username:p@ssword" should be treated as valid userinfo.
1285 // Ref:
1286 // https://go.dev/issue/3439
1287 // https://go.dev/issue/22655
1288 continue
1289 default:
1290 return false
1291 }
1292 }
1293 return true
1294 }
1295
1296 // stringContainsCTLByte reports whether s contains any ASCII control character.
1297 func stringContainsCTLByte(s string) bool {
1298 for i := 0; i < len(s); i++ {
1299 b := s[i]
1300 if b < ' ' || b == 0x7f {
1301 return true
1302 }
1303 }
1304 return false
1305 }
1306
1307 // JoinPath returns a [URL] string with the provided path elements joined to
1308 // the existing path of base and the resulting path cleaned of any ./ or ../ elements.
1309 // Path elements must already be in escaped form, as produced by [PathEscape].
1310 func JoinPath(base string, elem ...string) (result string, err error) {
1311 url, err := Parse(base)
1312 if err != nil {
1313 return
1314 }
1315 res, err := url.joinPath(elem...)
1316 if err != nil {
1317 return "", err
1318 }
1319 return res.String(), nil
1320 }