Ada 3.4.3
Fast spec-compliant URL parser
Loading...
Searching...
No Matches
url_aggregator.cpp
Go to the documentation of this file.
1#include "ada/checkers-inl.h"
2#include "ada/helpers.h"
4#include "ada/scheme.h"
5#include "ada/unicode-inl.h"
10
11#include <iterator>
12#include <ranges>
13#include <string>
14#include <string_view>
15
16namespace ada {
17template <bool has_state_override>
18[[nodiscard]] ada_really_inline bool url_aggregator::parse_scheme_with_colon(
19 const std::string_view input_with_colon) {
20 ada_log("url_aggregator::parse_scheme_with_colon ", input_with_colon);
22 ADA_ASSERT_TRUE(!helpers::overlaps(input_with_colon, buffer));
23 std::string_view input{input_with_colon};
24 input.remove_suffix(1);
25 auto parsed_type = ada::scheme::get_scheme_type(input);
26 const bool is_input_special = (parsed_type != ada::scheme::NOT_SPECIAL);
31 if (is_input_special) { // fast path!!!
32 if constexpr (has_state_override) {
33 // If url's scheme is not a special scheme and buffer is a special scheme,
34 // then return.
35 if (is_special() != is_input_special) {
36 return false;
37 }
38
39 // If url includes credentials or has a non-null port, and buffer is
40 // "file", then return.
41 if ((has_credentials() || components.port != url_components::omitted) &&
42 parsed_type == ada::scheme::type::FILE) {
43 return false;
44 }
45
46 // If url's scheme is "file" and its host is an empty host, then return.
47 // An empty host is the empty string.
48 if (type == ada::scheme::type::FILE &&
49 components.host_start == components.host_end) {
50 return false;
51 }
52 }
53
54 type = parsed_type;
55 set_scheme_from_view_with_colon(input_with_colon);
56
57 if constexpr (has_state_override) {
58 // This is uncommon.
59 uint16_t urls_scheme_port = get_special_port();
60
61 // If url's port is url's scheme's default port, then set url's port to
62 // null.
63 if (components.port == urls_scheme_port) {
64 clear_port();
65 }
66 }
67 } else { // slow path
68 std::string _buffer(input);
69 // Next function is only valid if the input is ASCII and returns false
70 // otherwise, but it seems that we always have ascii content so we do not
71 // need to check the return value.
72 unicode::to_lower_ascii(_buffer.data(), _buffer.size());
73
74 if constexpr (has_state_override) {
75 // If url's scheme is a special scheme and buffer is not a special scheme,
76 // then return. If url's scheme is not a special scheme and buffer is a
77 // special scheme, then return.
78 if (is_special() != ada::scheme::is_special(_buffer)) {
79 return true;
80 }
81
82 // If url includes credentials or has a non-null port, and buffer is
83 // "file", then return.
84 if ((has_credentials() || components.port != url_components::omitted) &&
85 _buffer == "file") {
86 return true;
87 }
88
89 // If url's scheme is "file" and its host is an empty host, then return.
90 // An empty host is the empty string.
91 if (type == ada::scheme::type::FILE &&
92 components.host_start == components.host_end) {
93 return true;
94 }
95 }
96
97 set_scheme(_buffer);
98
99 if constexpr (has_state_override) {
100 // This is uncommon.
101 uint16_t urls_scheme_port = get_special_port();
102
103 // If url's port is url's scheme's default port, then set url's port to
104 // null.
105 if (components.port == urls_scheme_port) {
106 clear_port();
107 }
108 }
109 }
111 return true;
112}
113
114inline void url_aggregator::copy_scheme(const url_aggregator& u) {
115 ada_log("url_aggregator::copy_scheme ", u.buffer);
117 // next line could overflow but unsigned arithmetic has well-defined
118 // overflows.
119 uint32_t new_difference = u.components.protocol_end - components.protocol_end;
120 type = u.type;
121 buffer.erase(0, components.protocol_end);
122 buffer.insert(0, u.get_protocol());
123 components.protocol_end = u.components.protocol_end;
124
125 // No need to update the components
126 if (new_difference == 0) {
127 return;
128 }
129
130 // Update the rest of the components.
131 components.username_end += new_difference;
132 components.host_start += new_difference;
133 components.host_end += new_difference;
134 components.pathname_start += new_difference;
135 if (components.search_start != url_components::omitted) {
136 components.search_start += new_difference;
137 }
138 if (components.hash_start != url_components::omitted) {
139 components.hash_start += new_difference;
140 }
142}
143
144inline void url_aggregator::set_scheme_from_view_with_colon(
145 std::string_view new_scheme_with_colon) {
146 ada_log("url_aggregator::set_scheme_from_view_with_colon ",
147 new_scheme_with_colon);
149 ADA_ASSERT_TRUE(!new_scheme_with_colon.empty() &&
150 new_scheme_with_colon.back() == ':');
151 // next line could overflow but unsigned arithmetic has well-defined
152 // overflows.
153 uint32_t new_difference =
154 uint32_t(new_scheme_with_colon.size()) - components.protocol_end;
155
156 if (buffer.empty()) {
157 buffer.append(new_scheme_with_colon);
158 } else {
159 buffer.erase(0, components.protocol_end);
160 buffer.insert(0, new_scheme_with_colon);
161 }
162 components.protocol_end += new_difference;
163
164 // Update the rest of the components.
165 components.username_end += new_difference;
166 components.host_start += new_difference;
167 components.host_end += new_difference;
168 components.pathname_start += new_difference;
169 if (components.search_start != url_components::omitted) {
170 components.search_start += new_difference;
171 }
172 if (components.hash_start != url_components::omitted) {
173 components.hash_start += new_difference;
174 }
176}
177
178inline void url_aggregator::set_scheme(std::string_view new_scheme) {
179 ada_log("url_aggregator::set_scheme ", new_scheme);
181 ADA_ASSERT_TRUE(new_scheme.empty() || new_scheme.back() != ':');
182 // next line could overflow but unsigned arithmetic has well-defined
183 // overflows.
184 uint32_t new_difference =
185 uint32_t(new_scheme.size()) - components.protocol_end + 1;
186
187 type = ada::scheme::get_scheme_type(new_scheme);
188 if (buffer.empty()) {
189 buffer.append(helpers::concat(new_scheme, ":"));
190 } else {
191 buffer.erase(0, components.protocol_end);
192 buffer.insert(0, helpers::concat(new_scheme, ":"));
193 }
194 components.protocol_end = uint32_t(new_scheme.size() + 1);
195
196 // Update the rest of the components.
197 components.username_end += new_difference;
198 components.host_start += new_difference;
199 components.host_end += new_difference;
200 components.pathname_start += new_difference;
201 if (components.search_start != url_components::omitted) {
202 components.search_start += new_difference;
203 }
204 if (components.hash_start != url_components::omitted) {
205 components.hash_start += new_difference;
206 }
208}
209
210bool url_aggregator::set_protocol(const std::string_view input) {
211 ada_log("url_aggregator::set_protocol ", input);
213 ADA_ASSERT_TRUE(!helpers::overlaps(input, buffer));
214 std::string view(input);
215 helpers::remove_ascii_tab_or_newline(view);
216 if (view.empty()) {
217 return true;
218 }
219
220 // Schemes should start with alpha values.
221 if (!checkers::is_alpha(view[0])) {
222 return false;
223 }
224
225 view.append(":");
226
227 std::string::iterator pointer =
228 std::ranges::find_if_not(view, unicode::is_alnum_plus);
229
230 if (pointer != view.end() && *pointer == ':') {
231 return parse_scheme_with_colon<true>(
232 view.substr(0, pointer - view.begin() + 1));
233 }
234 return false;
235}
236
237bool url_aggregator::set_username(const std::string_view input) {
238 ada_log("url_aggregator::set_username '", input, "' ");
240 ADA_ASSERT_TRUE(!helpers::overlaps(input, buffer));
241 if (cannot_have_credentials_or_port()) {
242 return false;
243 }
246 if (idx == input.size()) {
247 update_base_username(input);
248 } else {
249 // We only create a temporary string if we have to!
250 update_base_username(ada::unicode::percent_encode(
252 }
254 return true;
255}
256
257bool url_aggregator::set_password(const std::string_view input) {
258 ada_log("url_aggregator::set_password '", input, "'");
260 ADA_ASSERT_TRUE(!helpers::overlaps(input, buffer));
261 if (cannot_have_credentials_or_port()) {
262 return false;
263 }
266 if (idx == input.size()) {
267 update_base_password(input);
268 } else {
269 // We only create a temporary string if we have to!
270 update_base_password(ada::unicode::percent_encode(
272 }
274 return true;
275}
276
277bool url_aggregator::set_port(const std::string_view input) {
278 ada_log("url_aggregator::set_port ", input);
280 ADA_ASSERT_TRUE(!helpers::overlaps(input, buffer));
281 if (cannot_have_credentials_or_port()) {
282 return false;
283 }
284
285 if (input.empty()) {
286 clear_port();
287 return true;
288 }
289
290 std::string trimmed(input);
291 helpers::remove_ascii_tab_or_newline(trimmed);
292
293 if (trimmed.empty()) {
294 return true;
295 }
296
297 // Input should not start with a non-digit character.
298 if (!ada::unicode::is_ascii_digit(trimmed.front())) {
299 return false;
300 }
301
302 // Find the first non-digit character to determine the length of digits
303 auto first_non_digit =
304 std::ranges::find_if_not(trimmed, ada::unicode::is_ascii_digit);
305 std::string_view digits_to_parse =
306 std::string_view(trimmed.data(), first_non_digit - trimmed.begin());
307
308 // Revert changes if parse_port fails.
309 uint32_t previous_port = components.port;
310 parse_port(digits_to_parse);
311 if (is_valid) {
312 return true;
313 }
314 update_base_port(previous_port);
315 is_valid = true;
317 return false;
318}
319
320bool url_aggregator::set_pathname(const std::string_view input) {
321 ada_log("url_aggregator::set_pathname ", input);
323 ADA_ASSERT_TRUE(!helpers::overlaps(input, buffer));
324 if (has_opaque_path) {
325 return false;
326 }
327 clear_pathname();
328 parse_path(input);
329 if (get_pathname().starts_with("//") && !has_authority() && !has_dash_dot()) {
330 buffer.insert(components.pathname_start, "/.");
331 components.pathname_start += 2;
332 if (components.search_start != url_components::omitted) {
333 components.search_start += 2;
334 }
335 if (components.hash_start != url_components::omitted) {
336 components.hash_start += 2;
337 }
338 }
340 return true;
341}
342
343ada_really_inline void url_aggregator::parse_path(std::string_view input) {
344 ada_log("url_aggregator::parse_path ", input);
346 ADA_ASSERT_TRUE(!helpers::overlaps(input, buffer));
347 std::string tmp_buffer;
348 std::string_view internal_input;
349 if (unicode::has_tabs_or_newline(input)) {
350 tmp_buffer = input;
351 // Optimization opportunity: Instead of copying and then pruning, we could
352 // just directly build the string from user_input.
353 helpers::remove_ascii_tab_or_newline(tmp_buffer);
354 internal_input = tmp_buffer;
355 } else {
356 internal_input = input;
357 }
358
359 // If url is special, then:
360 if (is_special()) {
361 if (internal_input.empty()) {
362 update_base_pathname("/");
363 } else if ((internal_input[0] == '/') || (internal_input[0] == '\\')) {
364 consume_prepared_path(internal_input.substr(1));
365 } else {
366 consume_prepared_path(internal_input);
367 }
368 } else if (!internal_input.empty()) {
369 if (internal_input[0] == '/') {
370 consume_prepared_path(internal_input.substr(1));
371 } else {
372 consume_prepared_path(internal_input);
373 }
374 } else {
375 // Non-special URLs with an empty host can have their paths erased
376 // Path-only URLs cannot have their paths erased
377 if (components.host_start == components.host_end && !has_authority()) {
378 update_base_pathname("/");
379 }
380 }
382}
383
384void url_aggregator::set_search(const std::string_view input) {
385 ada_log("url_aggregator::set_search ", input);
387 ADA_ASSERT_TRUE(!helpers::overlaps(input, buffer));
388 if (input.empty()) {
389 clear_search();
390 helpers::strip_trailing_spaces_from_opaque_path(*this);
391 return;
392 }
393
394 std::string new_value;
395 new_value = input[0] == '?' ? input.substr(1) : input;
396 helpers::remove_ascii_tab_or_newline(new_value);
397
398 auto query_percent_encode_set =
401
402 update_base_search(new_value, query_percent_encode_set);
404}
405
406void url_aggregator::set_hash(const std::string_view input) {
407 ada_log("url_aggregator::set_hash ", input);
409 ADA_ASSERT_TRUE(!helpers::overlaps(input, buffer));
410 if (input.empty()) {
411 if (components.hash_start != url_components::omitted) {
412 buffer.resize(components.hash_start);
413 components.hash_start = url_components::omitted;
414 }
415 helpers::strip_trailing_spaces_from_opaque_path(*this);
416 return;
417 }
418
419 std::string new_value;
420 new_value = input[0] == '#' ? input.substr(1) : input;
421 helpers::remove_ascii_tab_or_newline(new_value);
422 update_unencoded_base_hash(new_value);
424}
425
426bool url_aggregator::set_href(const std::string_view input) {
427 ADA_ASSERT_TRUE(!helpers::overlaps(input, buffer));
428 ada_log("url_aggregator::set_href ", input, " [", input.size(), " bytes]");
430 ada_log("url_aggregator::set_href, success :", out.has_value());
431
432 if (out) {
433 ada_log("url_aggregator::set_href, parsed ", out->to_string());
434 // TODO: Figure out why the following line puts test to never finish.
435 *this = *out;
436 }
437
438 return out.has_value();
439}
440
441ada_really_inline bool url_aggregator::parse_host(std::string_view input) {
442 ada_log("url_aggregator:parse_host \"", input, "\" [", input.size(),
443 " bytes]");
445 ADA_ASSERT_TRUE(!helpers::overlaps(input, buffer));
446 if (input.empty()) {
447 return is_valid = false;
448 } // technically unnecessary.
449 // If input starts with U+005B ([), then:
450 if (input[0] == '[') {
451 // If input does not end with U+005D (]), validation error, return failure.
452 if (input.back() != ']') {
453 return is_valid = false;
454 }
455 ada_log("parse_host ipv6");
456
457 // Return the result of IPv6 parsing input with its leading U+005B ([) and
458 // trailing U+005D (]) removed.
459 input.remove_prefix(1);
460 input.remove_suffix(1);
461 return parse_ipv6(input);
462 }
463
464 // If isNotSpecial is true, then return the result of opaque-host parsing
465 // input.
466 if (!is_special()) {
467 return parse_opaque_host(input);
468 }
469 // Let domain be the result of running UTF-8 decode without BOM on the
470 // percent-decoding of input. Let asciiDomain be the result of running domain
471 // to ASCII with domain and false. The most common case is an ASCII input, in
472 // which case we do not need to call the expensive 'to_ascii' if a few
473 // conditions are met: no '%' and no 'xn-' subsequence.
474
475 // Often, the input does not contain any forbidden code points, and no upper
476 // case ASCII letter, then we can just copy it to the buffer. We want to
477 // optimize for such a common case.
478
479 // Fast path: try to parse as pure decimal IPv4(a.b.c.d) first.
480 const uint64_t fast_result = checkers::try_parse_ipv4_fast(input);
481 if (fast_result < checkers::ipv4_fast_fail) {
482 // Fast path succeeded - input is pure decimal IPv4
483 if (!input.empty() && input.back() == '.') {
484 update_base_hostname(input.substr(0, input.size() - 1));
485 } else {
486 update_base_hostname(input);
487 }
488 host_type = IPV4;
489 ada_log("parse_host fast path decimal ipv4");
491 return true;
492 }
493 uint8_t is_forbidden_or_upper =
494 unicode::contains_forbidden_domain_code_point_or_upper(input.data(),
495 input.size());
496 // Minor optimization opportunity:
497 // contains_forbidden_domain_code_point_or_upper could be extend to check for
498 // the presence of characters that cannot appear in the ipv4 address and we
499 // could also check whether x and n and - are present, and so we could skip
500 // some of the checks below. However, the gains are likely to be small, and
501 // the code would be more complex.
502 if (is_forbidden_or_upper == 0 &&
503 input.find("xn-") == std::string_view::npos) {
504 // fast path
505 update_base_hostname(input);
506
507 // Check for other IPv4 formats (hex, octal, etc.)
508 if (checkers::is_ipv4(get_hostname())) {
509 ada_log("parse_host fast path ipv4");
510 return parse_ipv4(get_hostname(), true);
511 }
512 ada_log("parse_host fast path ", get_hostname());
513 return true;
514 }
515 // We have encountered at least one forbidden code point or the input contains
516 // 'xn-' (case insensitive), so we need to call 'to_ascii' to perform the full
517 // conversion.
518
519 ada_log("parse_host calling to_ascii");
520 std::optional<std::string> host = std::string(get_hostname());
521 is_valid = ada::unicode::to_ascii(host, input, input.find('%'));
522 if (!is_valid) {
523 ada_log("parse_host to_ascii returns false");
524 return is_valid = false;
525 }
526 ada_log("parse_host to_ascii succeeded ", *host, " [", host->size(),
527 " bytes]");
528
529 if (std::ranges::any_of(host.value(),
530 ada::unicode::is_forbidden_domain_code_point)) {
531 return is_valid = false;
532 }
533
534 // If asciiDomain ends in a number, then return the result of IPv4 parsing
535 // asciiDomain.
536 if (checkers::is_ipv4(host.value())) {
537 ada_log("parse_host got ipv4 ", *host);
538 return parse_ipv4(host.value(), false);
539 }
540
541 update_base_hostname(host.value());
543 return true;
544}
545
546template <bool override_hostname>
547bool url_aggregator::set_host_or_hostname(const std::string_view input) {
548 ada_log("url_aggregator::set_host_or_hostname ", input);
550 ADA_ASSERT_TRUE(!helpers::overlaps(input, buffer));
551 if (has_opaque_path) {
552 return false;
553 }
554
555 std::string previous_host(get_hostname());
556 uint32_t previous_port = components.port;
557
558 size_t host_end_pos = input.find('#');
559 std::string _host(input.data(), host_end_pos != std::string_view::npos
560 ? host_end_pos
561 : input.size());
562 helpers::remove_ascii_tab_or_newline(_host);
563 std::string_view new_host(_host);
564
565 // If url's scheme is "file", then set state to file host state, instead of
566 // host state.
567 if (type != ada::scheme::type::FILE) {
568 std::string_view host_view(_host.data(), _host.length());
569 auto [location, found_colon] =
570 helpers::get_host_delimiter_location(is_special(), host_view);
571
572 // Otherwise, if c is U+003A (:) and insideBrackets is false, then:
573 // Note: the 'found_colon' value is true if and only if a colon was
574 // encountered while not inside brackets.
575 if (found_colon) {
576 // If buffer is the empty string, host-missing validation error, return
577 // failure.
578 std::string_view host_buffer = host_view.substr(0, location);
579 if (host_buffer.empty()) {
580 return false;
581 }
582
583 // If state override is given and state override is hostname state, then
584 // return failure.
585 if constexpr (override_hostname) {
586 return false;
587 }
588
589 // Let host be the result of host parsing buffer with url is not special.
590 bool succeeded = parse_host(host_buffer);
591 if (!succeeded) {
592 update_base_hostname(previous_host);
593 update_base_port(previous_port);
594 return false;
595 }
596
597 // Set url's host to host, buffer to the empty string, and state to port
598 // state.
599 std::string_view port_buffer = new_host.substr(location + 1);
600 if (!port_buffer.empty()) {
601 set_port(port_buffer);
602 }
603 return true;
604 }
605 // Otherwise, if one of the following is true:
606 // - c is the EOF code point, U+002F (/), U+003F (?), or U+0023 (#)
607 // - url is special and c is U+005C (\‍)
608 else {
609 // If url is special and host_view is the empty string, host-missing
610 // validation error, return failure.
611 if (host_view.empty() && is_special()) {
612 return false;
613 }
614
615 // Otherwise, if state override is given, host_view is the empty string,
616 // and either url includes credentials or url's port is non-null, then
617 // return failure.
618 if (host_view.empty() && (has_credentials() || has_port())) {
619 return false;
620 }
621
622 // Let host be the result of host parsing host_view with url is not
623 // special.
624 if (host_view.empty() && !is_special()) {
625 if (has_hostname()) {
626 clear_hostname(); // easy!
627 } else if (has_dash_dot()) {
628 add_authority_slashes_if_needed();
629 delete_dash_dot();
630 }
631 return true;
632 }
633
634 bool succeeded = parse_host(host_view);
635 if (!succeeded) {
636 update_base_hostname(previous_host);
637 update_base_port(previous_port);
638 return false;
639 } else if (has_dash_dot()) {
640 // Should remove dash_dot from pathname
641 delete_dash_dot();
642 }
643 return true;
644 }
645 }
646
647 size_t location = new_host.find_first_of("/\\?");
648 if (location != std::string_view::npos) {
649 new_host.remove_suffix(new_host.length() - location);
650 }
651
652 if (new_host.empty()) {
653 // Set url's host to the empty string.
654 clear_hostname();
655 } else {
656 // Let host be the result of host parsing buffer with url is not special.
657 if (!parse_host(new_host)) {
658 update_base_hostname(previous_host);
659 update_base_port(previous_port);
660 return false;
661 }
662
663 // If host is "localhost", then set host to the empty string.
664 if (helpers::substring(buffer, components.host_start,
665 components.host_end) == "localhost") {
666 clear_hostname();
667 }
668 }
670 return true;
671}
672
673bool url_aggregator::set_host(const std::string_view input) {
674 ada_log("url_aggregator::set_host '", input, "'");
676 ADA_ASSERT_TRUE(!helpers::overlaps(input, buffer));
677 return set_host_or_hostname<false>(input);
678}
679
680bool url_aggregator::set_hostname(const std::string_view input) {
681 ada_log("url_aggregator::set_hostname '", input, "'");
683 ADA_ASSERT_TRUE(!helpers::overlaps(input, buffer));
684 return set_host_or_hostname<true>(input);
685}
686
687[[nodiscard]] std::string url_aggregator::get_origin() const {
688 ada_log("url_aggregator::get_origin");
689 if (is_special()) {
690 // Return a new opaque origin.
691 if (type == scheme::FILE) {
692 return "null";
693 }
694
695 return helpers::concat(get_protocol(), "//", get_host());
696 }
697
698 if (get_protocol() == "blob:") {
699 std::string_view path = get_pathname();
700 if (!path.empty()) {
701 auto out = ada::parse<ada::url_aggregator>(path);
702 if (out && (out->type == scheme::HTTP || out->type == scheme::HTTPS)) {
703 // If pathURL's scheme is not "http" and not "https", then return a
704 // new opaque origin.
705 return helpers::concat(out->get_protocol(), "//", out->get_host());
706 }
707 }
708 }
709
710 // Return a new opaque origin.
711 return "null";
712}
713
714[[nodiscard]] std::string_view url_aggregator::get_username() const
716 ada_log("url_aggregator::get_username");
718 return helpers::substring(buffer, components.protocol_end + 2,
719 components.username_end);
720 }
721 return "";
722}
723
724[[nodiscard]] std::string_view url_aggregator::get_password() const
726 ada_log("url_aggregator::get_password");
728 return helpers::substring(buffer, components.username_end + 1,
729 components.host_start);
730 }
731 return "";
732}
733
734[[nodiscard]] std::string_view url_aggregator::get_port() const
736 ada_log("url_aggregator::get_port");
737 if (components.port == url_components::omitted) {
738 return "";
739 }
740 return helpers::substring(buffer, components.host_end + 1,
741 components.pathname_start);
742}
743
744[[nodiscard]] std::string_view url_aggregator::get_hash() const
746 ada_log("url_aggregator::get_hash");
747 // If this's URL's fragment is either null or the empty string, then return
748 // the empty string. Return U+0023 (#), followed by this's URL's fragment.
749 if (components.hash_start == url_components::omitted) {
750 return "";
751 }
752 if (buffer.size() - components.hash_start <= 1) {
753 return "";
754 }
755 return helpers::substring(buffer, components.hash_start);
756}
757
758[[nodiscard]] std::string_view url_aggregator::get_host() const
760 ada_log("url_aggregator::get_host");
761 // Technically, we should check if there is a hostname, but
762 // the code below works even if there isn't.
763 // if(!has_hostname()) { return ""; }
764 size_t start = components.host_start;
765 if (components.host_end > components.host_start &&
766 buffer[components.host_start] == '@') {
767 start++;
768 }
769 // if we have an empty host, then the space between components.host_end and
770 // components.pathname_start may be occupied by /.
771 if (start == components.host_end) {
772 return {};
773 }
774 return helpers::substring(buffer, start, components.pathname_start);
775}
776
777[[nodiscard]] std::string_view url_aggregator::get_hostname() const
779 ada_log("url_aggregator::get_hostname");
780 // Technically, we should check if there is a hostname, but
781 // the code below works even if there isn't.
782 // if(!has_hostname()) { return ""; }
783 size_t start = components.host_start;
784 // So host_start is not where the host begins.
785 if (components.host_end > components.host_start &&
786 buffer[components.host_start] == '@') {
787 start++;
788 }
789 return helpers::substring(buffer, start, components.host_end);
790}
791
792[[nodiscard]] std::string_view url_aggregator::get_search() const
794 ada_log("url_aggregator::get_search");
795 // If this's URL's query is either null or the empty string, then return the
796 // empty string. Return U+003F (?), followed by this's URL's query.
797 if (components.search_start == url_components::omitted) {
798 return "";
799 }
800 auto ending_index = uint32_t(buffer.size());
801 if (components.hash_start != url_components::omitted) {
802 ending_index = components.hash_start;
803 }
804 if (ending_index - components.search_start <= 1) {
805 return "";
806 }
807 return helpers::substring(buffer, components.search_start, ending_index);
808}
809
810[[nodiscard]] std::string_view url_aggregator::get_protocol() const
812 ada_log("url_aggregator::get_protocol");
813 return helpers::substring(buffer, 0, components.protocol_end);
814}
815
816[[nodiscard]] std::string ada::url_aggregator::to_string() const {
817 ada_log("url_aggregator::to_string buffer:", buffer, " [", buffer.size(),
818 " bytes]");
819 if (!is_valid) {
820 return "null";
821 }
822
823 std::string answer;
824 auto back = std::back_insert_iterator(answer);
825 answer.append("{\n");
826
827 answer.append("\t\"buffer\":\"");
828 helpers::encode_json(buffer, back);
829 answer.append("\",\n");
830
831 answer.append("\t\"protocol\":\"");
832 helpers::encode_json(get_protocol(), back);
833 answer.append("\",\n");
834
835 if (has_credentials()) {
836 answer.append("\t\"username\":\"");
837 helpers::encode_json(get_username(), back);
838 answer.append("\",\n");
839 answer.append("\t\"password\":\"");
840 helpers::encode_json(get_password(), back);
841 answer.append("\",\n");
842 }
843
844 answer.append("\t\"host\":\"");
845 helpers::encode_json(get_host(), back);
846 answer.append("\",\n");
847
848 answer.append("\t\"path\":\"");
849 helpers::encode_json(get_pathname(), back);
850 answer.append("\",\n");
851 answer.append("\t\"opaque path\":");
852 answer.append((has_opaque_path ? "true" : "false"));
853 answer.append(",\n");
854
855 if (components.search_start != url_components::omitted) {
856 answer.append("\t\"query\":\"");
857 helpers::encode_json(get_search(), back);
858 answer.append("\",\n");
859 }
860 if (components.hash_start != url_components::omitted) {
861 answer.append("\t\"fragment\":\"");
862 helpers::encode_json(get_hash(), back);
863 answer.append("\",\n");
864 }
865
866 auto convert_offset_to_string = [](uint32_t offset) -> std::string {
867 if (offset == url_components::omitted) {
868 return "null";
869 } else {
870 return std::to_string(offset);
871 }
872 };
873
874 answer.append("\t\"protocol_end\":");
875 answer.append(convert_offset_to_string(components.protocol_end));
876 answer.append(",\n");
877
878 answer.append("\t\"username_end\":");
879 answer.append(convert_offset_to_string(components.username_end));
880 answer.append(",\n");
881
882 answer.append("\t\"host_start\":");
883 answer.append(convert_offset_to_string(components.host_start));
884 answer.append(",\n");
885
886 answer.append("\t\"host_end\":");
887 answer.append(convert_offset_to_string(components.host_end));
888 answer.append(",\n");
889
890 answer.append("\t\"port\":");
891 answer.append(convert_offset_to_string(components.port));
892 answer.append(",\n");
893
894 answer.append("\t\"pathname_start\":");
895 answer.append(convert_offset_to_string(components.pathname_start));
896 answer.append(",\n");
897
898 answer.append("\t\"search_start\":");
899 answer.append(convert_offset_to_string(components.search_start));
900 answer.append(",\n");
901
902 answer.append("\t\"hash_start\":");
903 answer.append(convert_offset_to_string(components.hash_start));
904 answer.append("\n}");
905
906 return answer;
907}
908
909[[nodiscard]] bool url_aggregator::has_valid_domain() const noexcept {
910 if (components.host_start == components.host_end) {
911 return false;
912 }
913 return checkers::verify_dns_length(get_hostname());
914}
915
916bool url_aggregator::parse_ipv4(std::string_view input, bool in_place) {
917 ada_log("parse_ipv4 ", input, " [", input.size(),
918 " bytes], overlaps with buffer: ",
919 helpers::overlaps(input, buffer) ? "yes" : "no");
921 const bool trailing_dot = (input.back() == '.');
922 if (trailing_dot) {
923 input.remove_suffix(1);
924 }
925 size_t digit_count{0};
926 int pure_decimal_count = 0; // entries that are decimal
927 uint64_t ipv4{0};
928 // we could unroll for better performance?
929 for (; (digit_count < 4) && !(input.empty()); digit_count++) {
930 uint32_t
931 segment_result{}; // If any number exceeds 32 bits, we have an error.
932 bool is_hex = checkers::has_hex_prefix(input);
933 if (is_hex && ((input.length() == 2) ||
934 ((input.length() > 2) && (input[2] == '.')))) {
935 // special case
936 segment_result = 0;
937 input.remove_prefix(2);
938 } else {
939 std::from_chars_result r{};
940 if (is_hex) {
941 ada_log("parse_ipv4 trying to parse hex number");
942 r = std::from_chars(input.data() + 2, input.data() + input.size(),
943 segment_result, 16);
944 } else if ((input.length() >= 2) && input[0] == '0' &&
945 checkers::is_digit(input[1])) {
946 ada_log("parse_ipv4 trying to parse octal number");
947 r = std::from_chars(input.data() + 1, input.data() + input.size(),
948 segment_result, 8);
949 } else {
950 ada_log("parse_ipv4 trying to parse decimal number");
951 pure_decimal_count++;
952 r = std::from_chars(input.data(), input.data() + input.size(),
953 segment_result, 10);
954 }
955 if (r.ec != std::errc()) {
956 ada_log("parse_ipv4 parsing failed");
957 return is_valid = false;
958 }
959 ada_log("parse_ipv4 parsed ", segment_result);
960 input.remove_prefix(r.ptr - input.data());
961 }
962 if (input.empty()) {
963 // We have the last value.
964 // At this stage, ipv4 contains digit_count*8 bits.
965 // So we have 32-digit_count*8 bits left.
966 if (segment_result >= (uint64_t(1) << (32 - digit_count * 8))) {
967 return is_valid = false;
968 }
969 ipv4 <<= (32 - digit_count * 8);
970 ipv4 |= segment_result;
971 goto final;
972 } else {
973 // There is more, so that the value must no be larger than 255
974 // and we must have a '.'.
975 if ((segment_result > 255) || (input[0] != '.')) {
976 return is_valid = false;
977 }
978 ipv4 <<= 8;
979 ipv4 |= segment_result;
980 input.remove_prefix(1); // remove '.'
981 }
982 }
983 if ((digit_count != 4) || (!input.empty())) {
984 ada_log("parse_ipv4 found invalid (more than 4 numbers or empty) ");
985 return is_valid = false;
986 }
987final:
988 ada_log("url_aggregator::parse_ipv4 completed ", get_href(),
989 " host: ", get_host());
990
991 // We could also check r.ptr to see where the parsing ended.
992 if (in_place && pure_decimal_count == 4 && !trailing_dot) {
993 ada_log(
994 "url_aggregator::parse_ipv4 completed and was already correct in the "
995 "buffer");
996 // The original input was already all decimal and we validated it. So we
997 // don't need to do anything.
998 } else {
999 ada_log("url_aggregator::parse_ipv4 completed and we need to update it");
1000 // Optimization opportunity: Get rid of unnecessary string return in ipv4
1001 // serializer.
1002 // TODO: This is likely a bug because it goes back update_base_hostname, not
1003 // what we want to do.
1004 update_base_hostname(
1005 ada::serializers::ipv4(ipv4)); // We have to reserialize the address.
1006 }
1007 host_type = IPV4;
1009 return true;
1010}
1011
1012bool url_aggregator::parse_ipv6(std::string_view input) {
1013 // TODO: Implement in_place optimization: we know that input points
1014 // in the buffer, so we can just check whether the buffer is already
1015 // well formatted.
1016 // TODO: Find a way to merge parse_ipv6 with url.cpp implementation.
1017 ada_log("parse_ipv6 ", input, " [", input.size(), " bytes]");
1019 ADA_ASSERT_TRUE(!helpers::overlaps(input, buffer));
1020 if (input.empty()) {
1021 return is_valid = false;
1022 }
1023 // Let address be a new IPv6 address whose IPv6 pieces are all 0.
1024 std::array<uint16_t, 8> address{};
1025
1026 // Let pieceIndex be 0.
1027 int piece_index = 0;
1028
1029 // Let compress be null.
1030 std::optional<int> compress{};
1031
1032 // Let pointer be a pointer for input.
1033 std::string_view::iterator pointer = input.begin();
1034
1035 // If c is U+003A (:), then:
1036 if (input[0] == ':') {
1037 // If remaining does not start with U+003A (:), validation error, return
1038 // failure.
1039 if (input.size() == 1 || input[1] != ':') {
1040 ada_log("parse_ipv6 starts with : but the rest does not start with :");
1041 return is_valid = false;
1042 }
1043
1044 // Increase pointer by 2.
1045 pointer += 2;
1046
1047 // Increase pieceIndex by 1 and then set compress to pieceIndex.
1048 compress = ++piece_index;
1049 }
1050
1051 // While c is not the EOF code point:
1052 while (pointer != input.end()) {
1053 // If pieceIndex is 8, validation error, return failure.
1054 if (piece_index == 8) {
1055 ada_log("parse_ipv6 piece_index == 8");
1056 return is_valid = false;
1057 }
1058
1059 // If c is U+003A (:), then:
1060 if (*pointer == ':') {
1061 // If compress is non-null, validation error, return failure.
1062 if (compress.has_value()) {
1063 ada_log("parse_ipv6 compress is non-null");
1064 return is_valid = false;
1065 }
1066
1067 // Increase pointer and pieceIndex by 1, set compress to pieceIndex, and
1068 // then continue.
1069 pointer++;
1070 compress = ++piece_index;
1071 continue;
1072 }
1073
1074 // Let value and length be 0.
1075 uint16_t value = 0, length = 0;
1076
1077 // While length is less than 4 and c is an ASCII hex digit,
1078 // set value to value times 0x10 + c interpreted as hexadecimal number, and
1079 // increase pointer and length by 1.
1080 while (length < 4 && pointer != input.end() &&
1081 unicode::is_ascii_hex_digit(*pointer)) {
1082 // https://stackoverflow.com/questions/39060852/why-does-the-addition-of-two-shorts-return-an-int
1083 value = uint16_t(value * 0x10 + unicode::convert_hex_to_binary(*pointer));
1084 pointer++;
1085 length++;
1086 }
1087
1088 // If c is U+002E (.), then:
1089 if (pointer != input.end() && *pointer == '.') {
1090 // If length is 0, validation error, return failure.
1091 if (length == 0) {
1092 ada_log("parse_ipv6 length is 0");
1093 return is_valid = false;
1094 }
1095
1096 // Decrease pointer by length.
1097 pointer -= length;
1098
1099 // If pieceIndex is greater than 6, validation error, return failure.
1100 if (piece_index > 6) {
1101 ada_log("parse_ipv6 piece_index > 6");
1102 return is_valid = false;
1103 }
1104
1105 // Let numbersSeen be 0.
1106 int numbers_seen = 0;
1107
1108 // While c is not the EOF code point:
1109 while (pointer != input.end()) {
1110 // Let ipv4Piece be null.
1111 std::optional<uint16_t> ipv4_piece{};
1112
1113 // If numbersSeen is greater than 0, then:
1114 if (numbers_seen > 0) {
1115 // If c is a U+002E (.) and numbersSeen is less than 4, then increase
1116 // pointer by 1.
1117 if (*pointer == '.' && numbers_seen < 4) {
1118 pointer++;
1119 } else {
1120 // Otherwise, validation error, return failure.
1121 ada_log("parse_ipv6 Otherwise, validation error, return failure");
1122 return is_valid = false;
1123 }
1124 }
1125
1126 // If c is not an ASCII digit, validation error, return failure.
1127 if (pointer == input.end() || !checkers::is_digit(*pointer)) {
1128 ada_log(
1129 "parse_ipv6 If c is not an ASCII digit, validation error, return "
1130 "failure");
1131 return is_valid = false;
1132 }
1133
1134 // While c is an ASCII digit:
1135 while (pointer != input.end() && checkers::is_digit(*pointer)) {
1136 // Let number be c interpreted as decimal number.
1137 int number = *pointer - '0';
1138
1139 // If ipv4Piece is null, then set ipv4Piece to number.
1140 if (!ipv4_piece.has_value()) {
1141 ipv4_piece = number;
1142 }
1143 // Otherwise, if ipv4Piece is 0, validation error, return failure.
1144 else if (ipv4_piece == 0) {
1145 ada_log("parse_ipv6 if ipv4Piece is 0, validation error");
1146 return is_valid = false;
1147 }
1148 // Otherwise, set ipv4Piece to ipv4Piece times 10 + number.
1149 else {
1150 ipv4_piece = *ipv4_piece * 10 + number;
1151 }
1152
1153 // If ipv4Piece is greater than 255, validation error, return failure.
1154 if (ipv4_piece > 255) {
1155 ada_log("parse_ipv6 ipv4_piece > 255");
1156 return is_valid = false;
1157 }
1158
1159 // Increase pointer by 1.
1160 pointer++;
1161 }
1162
1163 // Set address[pieceIndex] to address[pieceIndex] times 0x100 +
1164 // ipv4Piece.
1165 // https://stackoverflow.com/questions/39060852/why-does-the-addition-of-two-shorts-return-an-int
1166 address[piece_index] =
1167 uint16_t(address[piece_index] * 0x100 + *ipv4_piece);
1168
1169 // Increase numbersSeen by 1.
1170 numbers_seen++;
1171
1172 // If numbersSeen is 2 or 4, then increase pieceIndex by 1.
1173 if (numbers_seen == 2 || numbers_seen == 4) {
1174 piece_index++;
1175 }
1176 }
1177
1178 // If numbersSeen is not 4, validation error, return failure.
1179 if (numbers_seen != 4) {
1180 return is_valid = false;
1181 }
1182
1183 // Break.
1184 break;
1185 }
1186 // Otherwise, if c is U+003A (:):
1187 else if ((pointer != input.end()) && (*pointer == ':')) {
1188 // Increase pointer by 1.
1189 pointer++;
1190
1191 // If c is the EOF code point, validation error, return failure.
1192 if (pointer == input.end()) {
1193 ada_log(
1194 "parse_ipv6 If c is the EOF code point, validation error, return "
1195 "failure");
1196 return is_valid = false;
1197 }
1198 }
1199 // Otherwise, if c is not the EOF code point, validation error, return
1200 // failure.
1201 else if (pointer != input.end()) {
1202 ada_log(
1203 "parse_ipv6 Otherwise, if c is not the EOF code point, validation "
1204 "error, return failure");
1205 return is_valid = false;
1206 }
1207
1208 // Set address[pieceIndex] to value.
1209 address[piece_index] = value;
1210
1211 // Increase pieceIndex by 1.
1212 piece_index++;
1213 }
1214
1215 // If compress is non-null, then:
1216 if (compress.has_value()) {
1217 // Let swaps be pieceIndex - compress.
1218 int swaps = piece_index - *compress;
1219
1220 // Set pieceIndex to 7.
1221 piece_index = 7;
1222
1223 // While pieceIndex is not 0 and swaps is greater than 0,
1224 // swap address[pieceIndex] with address[compress + swaps - 1], and then
1225 // decrease both pieceIndex and swaps by 1.
1226 while (piece_index != 0 && swaps > 0) {
1227 std::swap(address[piece_index], address[*compress + swaps - 1]);
1228 piece_index--;
1229 swaps--;
1230 }
1231 }
1232 // Otherwise, if compress is null and pieceIndex is not 8, validation error,
1233 // return failure.
1234 else if (piece_index != 8) {
1235 ada_log(
1236 "parse_ipv6 if compress is null and pieceIndex is not 8, validation "
1237 "error, return failure");
1238 return is_valid = false;
1239 }
1240 // TODO: Optimization opportunity: Get rid of unnecessary string creation.
1241 // TODO: This is likely a bug because it goes back update_base_hostname, not
1242 // what we want to do.
1243 update_base_hostname(ada::serializers::ipv6(address));
1244 ada_log("parse_ipv6 ", get_hostname());
1246 host_type = IPV6;
1247 return true;
1248}
1249
1250bool url_aggregator::parse_opaque_host(std::string_view input) {
1251 ada_log("parse_opaque_host ", input, " [", input.size(), " bytes]");
1253 ADA_ASSERT_TRUE(!helpers::overlaps(input, buffer));
1254 if (std::ranges::any_of(input, ada::unicode::is_forbidden_host_code_point)) {
1255 return is_valid = false;
1256 }
1257
1258 // Return the result of running UTF-8 percent-encode on input using the C0
1259 // control percent-encode set.
1262 if (idx == input.size()) {
1263 update_base_hostname(input);
1264 } else {
1265 // We only create a temporary string if we need to.
1266 update_base_hostname(ada::unicode::percent_encode(
1268 }
1270 return true;
1271}
1272
1273[[nodiscard]] std::string url_aggregator::to_diagram() const {
1274 if (!is_valid) {
1275 return "invalid";
1276 }
1277 std::string answer;
1278 answer.append(buffer);
1279 answer.append(" [");
1280 answer.append(std::to_string(buffer.size()));
1281 answer.append(" bytes]");
1282 answer.append("\n");
1283 // first line
1284 std::string line1;
1285 line1.resize(buffer.size(), ' ');
1286 if (components.hash_start != url_components::omitted) {
1287 line1[components.hash_start] = '|';
1288 }
1289 if (components.search_start != url_components::omitted) {
1290 line1[components.search_start] = '|';
1291 }
1292 if (components.pathname_start != buffer.size()) {
1293 line1[components.pathname_start] = '|';
1294 }
1295 if (components.host_end != buffer.size()) {
1296 line1[components.host_end] = '|';
1297 }
1298 if (components.host_start != buffer.size()) {
1299 line1[components.host_start] = '|';
1300 }
1301 if (components.username_end != buffer.size()) {
1302 line1[components.username_end] = '|';
1303 }
1304 if (components.protocol_end != buffer.size()) {
1305 line1[components.protocol_end] = '|';
1306 }
1307 answer.append(line1);
1308 answer.append("\n");
1309
1310 std::string line2 = line1;
1311 if (components.hash_start != url_components::omitted) {
1312 line2[components.hash_start] = '`';
1313 line1[components.hash_start] = ' ';
1314
1315 for (size_t i = components.hash_start + 1; i < line2.size(); i++) {
1316 line2[i] = '-';
1317 }
1318 line2.append(" hash_start");
1319 answer.append(line2);
1320 answer.append("\n");
1321 }
1322
1323 std::string line3 = line1;
1324 if (components.search_start != url_components::omitted) {
1325 line3[components.search_start] = '`';
1326 line1[components.search_start] = ' ';
1327
1328 for (size_t i = components.search_start + 1; i < line3.size(); i++) {
1329 line3[i] = '-';
1330 }
1331 line3.append(" search_start ");
1332 line3.append(std::to_string(components.search_start));
1333 answer.append(line3);
1334 answer.append("\n");
1335 }
1336
1337 std::string line4 = line1;
1338 if (components.pathname_start != buffer.size()) {
1339 line4[components.pathname_start] = '`';
1340 line1[components.pathname_start] = ' ';
1341 for (size_t i = components.pathname_start + 1; i < line4.size(); i++) {
1342 line4[i] = '-';
1343 }
1344 line4.append(" pathname_start ");
1345 line4.append(std::to_string(components.pathname_start));
1346 answer.append(line4);
1347 answer.append("\n");
1348 }
1349
1350 std::string line5 = line1;
1351 if (components.host_end != buffer.size()) {
1352 line5[components.host_end] = '`';
1353 line1[components.host_end] = ' ';
1354
1355 for (size_t i = components.host_end + 1; i < line5.size(); i++) {
1356 line5[i] = '-';
1357 }
1358 line5.append(" host_end ");
1359 line5.append(std::to_string(components.host_end));
1360 answer.append(line5);
1361 answer.append("\n");
1362 }
1363
1364 std::string line6 = line1;
1365 if (components.host_start != buffer.size()) {
1366 line6[components.host_start] = '`';
1367 line1[components.host_start] = ' ';
1368
1369 for (size_t i = components.host_start + 1; i < line6.size(); i++) {
1370 line6[i] = '-';
1371 }
1372 line6.append(" host_start ");
1373 line6.append(std::to_string(components.host_start));
1374 answer.append(line6);
1375 answer.append("\n");
1376 }
1377
1378 std::string line7 = line1;
1379 if (components.username_end != buffer.size()) {
1380 line7[components.username_end] = '`';
1381 line1[components.username_end] = ' ';
1382
1383 for (size_t i = components.username_end + 1; i < line7.size(); i++) {
1384 line7[i] = '-';
1385 }
1386 line7.append(" username_end ");
1387 line7.append(std::to_string(components.username_end));
1388 answer.append(line7);
1389 answer.append("\n");
1390 }
1391
1392 std::string line8 = line1;
1393 if (components.protocol_end != buffer.size()) {
1394 line8[components.protocol_end] = '`';
1395 line1[components.protocol_end] = ' ';
1396
1397 for (size_t i = components.protocol_end + 1; i < line8.size(); i++) {
1398 line8[i] = '-';
1399 }
1400 line8.append(" protocol_end ");
1401 line8.append(std::to_string(components.protocol_end));
1402 answer.append(line8);
1403 answer.append("\n");
1404 }
1405
1406 if (components.hash_start == url_components::omitted) {
1407 answer.append("note: hash omitted\n");
1408 }
1409 if (components.search_start == url_components::omitted) {
1410 answer.append("note: search omitted\n");
1411 }
1412 if (components.protocol_end > buffer.size()) {
1413 answer.append("warning: protocol_end overflows\n");
1414 }
1415 if (components.username_end > buffer.size()) {
1416 answer.append("warning: username_end overflows\n");
1417 }
1418 if (components.host_start > buffer.size()) {
1419 answer.append("warning: host_start overflows\n");
1420 }
1421 if (components.host_end > buffer.size()) {
1422 answer.append("warning: host_end overflows\n");
1423 }
1424 if (components.pathname_start > buffer.size()) {
1425 answer.append("warning: pathname_start overflows\n");
1426 }
1427 return answer;
1428}
1429
1430void url_aggregator::delete_dash_dot() {
1431 ada_log("url_aggregator::delete_dash_dot");
1433 ADA_ASSERT_TRUE(has_dash_dot());
1434 buffer.erase(components.host_end, 2);
1435 components.pathname_start -= 2;
1436 if (components.search_start != url_components::omitted) {
1437 components.search_start -= 2;
1438 }
1439 if (components.hash_start != url_components::omitted) {
1440 components.hash_start -= 2;
1441 }
1443 ADA_ASSERT_TRUE(!has_dash_dot());
1444}
1445
1446inline void url_aggregator::consume_prepared_path(std::string_view input) {
1447 ada_log("url_aggregator::consume_prepared_path ", input);
1448
1457 uint8_t accumulator = checkers::path_signature(input);
1458 // Let us first detect a trivial case.
1459 // If it is special, we check that we have no dot, no %, no \ and no
1460 // character needing percent encoding. Otherwise, we check that we have no %,
1461 // no dot, and no character needing percent encoding.
1462 constexpr uint8_t need_encoding = 1;
1463 constexpr uint8_t backslash_char = 2;
1464 constexpr uint8_t dot_char = 4;
1465 constexpr uint8_t percent_char = 8;
1466 bool special = type != ada::scheme::NOT_SPECIAL;
1467 bool may_need_slow_file_handling = (type == ada::scheme::type::FILE &&
1469 bool trivial_path =
1470 (special ? (accumulator == 0)
1471 : ((accumulator & (need_encoding | dot_char | percent_char)) ==
1472 0)) &&
1473 (!may_need_slow_file_handling);
1474 if (accumulator == dot_char && !may_need_slow_file_handling) {
1475 // '4' means that we have at least one dot, but nothing that requires
1476 // percent encoding or decoding. The only part that is not trivial is
1477 // that we may have single dots and double dots path segments.
1478 // If we have such segments, then we either have a path that begins
1479 // with '.' (easy to check), or we have the sequence './'.
1480 // Note: input cannot be empty, it must at least contain one character ('.')
1481 // Note: we know that '\' is not present.
1482 if (input[0] != '.') {
1483 size_t slashdot = 0;
1484 bool dot_is_file = true;
1485 for (;;) {
1486 slashdot = input.find("/.", slashdot);
1487 if (slashdot == std::string_view::npos) { // common case
1488 break;
1489 } else { // uncommon
1490 // only three cases matter: /./, /.. or a final /
1491 slashdot += 2;
1492 dot_is_file &= !(slashdot == input.size() || input[slashdot] == '.' ||
1493 input[slashdot] == '/');
1494 }
1495 }
1496 trivial_path = dot_is_file;
1497 }
1498 }
1499 if (trivial_path && is_at_path()) {
1500 ada_log("parse_path trivial");
1501 buffer += '/';
1502 buffer += input;
1503 return;
1504 }
1505 std::string path = std::string(get_pathname());
1506 // We are going to need to look a bit at the path, but let us see if we can
1507 // ignore percent encoding *and* backslashes *and* percent characters.
1508 // Except for the trivial case, this is likely to capture 99% of paths out
1509 // there.
1510 bool fast_path =
1511 (special &&
1512 (accumulator & (need_encoding | backslash_char | percent_char)) == 0) &&
1513 (type != ada::scheme::type::FILE);
1514 if (fast_path) {
1515 ada_log("parse_prepared_path fast");
1516 // Here we don't need to worry about \ or percent encoding.
1517 // We also do not have a file protocol. We might have dots, however,
1518 // but dots must as appear as '.', and they cannot be encoded because
1519 // the symbol '%' is not present.
1520 size_t previous_location = 0; // We start at 0.
1521 do {
1522 size_t new_location = input.find('/', previous_location);
1523 // std::string_view path_view = input;
1524 // We process the last segment separately:
1525 if (new_location == std::string_view::npos) {
1526 std::string_view path_view = input.substr(previous_location);
1527 if (path_view == "..") { // The path ends with ..
1528 // e.g., if you receive ".." with an empty path, you go to "/".
1529 if (path.empty()) {
1530 path = '/';
1531 update_base_pathname(path);
1532 return;
1533 }
1534 // Fast case where we have nothing to do:
1535 if (path.back() == '/') {
1536 update_base_pathname(path);
1537 return;
1538 }
1539 // If you have the path "/joe/myfriend",
1540 // then you delete 'myfriend'.
1541 path.resize(path.rfind('/') + 1);
1542 update_base_pathname(path);
1543 return;
1544 }
1545 path += '/';
1546 if (path_view != ".") {
1547 path.append(path_view);
1548 }
1549 update_base_pathname(path);
1550 return;
1551 } else {
1552 // This is a non-final segment.
1553 std::string_view path_view =
1554 input.substr(previous_location, new_location - previous_location);
1555 previous_location = new_location + 1;
1556 if (path_view == "..") {
1557 size_t last_delimiter = path.rfind('/');
1558 if (last_delimiter != std::string::npos) {
1559 path.erase(last_delimiter);
1560 }
1561 } else if (path_view != ".") {
1562 path += '/';
1563 path.append(path_view);
1564 }
1565 }
1566 } while (true);
1567 } else {
1568 ada_log("parse_path slow");
1569 // we have reached the general case
1570 bool needs_percent_encoding = (accumulator & 1);
1571 std::string path_buffer_tmp;
1572 do {
1573 size_t location = (special && (accumulator & 2))
1574 ? input.find_first_of("/\\")
1575 : input.find('/');
1576 std::string_view path_view = input;
1577 if (location != std::string_view::npos) {
1578 path_view.remove_suffix(path_view.size() - location);
1579 input.remove_prefix(location + 1);
1580 }
1581 // path_buffer is either path_view or it might point at a percent encoded
1582 // temporary string.
1583 std::string_view path_buffer =
1584 (needs_percent_encoding &&
1585 ada::unicode::percent_encode<false>(
1586 path_view, character_sets::PATH_PERCENT_ENCODE, path_buffer_tmp))
1587 ? path_buffer_tmp
1588 : path_view;
1589 if (unicode::is_double_dot_path_segment(path_buffer)) {
1590 helpers::shorten_path(path, type);
1591 if (location == std::string_view::npos) {
1592 path += '/';
1593 }
1594 } else if (unicode::is_single_dot_path_segment(path_buffer) &&
1595 (location == std::string_view::npos)) {
1596 path += '/';
1597 }
1598 // Otherwise, if path_buffer is not a single-dot path segment, then:
1599 else if (!unicode::is_single_dot_path_segment(path_buffer)) {
1600 // If url's scheme is "file", url's path is empty, and path_buffer is a
1601 // Windows drive letter, then replace the second code point in
1602 // path_buffer with U+003A (:).
1603 if (type == ada::scheme::type::FILE && path.empty() &&
1604 checkers::is_windows_drive_letter(path_buffer)) {
1605 path += '/';
1606 path += path_buffer[0];
1607 path += ':';
1608 path_buffer.remove_prefix(2);
1609 path.append(path_buffer);
1610 } else {
1611 // Append path_buffer to url's path.
1612 path += '/';
1613 path.append(path_buffer);
1614 }
1615 }
1616 if (location == std::string_view::npos) {
1617 update_base_pathname(path);
1618 return;
1619 }
1620 } while (true);
1621 }
1622}
1623} // namespace ada
Definitions for URL specific checkers used within Ada.
#define ADA_ASSERT_TRUE(COND)
#define ada_lifetime_bound
#define ada_really_inline
Definition common_defs.h:85
Definitions for helper functions used within Ada.
User-facing functions for URL parsing and manipulation.
constexpr uint8_t QUERY_PERCENT_ENCODE[32]
constexpr uint8_t SPECIAL_QUERY_PERCENT_ENCODE[32]
constexpr uint8_t PATH_PERCENT_ENCODE[32]
constexpr uint8_t C0_CONTROL_PERCENT_ENCODE[32]
constexpr uint8_t USERINFO_PERCENT_ENCODE[32]
constexpr bool has_hex_prefix(std::string_view input)
constexpr bool is_windows_drive_letter(std::string_view input) noexcept
constexpr uint64_t ipv4_fast_fail
Definition checkers.h:129
constexpr bool is_alpha(char x) noexcept
constexpr bool is_digit(char x) noexcept
ada_really_inline constexpr uint64_t try_parse_ipv4_fast(std::string_view input) noexcept
constexpr ada::scheme::type get_scheme_type(std::string_view scheme) noexcept
Definition scheme-inl.h:72
@ NOT_SPECIAL
Definition scheme.h:43
std::string ipv6(const std::array< uint16_t, 8 > &address)
std::string ipv4(uint64_t address)
ada_really_inline size_t percent_encode_index(const std::string_view input, const uint8_t character_set[])
Definition unicode-inl.h:19
Definition ada_idna.h:13
@ IPV6
Definition url_base.h:32
@ IPV4
Definition url_base.h:30
template ada::result< url_aggregator > parse< url_aggregator >(std::string_view input, const url_aggregator *base_url)
tl::expected< result_type, ada::errors > result
ada_warn_unused ada::result< result_type > parse(std::string_view input, const result_type *base_url=nullptr)
URL scheme type definitions and utilities.
Memory-efficient URL representation using a single buffer.
constexpr bool has_non_empty_password() const noexcept
void set_hash(std::string_view input)
constexpr bool validate() const noexcept
void clear_search() override
std::string_view get_search() const ada_lifetime_bound
std::string_view get_hash() const ada_lifetime_bound
std::string to_string() const override
std::string_view get_password() const ada_lifetime_bound
std::string_view get_host() const ada_lifetime_bound
std::string_view get_username() const ada_lifetime_bound
std::string_view get_port() const ada_lifetime_bound
std::string to_diagram() const
constexpr bool has_hostname() const noexcept
bool set_protocol(std::string_view input)
std::string get_origin() const override
constexpr std::string_view get_href() const noexcept ada_lifetime_bound
bool has_valid_domain() const noexcept override
bool set_hostname(std::string_view input)
bool set_password(std::string_view input)
bool set_pathname(std::string_view input)
bool set_href(std::string_view input)
constexpr std::string_view get_pathname() const ada_lifetime_bound
void set_search(std::string_view input)
std::string_view get_hostname() const ada_lifetime_bound
std::string_view get_protocol() const ada_lifetime_bound
constexpr bool has_port() const noexcept
ada_really_inline constexpr bool has_credentials() const noexcept
bool set_host(std::string_view input)
bool set_port(std::string_view input)
constexpr bool has_non_empty_username() const noexcept
bool set_username(std::string_view input)
ada_really_inline constexpr bool is_special() const noexcept
url_host_type host_type
Definition url_base.h:67
bool is_valid
Definition url_base.h:56
bool has_opaque_path
Definition url_base.h:62
static constexpr uint32_t omitted
Definitions for unicode operations.
Inline functions for url aggregator.
Declaration for the ada::url_aggregator class.
Declaration for the URL Components.