Skip to content
Closed
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
68 changes: 48 additions & 20 deletions java/org/apache/catalina/connector/Request.java
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
Expand Down Expand Up @@ -3136,40 +3137,67 @@ protected void parseLocales() {
*/
protected void parseLocalesHeader(String value, TreeMap<Double,ArrayList<Locale>> locales) {

// Determine how many more entries are of interest. One more than the
// maximum is parsed so that a header that exceeds the limit is
// rejected rather than silently truncated. Parsing no further entries
// once the limit is reached avoids creating Locale objects for entries
// that can never be used.
int maxElements = -1;
if (maxLocaleCount > -1) {
int current = 0;
for (ArrayList<Locale> list : locales.values()) {
current += list.size();
}
maxElements = maxLocaleCount + 1 - current;
if (maxElements < 1) {
return;
}
}

List<AcceptLanguage> acceptLanguages;
try {
if (USE_STANDARD_ACCEPT_LANGUAGE_PARSER) {
acceptLanguages = AcceptLanguage.parse(new StringReader(value), maxElements);
acceptLanguages = AcceptLanguage.parse(new StringReader(value), -1);
} else {
acceptLanguages = AcceptLanguage2.parse(new StringReader(value), maxElements);
acceptLanguages = AcceptLanguage2.parse(new StringReader(value), -1);
}
} catch (IOException ioe) {
// Mal-formed headers are ignore. Do the same in the unlikely event
// of an IOException.
return;
}

if (maxLocaleCount < 0) {
for (AcceptLanguage acceptLanguage : acceptLanguages) {
// Add a new Locale to the list of Locales for this quality level
Double key = Double.valueOf(-acceptLanguage.getQuality()); // Reverse the order
locales.computeIfAbsent(key, k -> new ArrayList<>()).add(acceptLanguage.getLocale());
}
return;
}

// Retain the entries with the highest quality values. The order of the
// entries in the header(s) cannot be relied upon to indicate priority
// (RFC 9110, section 12.5.4) so the whole header is parsed. One more
// than the maximum is retained so that a header that exceeds the limit
// can be detected. The Locale is only created for the entries that are
// retained.
int maxElements = maxLocaleCount == Integer.MAX_VALUE ? maxLocaleCount : maxLocaleCount + 1;
if (acceptLanguages.size() > maxElements) {
// The sort is stable so entries with the same quality value remain
// in header order
acceptLanguages.sort(Comparator.comparingDouble(AcceptLanguage::getQuality).reversed());
acceptLanguages = acceptLanguages.subList(0, maxElements);
}

int current = 0;
for (ArrayList<Locale> list : locales.values()) {
current += list.size();
}

for (AcceptLanguage acceptLanguage : acceptLanguages) {
// Add a new Locale to the list of Locales for this quality level
Double key = Double.valueOf(-acceptLanguage.getQuality()); // Reverse the order
if (current >= maxElements) {
// Replace the entry with the lowest quality value, and the last
// one with that quality value, if this entry has a higher
// quality value. Otherwise, this entry is not retained.
Double lowestKey = locales.lastKey();
if (key.compareTo(lowestKey) >= 0) {
continue;
}
ArrayList<Locale> lowest = locales.get(lowestKey);
lowest.remove(lowest.size() - 1);
if (lowest.isEmpty()) {
locales.remove(lowestKey);
}
current--;
}
// Add a new Locale to the list of Locales for this quality level
locales.computeIfAbsent(key, k -> new ArrayList<>()).add(acceptLanguage.getLocale());
current++;
}
}

Expand Down
33 changes: 30 additions & 3 deletions java/org/apache/tomcat/util/http/parser/AcceptLanguage.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,17 @@
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.function.Function;

/**
* Represents a single language entry from an Accept-Language header.
*/
public class AcceptLanguage {

private final Locale locale;
private final String languageTag;
private final Function<String,Locale> localeFactory;
private final double quality;
private Locale locale;

/**
* Constructs a new AcceptLanguage.
Expand All @@ -37,7 +40,26 @@ public class AcceptLanguage {
* @param quality The quality value for this language entry
*/
protected AcceptLanguage(Locale locale, double quality) {
this.languageTag = null;
this.localeFactory = null;
this.quality = quality;
this.locale = locale;
}

/**
* Constructs a new AcceptLanguage for which the Locale is only created
* when it is first requested. This allows callers to select entries based
* on the quality value without creating Locale objects for the entries
* that are not used.
*
* @param languageTag The language tag of this language entry
* @param quality The quality value for this language entry
* @param localeFactory The function used to create the Locale from the
* language tag
*/
AcceptLanguage(String languageTag, double quality, Function<String,Locale> localeFactory) {
this.languageTag = languageTag;
this.localeFactory = localeFactory;
this.quality = quality;
}

Expand All @@ -47,7 +69,12 @@ protected AcceptLanguage(Locale locale, double quality) {
* @return The locale of this language entry
*/
public Locale getLocale() {
return locale;
Locale result = locale;
if (result == null && localeFactory != null) {
result = localeFactory.apply(languageTag);
locale = result;
}
return result;
}

/**
Expand Down Expand Up @@ -124,7 +151,7 @@ public static List<AcceptLanguage> parse(StringReader input, int maxElements) th
}

if (quality > 0) {
result.add(new AcceptLanguage(Locale.forLanguageTag(languageTag), quality));
result.add(new AcceptLanguage(languageTag, quality, Locale::forLanguageTag));
}
} while (true);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ public static List<AcceptLanguage> parse(StringReader input, int maxElements) th
}

if (quality > 0) {
result.add(new AcceptLanguage(toLegacyLocale(languageTag), quality));
result.add(new AcceptLanguage(languageTag, quality, AcceptLanguage2::toLegacyLocale));
}
} while (true);

Expand Down
82 changes: 80 additions & 2 deletions test/org/apache/catalina/connector/TestRequest.java
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
import java.nio.charset.UnsupportedCharsetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
Expand Down Expand Up @@ -839,8 +840,7 @@ private static int localeCount(Connector connector, String acceptLanguage) {

/*
* When multiple Accept-Language headers are present the limit
* applies to the combined set of locales and parsing stops
* early on the header in which the limit is exceeded.
* applies to the combined set of locales.
*/
@Test
public void testAcceptLanguageLocaleLimitMultipleHeaders() throws Exception {
Expand Down Expand Up @@ -869,6 +869,84 @@ private static int localeCount(Connector connector, String... acceptLanguages) {
return count;
}

/*
* When the limit is exceeded, the locales with the highest quality
* values are retained regardless of the order in which they appear
* in the header.
*/
@Test
public void testAcceptLanguageLocaleLimitQuality() throws Exception {
Connector connector = new Connector();
connector.setMaxLocaleCount(2);

Assert.assertEquals(locales("ja", "it"), getLocales(connector, "de;q=0.1,fr;q=0.2,it;q=0.3,ja"));
}

/*
* Locales with the same quality value are retained in header order.
*/
@Test
public void testAcceptLanguageLocaleLimitSameQuality() throws Exception {
Connector connector = new Connector();
connector.setMaxLocaleCount(2);

Assert.assertEquals(locales("aa", "cc"), getLocales(connector, "aa,bb;q=0.5,cc,dd"));
}

/*
* The highest quality locales are selected across multiple
* Accept-Language headers and locales with the same quality value
* are retained in the order of the headers.
*/
@Test
public void testAcceptLanguageLocaleLimitQualityMultipleHeaders() throws Exception {
Connector connector = new Connector();
connector.setMaxLocaleCount(2);

Assert.assertEquals(locales("ja", "en"), getLocales(connector, "de;q=0.1,fr;q=0.2", "ja,en;q=0.9"));
Assert.assertEquals(locales("cc", "aa"), getLocales(connector, "aa;q=0.5", "bb;q=0.5,cc"));
}

/*
* The highest quality locales are retained when the header contains
* far more entries than the limit.
*/
@Test
public void testAcceptLanguageLocaleLimitQualityHeaderFlood() throws Exception {
StringBuilder acceptLanguage = new StringBuilder();
for (int i = 1; i < 1000; i++) {
if (i > 1) {
acceptLanguage.append(',');
}
acceptLanguage.append(String.format("aa-%03d;q=0.%03d", Integer.valueOf(i), Integer.valueOf(i)));
}

List<Locale> expected = new ArrayList<>();
for (int i = 999; i > 989; i--) {
expected.add(Locale.forLanguageTag(String.format("aa-%03d", Integer.valueOf(i))));
}

Assert.assertEquals(expected, getLocales(new Connector(), acceptLanguage.toString()));
}

private static List<Locale> locales(String... languageTags) {
List<Locale> result = new ArrayList<>();
for (String languageTag : languageTags) {
result.add(Locale.forLanguageTag(languageTag));
}
return result;
}

private static List<Locale> getLocales(Connector connector, String... acceptLanguages) {
org.apache.coyote.Request coyoteRequest = new org.apache.coyote.Request();
for (String acceptLanguage : acceptLanguages) {
coyoteRequest.getMimeHeaders().addValue("accept-language").setString(acceptLanguage);
}
Request request = new Request(connector, coyoteRequest);

return Collections.list(request.getLocales());
}

@Test
public void getLocaleMultipleHeaders01() throws Exception {
TesterRequest req = new TesterRequest();
Expand Down
23 changes: 23 additions & 0 deletions test/org/apache/tomcat/util/http/parser/TestAcceptLanguage.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import java.io.StringReader;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.atomic.AtomicInteger;

import org.junit.Assert;
import org.junit.Test;
Expand Down Expand Up @@ -416,4 +417,26 @@ public void testLimited04() throws Exception {
Assert.assertEquals(L_FR, actual.get(1).getLocale());
Assert.assertEquals(Locale.forLanguageTag("de"), actual.get(2).getLocale());
}


/*
* The Locale is only created when it is first requested so that
* entries can be selected by quality without creating Locale
* objects for entries that are not used.
*/
@Test
public void testLazyLocale() {
AtomicInteger count = new AtomicInteger();
AcceptLanguage acceptLanguage = new AcceptLanguage("en", Q0_500, tag -> {
count.incrementAndGet();
return Locale.forLanguageTag(tag);
});

Assert.assertEquals(0, count.get());
Assert.assertEquals(Q0_500, acceptLanguage.getQuality(), 0.0001);
Assert.assertEquals(0, count.get());
Assert.assertEquals(L_EN, acceptLanguage.getLocale());
Assert.assertEquals(L_EN, acceptLanguage.getLocale());
Assert.assertEquals(1, count.get());
}
}
8 changes: 5 additions & 3 deletions webapps/docs/config/ajp.xml
Original file line number Diff line number Diff line change
Expand Up @@ -176,9 +176,11 @@
<attribute name="maxLocaleCount" required="false">
<p>The maximum number of locales (obtained from the
<code>Accept-Language</code> header(s)) that are permitted for a request.
Locales above this limit will be ignored when the locales are
parsed and an info will be logged. A value of less than 0 means no
limit. If not specified, a default of 10 is used.</p>
If this limit is exceeded, the locales with the highest quality values
are retained, the remaining locales are ignored and an info will be
logged. Locales with the same quality value are retained in the order
they appear in the header(s). A value of less than 0 means no limit. If
not specified, a default of 10 is used.</p>
</attribute>

<attribute name="maxParameterCount" required="false">
Expand Down
8 changes: 5 additions & 3 deletions webapps/docs/config/http.xml
Original file line number Diff line number Diff line change
Expand Up @@ -172,9 +172,11 @@
<attribute name="maxLocaleCount" required="false">
<p>The maximum number of locales (obtained from the
<code>Accept-Language</code> header(s)) that are permitted for a request.
Locales above this limit will be ignored when the locales are
parsed and an info will be logged. A value of less than 0 means no
limit. If not specified, a default of 10 is used.</p>
If this limit is exceeded, the locales with the highest quality values
are retained, the remaining locales are ignored and an info will be
logged. Locales with the same quality value are retained in the order
they appear in the header(s). A value of less than 0 means no limit. If
not specified, a default of 10 is used.</p>
</attribute>

<attribute name="maxParameterCount" required="false">
Expand Down