Apache Nutch is an extensible and scalable web crawler
NUTCH-3176 URLUtil and urlnormalizer-basic: add support for IDNA2008
Sebastian Nagel54efa9f0c2f1
diff --git a/conf/nutch-default.xml b/conf/nutch-default.xmlindex cc0e8d438..f26ad419c 100644--- a/conf/nutch-default.xml+++ b/conf/nutch-default.xml@@ -1556,6 +1556,17 @@</description></property>+<property>+ <name>urlnormalizer.basic.host.idna2008</name>+ <value>false</value>+ <description>If true, let urlnormalizer-basic+ normalize Internationalized Domain Names (IDNs) using the+ standard IDNA2008 (RFC 5890). If false, use IDNA2003 (RFC 3490).+ Note that urlnormalizer.basic.host.idn must be set, otherwise+ this property has no effect.+ </description>+</property>+<property><name>urlnormalizer.basic.host.trim-trailing-dot</name><value>false</value>diff --git a/ivy/ivy.xml b/ivy/ivy.xmlindex 70763adc0..944a329a0 100644--- a/ivy/ivy.xml+++ b/ivy/ivy.xml@@ -118,6 +118,7 @@<!-- Required for JUnit 6 (Jupiter) test execution --><dependency org="org.junit.jupiter" name="junit-jupiter-engine" rev="6.0.3" conf="test->default"/><dependency org="org.junit.jupiter" name="junit-jupiter-api" rev="6.0.3" conf="test->default"/>+ <dependency org="org.junit.jupiter" name="junit-jupiter-params" rev="6.0.3" conf="test->default"/><!-- Mockito for mocking in tests --><dependency org="org.mockito" name="mockito-core" rev="5.18.0" conf="test->default"/><dependency org="org.mockito" name="mockito-junit-jupiter" rev="5.18.0" conf="test->default"/>diff --git a/src/java/org/apache/nutch/util/URLUtil.java b/src/java/org/apache/nutch/util/URLUtil.javaindex 44c6309d2..ec5aefbe4 100644--- a/src/java/org/apache/nutch/util/URLUtil.java+++ b/src/java/org/apache/nutch/util/URLUtil.java@@ -16,6 +16,7 @@*/package org.apache.nutch.util;+import java.lang.invoke.MethodHandles;import java.net.IDN;import java.net.MalformedURLException;import java.net.URI;@@ -23,11 +24,22 @@ import java.net.URL;import java.util.Locale;import java.util.regex.Pattern;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;++import com.ibm.icu.text.IDNA;+import crawlercommons.domains.EffectiveTldFinder;/** Utility class for URL analysis */public class URLUtil {+ private static final Logger LOG = LoggerFactory+ .getLogger(MethodHandles.lookup().lookupClass());++ private static final IDNA idna = IDNA.getUTS46Instance(+ IDNA.NONTRANSITIONAL_TO_ASCII | IDNA.NONTRANSITIONAL_TO_UNICODE);+/*** Resolve relative URL-s and fix a java.net.URL error in handling of URLs* with pure query targets.@@ -520,17 +532,29 @@ public class URLUtil {return url.getProtocol();}+ public static boolean isAscii(String str) {+ char[] chars = str.toCharArray();+ for (char c : chars) {+ if (c > 127) {+ return false;+ }+ }+ return true;+ }+public static String toASCII(String url) {try {URL u = new URL(url);String host = u.getHost();- if (host == null || host.isEmpty()) {- // no host name => no punycoded domain name- // also do not add additional slashes for file: URLs (NUTCH-1880)+ if (host == null || host.isEmpty() || isAscii(host)) {+ // - no host name => no punycoded domain name+ // - also do not add additional slashes for file: URLs (NUTCH-1880)+ // - do nothing if host is already ASCII-onlyreturn url;}- URI p = new URI(u.getProtocol(), u.getUserInfo(), IDN.toASCII(host),- u.getPort(), u.getPath(), u.getQuery(), u.getRef());+ URI p = new URI(u.getProtocol(), u.getUserInfo(),+ convertIDNA2008(u.getHost(), true), u.getPort(), u.getPath(),+ u.getQuery(), u.getRef());return p.toString();} catch (Exception e) {@@ -542,9 +566,10 @@ public class URLUtil {try {URL u = new URL(url);String host = u.getHost();- if (host == null || host.isEmpty()) {- // no host name => no punycoded domain name- // also do not add additional slashes for file: URLs (NUTCH-1880)+ if (host == null || host.isEmpty() || !host.contains("xn--")) {+ // - no host name => no punycoded domain name+ // - also do not add additional slashes for file: URLs (NUTCH-1880)+ // - ???return url;}StringBuilder sb = new StringBuilder();@@ -554,7 +579,7 @@ public class URLUtil {sb.append(u.getUserInfo());sb.append('@');}- sb.append(IDN.toUnicode(host));+ sb.append(convertIDNA2008(u.getHost(), false));if (u.getPort() != -1) {sb.append(':');sb.append(u.getPort());@@ -572,22 +597,83 @@ public class URLUtil {}/**- * For testing- * @param args print with no args to get help+ * Convert IDN host to ASCII or Unicode using Java's built-in {@link IDN}+ * class.+ *+ * The conversion supports only IDNA2003, it does not support IDNA2008.+ * However, unless the parameter <code>strictIDNA2003</code> is true, the+ * methods {@link IDN#toASCII(String, int)} resp.+ * {@link IDN#toUnicode(String, int)} are called passing the flag+ * {@link IDN#ALLOW_UNASSIGNED} to avoid that the conversion fails on+ * characters not in the repertoire of Unicode 3.2.+ *+ * @param host+ * host name to be converted+ * @param toAscii+ * if true convert to ASCII, otherwise to Unicode+ * @param strictIDNA2003+ * if true, do+ * @return converted host name+ * @throws MalformedURLException+ * if the conversion fails*/- public static void main(String[] args) {-- if (args.length != 1) {- System.err.println("Usage : URLUtil <url>");- return;+ public static String convertIDNA2003(String host, boolean toAscii,+ boolean strictIDNA2003) throws MalformedURLException {+ try {+ if (toAscii) {+ return IDN.toASCII(host, strictIDNA2003 ? 0 : IDN.ALLOW_UNASSIGNED);+ } else {+ return IDN.toUnicode(host, strictIDNA2003 ? 0 : IDN.ALLOW_UNASSIGNED);+ }+ } catch (IllegalArgumentException | IndexOutOfBoundsException e) {+ // IllegalArgumentException: thrown if the input string contains+ // non-convertible Unicode codepoints+ // IndexOutOfBoundsException: thrown (undocumented) if one "label"+ // (non-ASCII dot-separated segment) is longer than 256 characters,+ // cf. https://bugs.openjdk.java.net/browse/JDK-6806873+ LOG.debug("Failed to convert IDN host {}: ", host, e);+ throw (MalformedURLException) new MalformedURLException(+ "Invalid IDN " + host + ": " + e.getMessage()).initCause(e);}+ }- String url = args[0];- try {- System.out.println(URLUtil.getDomainName(new URL(url)));- } catch (MalformedURLException ex) {- ex.printStackTrace();+ /**+ * Convert IDN host to ASCII or Unicode using ICU's {@link IDNA} class.+ *+ * The conversion supports IDNA2008 names.+ *+ * @param host+ * host name to be converted+ * @param toAscii+ * if true convert to ASCII, otherwise to Unicode+ * @return converted host name+ * @throws MalformedURLException+ * if the conversion fails+ */+ public static String convertIDNA2008(String host, boolean toAscii)+ throws MalformedURLException {+ final IDNA.Info idnaInfo = new IDNA.Info();+ final StringBuilder hostConverted = new StringBuilder();+ if (toAscii) {+ idna.nameToASCII(host, hostConverted, idnaInfo);+ } else {+ idna.nameToUnicode(host, hostConverted, idnaInfo);+ }+ if (idnaInfo.hasErrors()) {+ StringBuilder msg = new StringBuilder();+ for (IDNA.Error error : idnaInfo.getErrors()) {+ if (msg.length() == 0) {+ msg.append("Invalid IDNA2008 host").append(host).append(": ");+ } else {+ msg.append(", ");+ }+ msg.append(error.name());+ }+ String errorMsg = msg.toString();+ LOG.debug("Failed to convert IDN host {}: {}", host, errorMsg);+ throw new MalformedURLException(errorMsg);}+ return hostConverted.toString();}/**@@ -610,4 +696,24 @@ public class URLUtil {&& url.getRef() == null //&& url.getUserInfo() == null;}++ /**+ * For testing+ * @param args print with no args to get help+ */+ public static void main(String[] args) {++ if (args.length != 1) {+ System.err.println("Usage : URLUtil <url>");+ System.err.println("\nExtract and print pay-level domain names for the input URL");+ return;+ }++ String url = args[0];+ try {+ System.out.println(URLUtil.getDomainName(new URL(url)));+ } catch (MalformedURLException ex) {+ ex.printStackTrace();+ }+ }}diff --git a/src/plugin/urlnormalizer-basic/src/java/org/apache/nutch/net/urlnormalizer/basic/BasicURLNormalizer.java b/src/plugin/urlnormalizer-basic/src/java/org/apache/nutch/net/urlnormalizer/basic/BasicURLNormalizer.javaindex 2123d8fa9..165ee548c 100644--- a/src/plugin/urlnormalizer-basic/src/java/org/apache/nutch/net/urlnormalizer/basic/BasicURLNormalizer.java+++ b/src/plugin/urlnormalizer-basic/src/java/org/apache/nutch/net/urlnormalizer/basic/BasicURLNormalizer.java@@ -16,12 +16,11 @@*/package org.apache.nutch.net.urlnormalizer.basic;-import java.lang.invoke.MethodHandles;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.UnsupportedEncodingException;-import java.net.IDN;+import java.lang.invoke.MethodHandles;import java.net.MalformedURLException;import java.net.URISyntaxException;import java.net.URL;@@ -36,6 +35,7 @@ import org.apache.hadoop.conf.Configuration;import org.apache.nutch.net.URLNormalizer;import org.apache.nutch.net.URLNormalizers;import org.apache.nutch.util.NutchConfiguration;+import org.apache.nutch.util.URLUtil;import org.slf4j.Logger;import org.slf4j.LoggerFactory;@@ -47,6 +47,12 @@ import org.slf4j.LoggerFactory;* <li>normalize <a href=* "https://en.wikipedia.org/wiki/Percent-encoding#Percent-encoding_in_a_URI">* percent-encoding</a> in URL paths</li>+ * <li>normalize the host name if it is an Internationalized Domain Name (IDN)+ * to ASCII or Unicode, depending on the configuration properties+ * <code>urlnormalizer.basic.host.idn</code> and+ * <code>urlnormalizer.basic.host.idna2008</code></li>+ * <li>remove a trailing dot in the host name (if the property+ * <code>urlnormalizer.basic.host.trim-trailing-dot</code> is true)</li>* </ul>*/public class BasicURLNormalizer implements URLNormalizer {@@ -54,6 +60,7 @@ public class BasicURLNormalizer implements URLNormalizer {.getLogger(MethodHandles.lookup().lookupClass());public final static String NORM_HOST_IDN = "urlnormalizer.basic.host.idn";+ public final static String NORM_HOST_IDNA_2008 = "urlnormalizer.basic.host.idna2008";public final static String NORM_HOST_TRIM_TRAILING_DOT = "urlnormalizer.basic.host.trim-trailing-dot";/**@@ -132,20 +139,11 @@ public class BasicURLNormalizer implements URLNormalizer {|| (0x30 <= c && c <= 0x39);}- private static boolean isAscii(String str) {- char[] chars = str.toCharArray();- for (char c : chars) {- if (c > 127) {- return false;- }- }- return true;- }-private Configuration conf;private boolean hostIDNtoASCII;private boolean hostASCIItoIDN;+ private boolean hostIDNA2008;private boolean hostTrimTrailingDot;@Override@@ -162,6 +160,7 @@ public class BasicURLNormalizer implements URLNormalizer {} else if (normIdn.equalsIgnoreCase("toUnicode")) {hostASCIItoIDN = true;}+ hostIDNA2008 = conf.getBoolean(NORM_HOST_IDNA_2008, false);hostTrimTrailingDot = conf.getBoolean(NORM_HOST_TRIM_TRAILING_DOT, false);}@@ -429,21 +428,18 @@ public class BasicURLNormalizer implements URLNormalizer {// 3. if configured: convert between Unicode and ASCII forms// for Internationalized Domain Names (IDNs)- if (hostIDNtoASCII && !isAscii(host)) {- try {- host = IDN.toASCII(host);- } catch (IllegalArgumentException | IndexOutOfBoundsException e) {- // IllegalArgumentException: thrown if the input string contains- // non-convertible Unicode codepoints- // IndexOutOfBoundsException: thrown (undocumented) if one "label"- // (non-ASCII dot-separated segment) is longer than 256 characters,- // cf. https://bugs.openjdk.java.net/browse/JDK-6806873- LOG.debug("Failed to convert IDN host {}: ", host, e);- throw (MalformedURLException) new MalformedURLException(- "Invalid IDN " + host + ": " + e.getMessage()).initCause(e);+ if (hostIDNtoASCII && !URLUtil.isAscii(host)) {+ if (hostIDNA2008) {+ host = URLUtil.convertIDNA2008(host, true);+ } else {+ host = URLUtil.convertIDNA2003(host, true, false);}} else if (hostASCIItoIDN && host.contains("xn--")) {- host = IDN.toUnicode(host);+ if (hostIDNA2008) {+ host = URLUtil.convertIDNA2008(host, false);+ } else {+ host = URLUtil.convertIDNA2003(host, false, false);+ }}// 4. optionally trim a trailing dotdiff --git a/src/plugin/urlnormalizer-basic/src/test/org/apache/nutch/net/urlnormalizer/basic/TestBasicURLNormalizer.java b/src/plugin/urlnormalizer-basic/src/test/org/apache/nutch/net/urlnormalizer/basic/TestBasicURLNormalizer.javaindex a6bad41f2..1d3813ac8 100644--- a/src/plugin/urlnormalizer-basic/src/test/org/apache/nutch/net/urlnormalizer/basic/TestBasicURLNormalizer.java+++ b/src/plugin/urlnormalizer-basic/src/test/org/apache/nutch/net/urlnormalizer/basic/TestBasicURLNormalizer.java@@ -274,6 +274,46 @@ public class TestBasicURLNormalizer {"https://www.example.org/");}+ /**+ * Test for IDNA2008 and IDNA2003 compatibility.+ */+ @Test+ public void testHostNameIDNA2008() throws Exception {+ // IDNA2008 (https://www.rfc-editor.org/rfc/rfc5890.html#section-1.1)+ BasicURLNormalizer norm = new BasicURLNormalizer();+ conf = NutchConfiguration.create();+ conf.set(BasicURLNormalizer.NORM_HOST_IDN, "toAscii");+ norm.setConf(conf);++ // IDNA2003 / RFC 3490+ // Note: IDNA2008 and IDNA2003 deviate for this example+ normalizeTest(norm, "https://straße.de/", "https://strasse.de/");++ // Verify that characters not in Unicode 3.2 do not fail the normalization+ normalizeTest(norm, "https://example.ᬩᬮᬶ.id/", "https://example.xn--9tfky.id/");++ // IDNA2008 / RFC 5890+ conf.setBoolean(BasicURLNormalizer.NORM_HOST_IDNA_2008, true);+ norm.setConf(conf);+ // Note: this is different from IDNA2003+ normalizeTest(norm, "https://straße.de/", "https://xn--strae-oqa.de/");++ // Verify that characters not in Unicode 3.2 do not fail the normalization+ normalizeTest(norm, "https://example.ᬩᬮᬶ.id/", "https://example.xn--9tfky.id/");++ // test conversion to Unicode (IDNA2008)+ conf.set(BasicURLNormalizer.NORM_HOST_IDN, "toUnicode");+ norm.setConf(conf);+ normalizeTest(norm, "https://xn--strae-oqa.de/", "https://straße.de/");+ normalizeTest(norm, "https://example.xn--9tfky.id/", "https://example.ᬩᬮᬶ.id/");++ // test conversion to Unicode (IDNA2003)+ conf.setBoolean(BasicURLNormalizer.NORM_HOST_IDNA_2008, false);+ norm.setConf(conf);+ normalizeTest(norm, "https://xn--strae-oqa.de/", "https://xn--strae-oqa.de/");+ normalizeTest(norm, "https://example.xn--9tfky.id/", "https://example.ᬩᬮᬶ.id/");+ }+/*** Test that normalizer throws MalformedURLException for invalid URLs*/diff --git a/src/test/org/apache/nutch/util/TestURLUtil.java b/src/test/org/apache/nutch/util/TestURLUtil.javaindex 092edb9c1..b0f036a1c 100644--- a/src/test/org/apache/nutch/util/TestURLUtil.java+++ b/src/test/org/apache/nutch/util/TestURLUtil.java@@ -16,11 +16,16 @@*/package org.apache.nutch.util;+import java.net.MalformedURLException;import java.net.URL;import org.junit.jupiter.api.Test;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.CsvSource;-import static org.junit.jupiter.api.Assertions.*;+import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertNotNull;+import static org.junit.jupiter.api.Assertions.assertNull;/** Test class for URLUtil */public class TestURLUtil {@@ -312,7 +317,12 @@ public class TestURLUtil {assertEquals("http://www.medizin.uni-tübingen.de:8080/search.php?q=abc#p1",URLUtil.toUNICODE("http://www.medizin.xn--uni-tbingen-xhb.de:8080/search.php?q=abc#p1"));-+ // do not fail on characters not in Unicode 3.2+ assertEquals("https://example.ᬩᬮᬶ.id/",+ URLUtil.toUNICODE("https://example.xn--9tfky.id/"));+ // IDNA2008+ assertEquals("http://straße.de/",+ URLUtil.toUNICODE("http://xn--strae-oqa.de/"));}@Test@@ -324,6 +334,50 @@ public class TestURLUtil {assertEquals("http://www.medizin.xn--uni-tbingen-xhb.de:8080/search.php?q=abc#p1",URLUtil.toASCII("http://www.medizin.uni-tübingen.de:8080/search.php?q=abc#p1"));+ // IDNA2003+ // assertEquals("http://strasse.de/",+ // URLUtil.toASCII("http://straße.de/"));+ // do not fail on characters not in Unicode 3.2+ assertEquals("https://example.xn--9tfky.id/",+ URLUtil.toASCII("https://example.ᬩᬮᬶ.id/"));+ // IDNA2008+ assertEquals("http://xn--strae-oqa.de/",+ URLUtil.toASCII("http://straße.de/"));+ }++ @ParameterizedTest+ @CsvSource({ //+ "www.xn--evir-zoa.com,www.çevir.com,IDNA2003,true", //+ "xn--uni-tbingen-xhb.de,uni-tübingen.de,IDNA2003,true", //+ "example.xn--9tfky.id,example.ᬩᬮᬶ.id,IDNA2008,true", //+ "xn--53h.example,☕.example,IDNA2008,true", //+ "xn--0ca.xn--ssa73l,à.א̈,IDNA2008,true", //+ // Note: IDNA2008 and IDNA2003 deviate for the following example+ "xn--strae-oqa.de,straße.de,IDNA2008,true", //+ "strasse.de,straße.de,IDNA2003,false", //+ "strasse.de,strasse.de,IDNA2003,true", //+ })+ public final void testConvertHost(String ascii, String unicode, String type,+ boolean roundTrip) throws Exception {+ if ("IDNA2008".equals(type)) {+ assertEquals(ascii, URLUtil.convertIDNA2008(unicode, true));+ assertEquals(unicode, URLUtil.convertIDNA2008(ascii, false));+ try {+ assertNotNull(URLUtil.convertIDNA2003(unicode, true, false));+ } catch (MalformedURLException e) {+ /*+ * Ok. A IDNA2008 input may raise an exception when using the IDNA2003+ * method+ */+ }+ } else if ("IDNA2003".equals(type)) {+ assertEquals(ascii, URLUtil.convertIDNA2003(unicode, true, true));+ assertEquals(ascii, URLUtil.convertIDNA2003(unicode, true, false));+ if (roundTrip) {+ assertEquals(unicode, URLUtil.convertIDNA2003(ascii, false, true));+ assertEquals(unicode, URLUtil.convertIDNA2003(ascii, false, false));+ }+ }}@Test