Merged branch 'jetty-9.4.x' into 'jetty-10.0.x'.

This commit is contained in:
Simone Bordet 2020-08-11 21:00:43 +02:00
commit 16cd552995
19 changed files with 330 additions and 85 deletions

View File

@ -27,6 +27,7 @@ import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.util.component.LifeCycle;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
@ -54,8 +55,10 @@ public class OneWebAppTest extends AbstractEmbeddedTest
}
@Test
@Tag("external")
public void testGetAsyncRest() throws Exception
{
// The async rest webapp forwards the call to ebay.com.
URI uri = server.getURI().resolve("/testAsync?items=mouse,beer,gnome");
ContentResponse response = client.newRequest(uri)
.method(HttpMethod.GET)

View File

@ -1111,10 +1111,14 @@ public class HttpClient extends ContainerLifeCycle
return encodingField;
}
/**
* @param host the host to normalize
* @return the host itself
* @deprecated no replacement, do not use it
*/
@Deprecated
protected String normalizeHost(String host)
{
if (host != null && host.startsWith("[") && host.endsWith("]"))
return host.substring(1, host.length() - 1);
return host;
}

View File

@ -99,7 +99,7 @@ public class HttpRequest implements Request
this.client = client;
this.conversation = conversation;
scheme = uri.getScheme();
host = client.normalizeHost(uri.getHost());
host = uri.getHost();
port = HttpClient.normalizePort(scheme, uri.getPort());
path = uri.getRawPath();
query = uri.getRawQuery();

View File

@ -25,6 +25,7 @@ import java.util.Objects;
import org.eclipse.jetty.client.dynamic.HttpClientTransportDynamic;
import org.eclipse.jetty.io.ClientConnectionFactory;
import org.eclipse.jetty.io.EndPoint;
import org.eclipse.jetty.util.HostPort;
import org.eclipse.jetty.util.URIUtil;
/**
@ -147,7 +148,7 @@ public class Origin
public Address(String host, int port)
{
this.host = Objects.requireNonNull(host);
this.host = HostPort.normalizeHost(Objects.requireNonNull(host));
this.port = port;
}

View File

@ -77,7 +77,6 @@ import org.eclipse.jetty.http.HttpHeaderValue;
import org.eclipse.jetty.http.HttpMethod;
import org.eclipse.jetty.http.HttpScheme;
import org.eclipse.jetty.http.HttpVersion;
import org.eclipse.jetty.io.AbstractConnection;
import org.eclipse.jetty.io.ClientConnector;
import org.eclipse.jetty.io.EndPoint;
import org.eclipse.jetty.logging.StacklessLogging;
@ -1603,29 +1602,32 @@ public class HttpClientTest extends AbstractHttpClientServerTest
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testIPv6Host(Scenario scenario) throws Exception
public void testIPv6HostWithHTTP10(Scenario scenario) throws Exception
{
Assumptions.assumeTrue(Net.isIpv6InterfaceAvailable());
start(scenario, new AbstractHandler()
start(scenario, new EmptyServerHandler()
{
@Override
public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException
protected void service(String target, org.eclipse.jetty.server.Request jettyRequest, HttpServletRequest request, HttpServletResponse response) throws IOException
{
baseRequest.setHandled(true);
response.setContentType("text/plain");
response.getOutputStream().print(request.getHeader("Host"));
response.getOutputStream().print(request.getServerName());
}
});
URI uri = URI.create(scenario.getScheme() + "://[::1]:" + connector.getLocalPort() + "/path");
ContentResponse response = client.newRequest(uri)
.method(HttpMethod.PUT)
.version(HttpVersion.HTTP_1_0)
.onRequestBegin(r -> r.headers(headers -> headers.remove(HttpHeader.HOST)))
.timeout(5, TimeUnit.SECONDS)
.send();
assertNotNull(response);
assertEquals(200, response.getStatus());
assertThat(new String(response.getContent(), StandardCharsets.ISO_8859_1), Matchers.startsWith("[::1]:"));
String content = response.getContentAsString();
assertThat(content, Matchers.startsWith("["));
assertThat(content, Matchers.endsWith(":1]"));
}
@ParameterizedTest

View File

@ -67,8 +67,10 @@ public class HttpClientURITest extends AbstractHttpClientServerTest
Assumptions.assumeTrue(Net.isIpv6InterfaceAvailable());
start(scenario, new EmptyServerHandler());
String host = "::1";
Request request = client.newRequest(host, connector.getLocalPort())
String hostAddress = "::1";
String host = "[" + hostAddress + "]";
// Explicitly use a non-bracketed IPv6 host.
Request request = client.newRequest(hostAddress, connector.getLocalPort())
.scheme(scenario.getScheme())
.timeout(5, TimeUnit.SECONDS);

View File

@ -0,0 +1,41 @@
//
// ========================================================================
// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others.
//
// This program and the accompanying materials are made available under
// the terms of the Eclipse Public License 2.0 which is available at
// https://www.eclipse.org/legal/epl-2.0
//
// This Source Code may also be made available under the following
// Secondary Licenses when the conditions for such availability set
// forth in the Eclipse Public License, v. 2.0 are satisfied:
// the Apache License v2.0 which is available at
// https://www.apache.org/licenses/LICENSE-2.0
//
// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
// ========================================================================
//
package org.eclipse.jetty.proxy;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;
public class EmptyServerHandler extends AbstractHandler
{
@Override
public final void handle(String target, Request jettyRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
jettyRequest.setHandled(true);
service(target, jettyRequest, request, response);
}
protected void service(String target, Request jettyRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
}
}

View File

@ -21,11 +21,15 @@ package org.eclipse.jetty.proxy;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.stream.Stream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.client.HttpProxy;
import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.client.api.Request;
import org.eclipse.jetty.client.http.HttpClientTransportOverHTTP;
import org.eclipse.jetty.http.HttpHeader;
import org.eclipse.jetty.http.HttpMethod;
import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.io.AbstractConnection;
@ -35,10 +39,16 @@ import org.eclipse.jetty.io.EndPoint;
import org.eclipse.jetty.server.AbstractConnectionFactory;
import org.eclipse.jetty.server.ConnectionFactory;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.ForwardedRequestCustomizer;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.HttpConfiguration;
import org.eclipse.jetty.server.HttpConnectionFactory;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.toolchain.test.MavenTestingUtils;
import org.eclipse.jetty.toolchain.test.Net;
import org.eclipse.jetty.util.BufferUtil;
import org.eclipse.jetty.util.Callback;
import org.eclipse.jetty.util.Utf8StringBuilder;
@ -46,10 +56,14 @@ import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.greaterThan;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
@ -75,7 +89,7 @@ public class ForwardProxyServerTest
private Server proxy;
private ServerConnector proxyConnector;
protected void startServer(SslContextFactory.Server serverTLS, ConnectionFactory connectionFactory) throws Exception
protected void startServer(SslContextFactory.Server serverTLS, ConnectionFactory connectionFactory, Handler handler) throws Exception
{
serverSslContextFactory = serverTLS;
QueuedThreadPool serverThreads = new QueuedThreadPool();
@ -83,10 +97,11 @@ public class ForwardProxyServerTest
server = new Server(serverThreads);
serverConnector = new ServerConnector(server, serverSslContextFactory, connectionFactory);
server.addConnector(serverConnector);
server.setHandler(handler);
server.start();
}
protected void startProxy() throws Exception
protected void startProxy(ProxyServlet proxyServlet) throws Exception
{
QueuedThreadPool proxyThreads = new QueuedThreadPool();
proxyThreads.setName("proxy");
@ -100,7 +115,7 @@ public class ForwardProxyServerTest
proxy.setHandler(connectHandler);
ServletContextHandler proxyHandler = new ServletContextHandler(connectHandler, "/");
proxyHandler.addServlet(ProxyServlet.class, "/*");
proxyHandler.addServlet(new ServletHolder(proxyServlet), "/*");
proxy.start();
}
@ -167,7 +182,7 @@ public class ForwardProxyServerTest
// the client, and convert it to a relative URI.
// The ConnectHandler won't modify what the client
// sent, which must be a relative URI.
assertThat(request.length(), Matchers.greaterThan(0));
assertThat(request.length(), greaterThan(0));
if (serverSslContextFactory == null)
assertFalse(request.contains("http://"));
else
@ -187,8 +202,8 @@ public class ForwardProxyServerTest
}
};
}
});
startProxy();
}, new EmptyServerHandler());
startProxy(new ProxyServlet());
SslContextFactory.Client clientTLS = new SslContextFactory.Client(true);
ClientConnector clientConnector = new ClientConnector();
@ -212,4 +227,83 @@ public class ForwardProxyServerTest
httpClient.stop();
}
}
@ParameterizedTest
@ValueSource(strings = {"::2", "[::3]"})
public void testIPv6WithXForwardedForHeader(String ipv6) throws Exception
{
Assumptions.assumeTrue(Net.isIpv6InterfaceAvailable());
HttpConfiguration httpConfig = new HttpConfiguration();
httpConfig.addCustomizer(new ForwardedRequestCustomizer());
ConnectionFactory http = new HttpConnectionFactory(httpConfig);
startServer(null, http, new EmptyServerHandler()
{
@Override
protected void service(String target, org.eclipse.jetty.server.Request jettyRequest, HttpServletRequest request, HttpServletResponse response)
{
String remoteHost = jettyRequest.getRemoteHost();
assertThat(remoteHost, Matchers.matchesPattern("\\[.+\\]"));
String remoteAddr = jettyRequest.getRemoteAddr();
assertThat(remoteAddr, Matchers.matchesPattern("\\[.+\\]"));
}
});
startProxy(new ProxyServlet()
{
@Override
protected void addProxyHeaders(HttpServletRequest clientRequest, Request proxyRequest)
{
proxyRequest.headers(headers -> headers.put(HttpHeader.X_FORWARDED_FOR, ipv6));
}
});
HttpClient httpClient = new HttpClient();
httpClient.getProxyConfiguration().getProxies().add(newHttpProxy());
httpClient.start();
ContentResponse response = httpClient.newRequest("[::1]", serverConnector.getLocalPort())
.scheme("http")
.send();
assertEquals(HttpStatus.OK_200, response.getStatus());
}
@Test
public void testIPv6WithForwardedHeader() throws Exception
{
Assumptions.assumeTrue(Net.isIpv6InterfaceAvailable());
HttpConfiguration httpConfig = new HttpConfiguration();
httpConfig.addCustomizer(new ForwardedRequestCustomizer());
ConnectionFactory http = new HttpConnectionFactory(httpConfig);
startServer(null, http, new EmptyServerHandler()
{
@Override
protected void service(String target, org.eclipse.jetty.server.Request jettyRequest, HttpServletRequest request, HttpServletResponse response)
{
String remoteHost = jettyRequest.getRemoteHost();
assertThat(remoteHost, Matchers.matchesPattern("\\[.+\\]"));
String remoteAddr = jettyRequest.getRemoteAddr();
assertThat(remoteAddr, Matchers.matchesPattern("\\[.+\\]"));
}
});
startProxy(new ProxyServlet()
{
@Override
protected void addProxyHeaders(HttpServletRequest clientRequest, Request proxyRequest)
{
proxyRequest.headers(headers -> headers.put(HttpHeader.FORWARDED, "for=\"[::2]\""));
}
});
HttpClient httpClient = new HttpClient();
httpClient.getProxyConfiguration().getProxies().add(newHttpProxy());
httpClient.start();
ContentResponse response = httpClient.newRequest("[::1]", serverConnector.getLocalPort())
.scheme("http")
.send();
assertEquals(HttpStatus.OK_200, response.getStatus());
}
}

View File

@ -62,11 +62,13 @@ import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.toolchain.test.MavenTestingUtils;
import org.eclipse.jetty.toolchain.test.Net;
import org.eclipse.jetty.util.Promise;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
@ -475,6 +477,36 @@ public class ForwardProxyTLSServerTest
httpClient.stop();
}
@ParameterizedTest
@MethodSource("proxyTLS")
public void testIPv6(SslContextFactory.Server proxyTLS) throws Exception
{
Assumptions.assumeTrue(Net.isIpv6InterfaceAvailable());
startTLSServer(new ServerHandler());
startProxy(proxyTLS);
HttpClient httpClient = newHttpClient();
HttpProxy httpProxy = new HttpProxy(new Origin.Address("[::1]", proxyConnector.getLocalPort()), proxyTLS != null);
httpClient.getProxyConfiguration().getProxies().add(httpProxy);
httpClient.start();
try
{
ContentResponse response = httpClient.newRequest("[::1]", serverConnector.getLocalPort())
.scheme(HttpScheme.HTTPS.asString())
.path("/echo?body=")
.timeout(5, TimeUnit.SECONDS)
.send();
assertEquals(HttpStatus.OK_200, response.getStatus());
}
finally
{
httpClient.stop();
}
}
@ParameterizedTest
@MethodSource("proxyTLS")
public void testProxyAuthentication(SslContextFactory.Server proxyTLS) throws Exception

View File

@ -27,6 +27,7 @@ import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.charset.UnsupportedCharsetException;
@ -89,6 +90,7 @@ import org.eclipse.jetty.server.session.Session;
import org.eclipse.jetty.server.session.SessionHandler;
import org.eclipse.jetty.util.Attributes;
import org.eclipse.jetty.util.AttributesMap;
import org.eclipse.jetty.util.HostPort;
import org.eclipse.jetty.util.IO;
import org.eclipse.jetty.util.MultiMap;
import org.eclipse.jetty.util.StringUtil;
@ -337,7 +339,7 @@ public class Request implements HttpServletRequest
Map<String,String> cookies = new HashMap<>();
Cookie[] existingCookies = getCookies();
if (existingCookies != null)
{
{
for (Cookie c: getCookies())
{
cookies.put(c.getName(), c.getValue());
@ -371,7 +373,7 @@ public class Request implements HttpServletRequest
}
fields.add(new HttpField(HttpHeader.COOKIE, buff.toString()));
}
PushBuilder builder = new PushBuilderImpl(this, fields, getMethod(), getQueryString(), id);
builder.addHeader("referer", getRequestURL().toString());
@ -972,11 +974,12 @@ public class Request implements HttpServletRequest
String name = InetAddress.getLocalHost().getHostAddress();
if (StringUtil.ALL_INTERFACES.equals(name))
return null;
return name;
return HostPort.normalizeHost(name);
}
catch (java.net.UnknownHostException e)
catch (UnknownHostException e)
{
LOG.trace("IGNORED", e);
return null;
}
}
@ -984,9 +987,10 @@ public class Request implements HttpServletRequest
if (local == null)
return "";
InetAddress address = local.getAddress();
if (address == null)
return local.getHostString();
return address.getHostAddress();
String result = address == null
? local.getHostString()
: address.getHostAddress();
return HostPort.normalizeHost(result);
}
@Override
@ -996,7 +1000,7 @@ public class Request implements HttpServletRequest
{
InetSocketAddress local = _channel.getLocalAddress();
if (local != null)
return local.getHostString();
return HostPort.normalizeHost(local.getHostString());
}
try
@ -1004,9 +1008,9 @@ public class Request implements HttpServletRequest
String name = InetAddress.getLocalHost().getHostName();
if (StringUtil.ALL_INTERFACES.equals(name))
return null;
return name;
return HostPort.normalizeHost(name);
}
catch (java.net.UnknownHostException e)
catch (UnknownHostException e)
{
LOG.trace("IGNORED", e);
}
@ -1191,15 +1195,17 @@ public class Request implements HttpServletRequest
InetSocketAddress remote = _remote;
if (remote == null)
remote = _channel.getRemoteAddress();
if (remote == null)
return "";
InetAddress address = remote.getAddress();
if (address == null)
return remote.getHostString();
return address.getHostAddress();
String result = address == null
? remote.getHostString()
: address.getHostAddress();
// Add IPv6 brackets if necessary, to be consistent
// with cases where _remote has been built from other
// sources such as forward headers or PROXY protocol.
return HostPort.normalizeHost(result);
}
@Override
@ -1208,7 +1214,10 @@ public class Request implements HttpServletRequest
InetSocketAddress remote = _remote;
if (remote == null)
remote = _channel.getRemoteAddress();
return remote == null ? "" : remote.getHostString();
if (remote == null)
return "";
// We want the URI host, so add IPv6 brackets if necessary.
return HostPort.normalizeHost(remote.getHostString());
}
@Override
@ -1314,14 +1323,14 @@ public class Request implements HttpServletRequest
// Return host from connection
String name = getLocalName();
if (name != null)
return name;
return HostPort.normalizeHost(name);
// Return the local host
try
{
return InetAddress.getLocalHost().getHostAddress();
return HostPort.normalizeHost(InetAddress.getLocalHost().getHostAddress());
}
catch (java.net.UnknownHostException e)
catch (UnknownHostException e)
{
LOG.trace("IGNORED", e);
}

View File

@ -785,19 +785,24 @@ public class ResourceService
int length = 0;
String[] header = new String[ranges.size()];
int i = 0;
final int CRLF = "\r\n".length();
final int DASHDASH = "--".length();
final int BOUNDARY = multi.getBoundary().length();
final int FIELD_SEP = ": ".length();
for (InclusiveByteRange ibr : ranges)
{
header[i] = ibr.toHeaderRangeString(content_length);
length +=
((i > 0) ? 2 : 0) +
2 + multi.getBoundary().length() + 2 +
(mimetype == null ? 0 : HttpHeader.CONTENT_TYPE.asString().length() + 2 + mimetype.length()) + 2 +
HttpHeader.CONTENT_RANGE.asString().length() + 2 + header[i].length() + 2 +
2 +
(ibr.getLast() - ibr.getFirst()) + 1;
if (i > 0) // in-part
length += CRLF;
length += DASHDASH + BOUNDARY + CRLF;
if (mimetype != null)
length += HttpHeader.CONTENT_TYPE.asString().length() + FIELD_SEP + mimetype.length() + CRLF;
length += HttpHeader.CONTENT_RANGE.asString().length() + FIELD_SEP + header[i].length() + CRLF;
length += CRLF;
length += ibr.getSize();
i++;
}
length += 2 + 2 + multi.getBoundary().length() + 2 + 2;
length += CRLF + DASHDASH + BOUNDARY + DASHDASH + CRLF;
response.setContentLength(length);
try (RangeWriter rangeWriter = HttpContentRangeWriter.newRangeWriter(content))

View File

@ -703,7 +703,7 @@ public class ForwardedRequestCustomizerTest
public void accept(Actual actual)
{
assertThat("scheme", actual.scheme.get(), is(expectedScheme));
if (actual.scheme.equals("https"))
if (actual.scheme.get().equals("https"))
{
assertTrue(actual.wasSecure.get(), "wasSecure");
}

View File

@ -109,8 +109,8 @@ public class ProxyConnectionTest
assertThat(response, Matchers.containsString("HTTP/1.1 200"));
assertThat(response, Matchers.containsString("pathInfo=/path"));
assertThat(response, Matchers.containsString("remote=eeee:eeee:eeee:eeee:eeee:eeee:eeee:eeee:65535"));
assertThat(response, Matchers.containsString("local=ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff:65535"));
assertThat(response, Matchers.containsString("remote=[eeee:eeee:eeee:eeee:eeee:eeee:eeee:eeee]:65535"));
assertThat(response, Matchers.containsString("local=[ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff]:65535"));
}
@ParameterizedTest
@ -147,8 +147,8 @@ public class ProxyConnectionTest
assertThat(response, Matchers.containsString("HTTP/1.1 200"));
assertThat(response, Matchers.containsString("pathInfo=/path"));
assertThat(response, Matchers.containsString("local=eeee:eeee:eeee:eeee:eeee:eeee:eeee:eeee:8080"));
assertThat(response, Matchers.containsString("remote=ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff:12345"));
assertThat(response, Matchers.containsString("local=[eeee:eeee:eeee:eeee:eeee:eeee:eeee:eeee]:8080"));
assertThat(response, Matchers.containsString("remote=[ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff]:12345"));
}
@ParameterizedTest

View File

@ -955,7 +955,7 @@ public class ResponseTest
ContextHandler context = new ContextHandler("/path");
int[] ports = new int[]{8080, 80};
String[] hosts = new String[]{null, "myhost", "192.168.0.1", "0::1"};
String[] hosts = new String[]{null, "myhost", "192.168.0.1", "[0::1]"};
for (int port : ports)
{
for (String host : hosts)
@ -994,7 +994,7 @@ public class ResponseTest
String location = response.getHeader("Location");
String expected = tests[i][1]
.replace("@HOST@", host == null ? request.getLocalAddr() : (host.contains(":") ? ("[" + host + "]") : host))
.replace("@HOST@", host == null ? request.getLocalAddr() : host)
.replace("@PORT@", host == null ? ":8888" : (port == 80 ? "" : (":" + port)));
assertEquals(expected, location, "test-" + i + " " + host + ":" + port);
request.setContext(null, "/info");
@ -1032,7 +1032,7 @@ public class ResponseTest
};
int[] ports = new int[]{8080, 80};
String[] hosts = new String[]{null, "myhost", "192.168.0.1", "0::1"};
String[] hosts = new String[]{null, "myhost", "192.168.0.1", "[0::1]"};
for (int port : ports)
{
for (String host : hosts)
@ -1072,7 +1072,7 @@ public class ResponseTest
String location = response.getHeader("Location");
String expected = tests[i][1]
.replace("@HOST@", host == null ? request.getLocalAddr() : (host.contains(":") ? ("[" + host + "]") : host))
.replace("@HOST@", host == null ? request.getLocalAddr() : host)
.replace("@PORT@", host == null ? ":8888" : (port == 80 ? "" : (":" + port)));
assertEquals(expected, location, "test-" + i + " " + host + ":" + port);
}

View File

@ -1340,12 +1340,10 @@ public class DoSFilter implements Filter
}
}
private String createRemotePortId(final ServletRequest request)
private String createRemotePortId(ServletRequest request)
{
final String addr = request.getRemoteAddr();
final int port = request.getRemotePort();
if (addr.contains(":"))
return "[" + addr + "]:" + port;
String addr = request.getRemoteAddr();
int port = request.getRemotePort();
return addr + ":" + port;
}
}

View File

@ -19,22 +19,18 @@
package org.eclipse.jetty.util;
/**
* Parse an authority string into Host and Port
* <p>Parse a string in the form "host:port", handling IPv4 an IPv6 hosts</p>
*
* <p>The System property "org.eclipse.jetty.util.HostPort.STRIP_IPV6" can be set to a boolean
* value to control of the square brackets are stripped off IPv6 addresses (default false).</p>
* <p>Parse an authority string (in the form {@code host:port}) into
* {@code host} and {@code port}, handling IPv4 and IPv6 host formats
* as defined in https://www.ietf.org/rfc/rfc2732.txt</p>
*/
public class HostPort
{
private static final boolean STRIP_IPV6 = Boolean.parseBoolean(System.getProperty("org.eclipse.jetty.util.HostPort.STRIP_IPV6", "false"));
private final String _host;
private final int _port;
public HostPort(String host, int port)
{
_host = host;
_host = normalizeHost(host);
_port = port;
}
@ -55,7 +51,7 @@ public class HostPort
int close = authority.lastIndexOf(']');
if (close < 0)
throw new IllegalArgumentException("Bad IPv6 host");
_host = STRIP_IPV6 ? authority.substring(1, close) : authority.substring(0, close + 1);
_host = authority.substring(0, close + 1);
if (authority.length() > close + 1)
{
@ -64,14 +60,17 @@ public class HostPort
_port = parsePort(authority.substring(close + 2));
}
else
{
_port = 0;
}
}
else
{
// ipv4address or hostname
// ipv6address or ipv4address or hostname
int c = authority.lastIndexOf(':');
if (c >= 0)
{
// ipv6address
if (c != authority.indexOf(':'))
{
_host = "[" + authority + "]";
@ -94,14 +93,9 @@ public class HostPort
{
throw iae;
}
catch (final Exception ex)
catch (Exception ex)
{
throw new IllegalArgumentException("Bad HostPort")
{
{
initCause(ex);
}
};
throw new IllegalArgumentException("Bad HostPort", ex);
}
}
@ -126,7 +120,7 @@ public class HostPort
}
/**
* Get the port.
* Get the port or the given default port.
*
* @param defaultPort, the default port to return if a port is not specified
* @return the port
@ -140,15 +134,17 @@ public class HostPort
public String toString()
{
if (_port > 0)
return normalizeHost(_host) + ":" + _port;
return _host + ":" + _port;
return _host;
}
/**
* Normalize IPv6 address as per https://www.ietf.org/rfc/rfc2732.txt
* Normalizes IPv6 address as per https://tools.ietf.org/html/rfc2732
* and https://tools.ietf.org/html/rfc6874,
* surrounding with square brackets if they are absent.
*
* @param host A host name
* @return Host name surrounded by '[' and ']' as needed.
* @param host a host name, IPv4 address, IPv6 address or IPv6 literal
* @return a host name or an IPv4 address or an IPv6 literal (not an IPv6 address)
*/
public static String normalizeHost(String host)
{
@ -165,6 +161,7 @@ public class HostPort
*
* @param rawPort the port string.
* @return the integer value for the port.
* @throws IllegalArgumentException if the port is invalid
*/
public static int parsePort(String rawPort) throws IllegalArgumentException
{

View File

@ -176,7 +176,7 @@ public class ResourceCollectionTest
}
@Test
public void testMutlipleSources1() throws Exception
public void testMultipleSources1() throws Exception
{
ResourceCollection rc1 = new ResourceCollection(new String[]{
"src/test/resources/org/eclipse/jetty/util/resource/one/",

View File

@ -52,10 +52,10 @@ public class WebInfConfiguration extends AbstractConfiguration
@Override
public void preConfigure(final WebAppContext context) throws Exception
{
//Make a temp directory for the webapp if one is not already set
// Make a temp directory for the webapp if one is not already set
resolveTempDirectory(context);
//Extract webapp if necessary
// Extract webapp if necessary
unpack(context);
}

View File

@ -21,6 +21,7 @@ package org.eclipse.jetty.http.client;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
@ -48,10 +49,12 @@ import org.eclipse.jetty.http2.FlowControlStrategy;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.toolchain.test.Net;
import org.eclipse.jetty.util.Callback;
import org.eclipse.jetty.util.IO;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ArgumentsSource;
@ -61,6 +64,7 @@ import static org.hamcrest.Matchers.containsString;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
@ -678,6 +682,59 @@ public class HttpClientTest extends AbstractTest<TransportScenario>
assertEquals(users, destinations.size());
}
@ParameterizedTest
@ArgumentsSource(TransportProvider.class)
public void testIPv6Host(Transport transport) throws Exception
{
Assumptions.assumeTrue(Net.isIpv6InterfaceAvailable());
init(transport);
scenario.start(new EmptyServerHandler()
{
@Override
protected void service(String target, Request jettyRequest, HttpServletRequest request, HttpServletResponse response) throws IOException
{
response.setContentType("text/plain");
response.getOutputStream().print(request.getHeader("Host"));
}
});
// Test with a full URI.
String hostAddress = "::1";
String host = "[" + hostAddress + "]";
int port = Integer.parseInt(scenario.getNetworkConnectorLocalPort().get());
String uri = scenario.getScheme() + "://" + host + ":" + port + "/path";
ContentResponse response = scenario.client.newRequest(uri)
.method(HttpMethod.PUT)
.timeout(5, TimeUnit.SECONDS)
.send();
assertNotNull(response);
assertEquals(200, response.getStatus());
assertThat(new String(response.getContent(), StandardCharsets.ISO_8859_1), Matchers.startsWith("[::1]:"));
// Test with host address.
response = scenario.client.newRequest(hostAddress, port)
.scheme(scenario.getScheme())
.method(HttpMethod.PUT)
.timeout(5, TimeUnit.SECONDS)
.send();
assertNotNull(response);
assertEquals(200, response.getStatus());
assertThat(new String(response.getContent(), StandardCharsets.ISO_8859_1), Matchers.startsWith("[::1]:"));
// Test with host.
response = scenario.client.newRequest(host, port)
.scheme(scenario.getScheme())
.method(HttpMethod.PUT)
.timeout(5, TimeUnit.SECONDS)
.send();
assertNotNull(response);
assertEquals(200, response.getStatus());
assertThat(new String(response.getContent(), StandardCharsets.ISO_8859_1), Matchers.startsWith("[::1]:"));
assertEquals(1, scenario.client.getDestinations().size());
}
private void sleep(long time) throws IOException
{
try