Debian Codegraph @

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