Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 33 additions & 2 deletions src/main/java/org/archive/url/BasicURLCanonicalizer.java
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,9 @@ public class BasicURLCanonicalizer implements URLCanonicalizer {
.compile("^(0[0-7]*)(\\.[0-7]+)?(\\.[0-7]+)?(\\.[0-7]+)?$");
Pattern DECIMAL_IP = Pattern
.compile("^([1-9][0-9]*)(\\.[0-9]+)?(\\.[0-9]+)?(\\.[0-9]+)?$");
Pattern MULTIDOT = Pattern.compile("\\.{2,}");

@Override
public void canonicalize(HandyURL url) {
url.setHash(null);
url.setAuthUser(minimalEscape(url.getAuthUser()));
Expand All @@ -55,8 +57,7 @@ public void canonicalize(HandyURL url) {
host = hostE;

}
host = host.replaceAll("^\\.+", "").replaceAll("\\.\\.+", ".")
.replaceAll("\\.$", "");
host = normalizeDots(host);
}

String ip = null;
Expand All @@ -74,6 +75,36 @@ public void canonicalize(HandyURL url) {
url.setPath(escapeOnce(normalizePath(path)));
}

/**
* Normalize dots in the host name.
*
* @param host
* @return host name with all sequences of dots replaced with a single dot,
* and all leading and trailing dots removed
*/
private String normalizeDots(String host) {
if (host.indexOf('.') == -1) {
return host;
}
int start = 0, end = host.length();
boolean changed = false;
while (start < end && host.charAt(start) == '.') {
start++;
changed = true;
}
while (end > start && host.charAt(end - 1) == '.') {
end--;
changed = true;
}
if (changed) {
host = host.substring(start, end);
}
if (host.contains("..")) {
host = MULTIDOT.matcher(host).replaceAll(".");
}
return host;
}

private static final Pattern SINGLE_FORWARDSLASH_PATTERN = Pattern
.compile("/");

Expand Down
10 changes: 10 additions & 0 deletions src/test/java/org/archive/url/BasicURLCanonicalizerTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -286,6 +286,16 @@ public void testUnicodeEscaping() throws URISyntaxException {
checkCanonicalization("http://example.org/%F0%9F%82%A1", "http://example.org/%F0%9F%82%A1");
}

@Test
public void testHostDots() throws URISyntaxException {
checkCanonicalization("https://foobar.org./", "https://foobar.org/");
checkCanonicalization("https://.foobar.org/", "https://foobar.org/");
checkCanonicalization("https://foo...bar.org/", "https://foo.bar.org/");
checkCanonicalization("https://...foo...bar.org.../", "https://foo.bar.org/");
checkCanonicalization("https://localhost/path/file.txt", "https://localhost/path/file.txt");
checkCanonicalization("https://....../path/file.txt", "https:///path/file.txt");
}

private void checkCanonicalization(String in, String want) throws URISyntaxException {
HandyURL h = URLParser.parse(in);
guc.canonicalize(h);
Expand Down