diff --git a/.github/ISSUE_TEMPLATE/issue-template.md b/.github/ISSUE_TEMPLATE/issue-template.md
new file mode 100644
index 00000000000..dd4f1455032
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/issue-template.md
@@ -0,0 +1,18 @@
+---
+name: Issue
+about: Reporting bugs and problems in Eclipse Jetty
+title: ''
+assignees: ''
+
+---
+
+**Jetty version**
+
+**Java version**
+
+**OS type/version**
+
+**Description**
+
+
+
diff --git a/.github/ISSUE_TEMPLATE/question-template.md b/.github/ISSUE_TEMPLATE/question-template.md
new file mode 100644
index 00000000000..d9cb028ca8b
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/question-template.md
@@ -0,0 +1,16 @@
+---
+name: Question
+about: Asking questions about Eclipse Jetty
+title: ''
+labels: Question
+assignees: ''
+
+---
+
+**Jetty version**
+
+**Java version**
+
+**Question**
+
+
diff --git a/.github/stale.yml b/.github/stale.yml
new file mode 100644
index 00000000000..8abd90936b2
--- /dev/null
+++ b/.github/stale.yml
@@ -0,0 +1,20 @@
+# Number of days of inactivity before an issue becomes stale
+daysUntilStale: 365
+# Number of days of inactivity before a stale issue is closed
+daysUntilClose: 30
+# Issues with these labels will never be considered stale
+exemptLabels:
+ - Pinned
+ - Security
+ - Specification
+ - TCK
+# Label to use when marking an issue as stale
+staleLabel: Stale
+# Comment to post when marking an issue as stale. Set to `false` to disable
+markComment: >
+ This issue has been automatically marked as stale because it has been a
+ full year without activity. It will be closed if no further activity occurs.
+ Thank you for your contributions.
+# Comment to post when closing a stale issue. Set to `false` to disable
+closeComment: >
+ This issue has been closed due to it having no activity.
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 9391cc18ab2..ef6433b76c8 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -53,10 +53,10 @@ Be sure to search for existing bugs before you create another one. Remember that
Reporting Security Issues
-----------------
-There are a number of avenues for reporting security issues to the Jetty project available.
-If the issue is directly related to Jetty itself then reporting to the Jetty developers is encouraged.
-The most direct method is to mail [security@webtide.com](mailto:security@webtide.com).
-Webtide is comprised of the active committers of the Jetty project is our preferred reporting method.
+There are a number of avenues for reporting security issues to the Jetty project available.
+If the issue is directly related to Jetty itself then reporting to the Jetty developers is encouraged.
+The most direct method is to mail [security@webtide.com](mailto:security@webtide.com).
+Webtide is comprised of the active committers of the Jetty project is our preferred reporting method.
We are flexible in how we work with reporters of security issues but we reserve the right to act in the interests of the Jetty project in all circumstances.
If the issue is related to Eclipse or its Jetty integration then we encourage you to reach out to [security@eclipse.org](mailto:security@eclipse.org).
diff --git a/Jenkinsfile b/Jenkinsfile
index 0d9b2c54a3d..4477293c51e 100644
--- a/Jenkinsfile
+++ b/Jenkinsfile
@@ -11,65 +11,53 @@ pipeline {
agent { node { label 'linux' } }
options { timeout(time: 120, unit: 'MINUTES') }
steps {
- mavenBuild("jdk11", "-Pmongodb install", "maven3", true) // -Pautobahn
+ mavenBuild("jdk11", "-T3 -Pmongodb clean install", "maven3", true) // -Pautobahn
// Collect up the jacoco execution results (only on main build)
jacoco inclusionPattern: '**/org/eclipse/jetty/**/*.class',
- exclusionPattern: '' +
- // build tools
- '**/org/eclipse/jetty/ant/**' +
- ',**/org/eclipse/jetty/maven/**' +
- ',**/org/eclipse/jetty/jspc/**' +
- // example code / documentation
- ',**/org/eclipse/jetty/embedded/**' +
- ',**/org/eclipse/jetty/asyncrest/**' +
- ',**/org/eclipse/jetty/demo/**' +
- // special environments / late integrations
- ',**/org/eclipse/jetty/gcloud/**' +
- ',**/org/eclipse/jetty/infinispan/**' +
- ',**/org/eclipse/jetty/osgi/**' +
- ',**/org/eclipse/jetty/spring/**' +
- ',**/org/eclipse/jetty/http/spi/**' +
- // test classes
- ',**/org/eclipse/jetty/tests/**' +
- ',**/org/eclipse/jetty/test/**',
- execPattern: '**/target/jacoco.exec',
- classPattern: '**/target/classes',
- sourcePattern: '**/src/main/java'
+ exclusionPattern: '' +
+ // build tools
+ '**/org/eclipse/jetty/ant/**' +
+ ',**/org/eclipse/jetty/maven/**' +
+ ',**/org/eclipse/jetty/jspc/**' +
+ // example code / documentation
+ ',**/org/eclipse/jetty/embedded/**' +
+ ',**/org/eclipse/jetty/asyncrest/**' +
+ ',**/org/eclipse/jetty/demo/**' +
+ // special environments / late integrations
+ ',**/org/eclipse/jetty/gcloud/**' +
+ ',**/org/eclipse/jetty/infinispan/**' +
+ ',**/org/eclipse/jetty/osgi/**' +
+ ',**/org/eclipse/jetty/spring/**' +
+ ',**/org/eclipse/jetty/http/spi/**' +
+ // test classes
+ ',**/org/eclipse/jetty/tests/**' +
+ ',**/org/eclipse/jetty/test/**',
+ execPattern: '**/target/jacoco.exec',
+ classPattern: '**/target/classes',
+ sourcePattern: '**/src/main/java'
warnings consoleParsers: [[parserName: 'Maven'], [parserName: 'Java']]
junit testResults: '**/target/surefire-reports/*.xml,**/target/invoker-reports/TEST*.xml,**/target/autobahntestsuite-reports/*.xml'
}
}
-
- stage("Build / Test - JDK12") {
+
+ stage("Build / Test - JDK13") {
agent { node { label 'linux' } }
- options { timeout(time: 120, unit: 'MINUTES') }
steps {
- mavenBuild("jdk12", "-Pmongodb install", "maven3", true)
- warnings consoleParsers: [[parserName: 'Maven'], [parserName: 'Java']]
- junit testResults: '**/target/surefire-reports/*.xml,**/target/invoker-reports/TEST*.xml'
+ timeout(time: 120, unit: 'MINUTES') {
+ mavenBuild("jdk13", "-T3 -Pmongodb clean install", "maven3", true)
+ warnings consoleParsers: [[parserName: 'Maven'], [parserName: 'Java']]
+ junit testResults: '**/target/surefire-reports/*.xml,**/target/invoker-reports/TEST*.xml'
+ }
}
}
stage("Build Javadoc") {
agent { node { label 'linux' } }
- options { timeout(time: 30, unit: 'MINUTES') }
steps {
- mavenBuild("jdk11", "install javadoc:javadoc -DskipTests", "maven3", true)
- warnings consoleParsers: [[parserName: 'Maven'], [parserName: 'JavaDoc'], [parserName: 'Java']]
- }
- }
-
- stage("Checkstyle ") {
- agent { node { label 'linux' } }
- options { timeout(time: 30, unit: 'MINUTES') }
- steps {
- mavenBuild("jdk11", "install -DskipTests", "maven3", true)
- mavenBuild("jdk11", "install -f build-resources", "maven3", true)
- mavenBuild("jdk11", "install checkstyle:check -DskipTests", "maven3", true)
- recordIssues(
- enabledForFailure: true, aggregatingResults: true,
- tools: [java(), checkStyle(pattern: '**/target/checkstyle-result.xml', reportEncoding: 'UTF-8')]
- )
+ timeout(time: 30, unit: 'MINUTES') {
+ mavenBuild("jdk11", "package source:jar javadoc:jar javadoc:aggregate-jar -Peclipse-release -DskipTests -Dpmd.skip=true -Dcheckstyle.skip=true", "maven3", true)
+ warnings consoleParsers: [[parserName: 'Maven'], [parserName: 'JavaDoc'], [parserName: 'Java']]
+ }
}
}
}
@@ -88,28 +76,24 @@ pipeline {
}
}
-
def slackNotif() {
- script {
- try
- {
- if ( env.BRANCH_NAME == 'jetty-10.0.x' || env.BRANCH_NAME == 'jetty-9.4.x' )
- {
- //BUILD_USER = currentBuild.rawBuild.getCause(Cause.UserIdCause).getUserId()
- // by ${BUILD_USER}
- COLOR_MAP = ['SUCCESS': 'good', 'FAILURE': 'danger', 'UNSTABLE': 'danger', 'ABORTED': 'danger']
- slackSend channel: '#jenkins',
- color: COLOR_MAP[currentBuild.currentResult],
- message: "*${currentBuild.currentResult}:* Job ${env.JOB_NAME} build ${env.BUILD_NUMBER} - ${env.BUILD_URL}"
- }
- } catch (Exception e) {
- e.printStackTrace()
- echo "skip failure slack notification: " + e.getMessage()
+ script {
+ try {
+ if (env.BRANCH_NAME == 'jetty-10.0.x' || env.BRANCH_NAME == 'jetty-9.4.x') {
+ //BUILD_USER = currentBuild.rawBuild.getCause(Cause.UserIdCause).getUserId()
+ // by ${BUILD_USER}
+ COLOR_MAP = ['SUCCESS': 'good', 'FAILURE': 'danger', 'UNSTABLE': 'danger', 'ABORTED': 'danger']
+ slackSend channel: '#jenkins',
+ color: COLOR_MAP[currentBuild.currentResult],
+ message: "*${currentBuild.currentResult}:* Job ${env.JOB_NAME} build ${env.BUILD_NUMBER} - ${env.BUILD_URL}"
}
+ } catch (Exception e) {
+ e.printStackTrace()
+ echo "skip failure slack notification: " + e.getMessage()
}
+ }
}
-
/**
* To other developers, if you are using this method above, please use the following syntax.
*
@@ -125,15 +109,16 @@ def mavenBuild(jdk, cmdline, mvnName, junitPublishDisabled) {
def mavenOpts = '-Xms1g -Xmx4g -Djava.awt.headless=true'
withMaven(
- maven: mvnName,
- jdk: "$jdk",
- publisherStrategy: 'EXPLICIT',
- options: [junitPublisher(disabled: junitPublishDisabled),mavenLinkerPublisher(disabled: false),pipelineGraphPublisher(disabled: false)],
- mavenOpts: mavenOpts,
- mavenLocalRepo: localRepo) {
+ maven: mvnName,
+ jdk: "$jdk",
+ publisherStrategy: 'EXPLICIT',
+ options: [junitPublisher(disabled: junitPublishDisabled), mavenLinkerPublisher(disabled: false), pipelineGraphPublisher(disabled: false)],
+ mavenOpts: mavenOpts,
+ mavenLocalRepo: localRepo) {
// Some common Maven command line + provided command line
- sh "mvn -Pci -V -B -T3 -e -fae -Dmaven.test.failure.ignore=true -Djetty.testtracker.log=true $cmdline -Dunix.socket.tmp=" + env.JENKINS_HOME
+ sh "mvn -Pci -V -B -e -fae -Dmaven.test.failure.ignore=true -Djetty.testtracker.log=true $cmdline -Dunix.socket.tmp=" + env.JENKINS_HOME
}
}
+
// vim: et:ts=2:sw=2:ft=groovy
diff --git a/KEYS.txt b/KEYS.txt
index acf04a8cc33..73b9fb49a4e 100644
--- a/KEYS.txt
+++ b/KEYS.txt
@@ -2,6 +2,6 @@
Jan Bartel
- * See exampleserver.xml
- *
- * See fileserver.xml - *
*/ public class FileServerXml { - public static void main(String[] args) throws Exception + public static Server createServer(int port, Path baseResource) throws Exception { + // Find Jetty XML (in classpath) that configures and starts Server. + // See src/main/resources/fileserver.xml Resource fileServerXml = Resource.newSystemResource("fileserver.xml"); XmlConfiguration configuration = new XmlConfiguration(fileServerXml); - Server server = (Server)configuration.configure(); + configuration.getProperties().put("http.port", Integer.toString(port)); + configuration.getProperties().put("fileserver.baseresource", baseResource.toAbsolutePath().toString()); + return (Server)configuration.configure(); + } + + public static void main(String[] args) throws Exception + { + int port = ExampleUtil.getPort(args, "jetty.http.port", 8080); + Path userDir = Paths.get(System.getProperty("user.dir")); + Server server = createServer(port, userDir); server.start(); server.join(); } diff --git a/examples/embedded/src/main/java/org/eclipse/jetty/embedded/HelloHandler.java b/examples/embedded/src/main/java/org/eclipse/jetty/embedded/HelloHandler.java index 4ddf274c547..f424b641125 100644 --- a/examples/embedded/src/main/java/org/eclipse/jetty/embedded/HelloHandler.java +++ b/examples/embedded/src/main/java/org/eclipse/jetty/embedded/HelloHandler.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.embedded; diff --git a/examples/embedded/src/main/java/org/eclipse/jetty/embedded/HelloServlet.java b/examples/embedded/src/main/java/org/eclipse/jetty/embedded/HelloServlet.java index a36957f7e73..79aadd8b67b 100644 --- a/examples/embedded/src/main/java/org/eclipse/jetty/embedded/HelloServlet.java +++ b/examples/embedded/src/main/java/org/eclipse/jetty/embedded/HelloServlet.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.embedded; diff --git a/examples/embedded/src/main/java/org/eclipse/jetty/embedded/HelloSessionServlet.java b/examples/embedded/src/main/java/org/eclipse/jetty/embedded/HelloSessionServlet.java index 4febfb8eb80..4daa4dc78aa 100644 --- a/examples/embedded/src/main/java/org/eclipse/jetty/embedded/HelloSessionServlet.java +++ b/examples/embedded/src/main/java/org/eclipse/jetty/embedded/HelloSessionServlet.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.embedded; diff --git a/examples/embedded/src/main/java/org/eclipse/jetty/embedded/HelloWorld.java b/examples/embedded/src/main/java/org/eclipse/jetty/embedded/HelloWorld.java index 151432fe6b9..2554591fc99 100644 --- a/examples/embedded/src/main/java/org/eclipse/jetty/embedded/HelloWorld.java +++ b/examples/embedded/src/main/java/org/eclipse/jetty/embedded/HelloWorld.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.embedded; @@ -51,7 +51,8 @@ public class HelloWorld extends AbstractHandler public static void main(String[] args) throws Exception { - Server server = new Server(8080); + int port = ExampleUtil.getPort(args, "jetty.http.port", 8080); + Server server = new Server(port); server.setHandler(new HelloWorld()); server.start(); diff --git a/examples/embedded/src/main/java/org/eclipse/jetty/embedded/Http2Server.java b/examples/embedded/src/main/java/org/eclipse/jetty/embedded/Http2Server.java index c07590e1d37..22dfd38702a 100644 --- a/examples/embedded/src/main/java/org/eclipse/jetty/embedded/Http2Server.java +++ b/examples/embedded/src/main/java/org/eclipse/jetty/embedded/Http2Server.java @@ -1,26 +1,29 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.embedded; -import java.io.File; +import java.io.FileNotFoundException; import java.io.IOException; import java.lang.management.ManagementFactory; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; import java.util.Arrays; import java.util.Date; import java.util.EnumSet; @@ -56,12 +59,15 @@ import org.eclipse.jetty.servlet.DefaultServlet; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; import org.eclipse.jetty.servlets.PushCacheFilter; +import org.eclipse.jetty.util.resource.PathResource; import org.eclipse.jetty.util.ssl.SslContextFactory; public class Http2Server { public static void main(String... args) throws Exception { + int port = ExampleUtil.getPort(args, "jetty.http.port", 8080); + int securePort = ExampleUtil.getPort(args, "jetty.https.port", 8443); Server server = new Server(); MBeanContainer mbContainer = new MBeanContainer( @@ -69,10 +75,11 @@ public class Http2Server server.addBean(mbContainer); ServletContextHandler context = new ServletContextHandler(server, "/", ServletContextHandler.SESSIONS); - String docroot = "src/main/resources/docroot"; - if (!new File(docroot).exists()) - docroot = "examples/embedded/src/main/resources/docroot"; - context.setResourceBase(docroot); + Path docroot = Paths.get("src/main/resources/docroot"); + if (!Files.exists(docroot)) + throw new FileNotFoundException(docroot.toString()); + + context.setBaseResource(new PathResource(docroot)); context.addFilter(PushCacheFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST)); // context.addFilter(PushSessionCacheFilter.class,"/*",EnumSet.of(DispatcherType.REQUEST)); context.addFilter(PushedTilesFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST)); @@ -83,23 +90,22 @@ public class Http2Server // HTTP Configuration HttpConfiguration httpConfig = new HttpConfiguration(); httpConfig.setSecureScheme("https"); - httpConfig.setSecurePort(8443); + httpConfig.setSecurePort(securePort); httpConfig.setSendXPoweredBy(true); httpConfig.setSendServerVersion(true); // HTTP Connector ServerConnector http = new ServerConnector(server, new HttpConnectionFactory(httpConfig), new HTTP2CServerConnectionFactory(httpConfig)); - http.setPort(8080); + http.setPort(port); server.addConnector(http); // SSL Context Factory for HTTPS and HTTP/2 - String jettyDistro = System.getProperty("jetty.distro", "../../jetty-distribution/target/distribution"); - if (!new File(jettyDistro).exists()) - jettyDistro = "jetty-distribution/target/distribution"; + Path keystorePath = Paths.get("src/main/resources/etc/keystore.p12").toAbsolutePath(); + if (!Files.exists(keystorePath)) + throw new FileNotFoundException(keystorePath.toString()); SslContextFactory.Server sslContextFactory = new SslContextFactory.Server(); - sslContextFactory.setKeyStorePath(jettyDistro + "/demo-base/etc/keystore"); - sslContextFactory.setKeyStorePassword("OBF:1vny1zlo1x8e1vnw1vn61x8g1zlu1vn4"); - sslContextFactory.setKeyManagerPassword("OBF:1u2u1wml1z7s1z7a1wnl1u2g"); + sslContextFactory.setKeyStorePath(keystorePath.toString()); + sslContextFactory.setKeyStorePassword("storepwd"); sslContextFactory.setCipherComparator(HTTP2Cipher.COMPARATOR); // sslContextFactory.setProvider("Conscrypt"); @@ -119,7 +125,7 @@ public class Http2Server // HTTP/2 Connector ServerConnector http2Connector = new ServerConnector(server, ssl, alpn, h2, new HttpConnectionFactory(httpsConfig)); - http2Connector.setPort(8443); + http2Connector.setPort(securePort); server.addConnector(http2Connector); server.start(); diff --git a/examples/embedded/src/main/java/org/eclipse/jetty/embedded/JarServer.java b/examples/embedded/src/main/java/org/eclipse/jetty/embedded/JarServer.java index c84ee9b3c33..ca285e010dd 100644 --- a/examples/embedded/src/main/java/org/eclipse/jetty/embedded/JarServer.java +++ b/examples/embedded/src/main/java/org/eclipse/jetty/embedded/JarServer.java @@ -1,24 +1,28 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.embedded; -import org.eclipse.jetty.server.Handler; +import java.io.FileNotFoundException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; + import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.handler.DefaultHandler; import org.eclipse.jetty.server.handler.HandlerList; @@ -28,24 +32,36 @@ import org.eclipse.jetty.servlet.ServletHolder; import org.eclipse.jetty.util.resource.Resource; /** - * + * Example of serving content from a JAR file. + * The JAR file in this example does not belong to any Classpath. */ public class JarServer { - public static void main(String[] args) throws Exception + public static Server createServer(int port) throws Exception { - final Server server = new Server(8080); + Server server = new Server(port); + + Path jarFile = Paths.get("src/main/other/content.jar"); + if (!Files.exists(jarFile)) + throw new FileNotFoundException(jarFile.toString()); ServletContextHandler context = new ServletContextHandler(); Resource.setDefaultUseCaches(true); - Resource base = Resource.newResource("jar:file:src/main/resources/content.jar!/"); + Resource base = Resource.newResource("jar:" + jarFile.toAbsolutePath().toUri().toASCIIString() + "!/"); context.setBaseResource(base); context.addServlet(new ServletHolder(new DefaultServlet()), "/"); HandlerList handlers = new HandlerList(); - handlers.setHandlers(new Handler[]{context, new DefaultHandler()}); + handlers.addHandler(context); + handlers.addHandler(new DefaultHandler()); server.setHandler(handlers); + return server; + } + public static void main(String[] args) throws Exception + { + int port = ExampleUtil.getPort(args, "jetty.http.port", 8080); + Server server = createServer(port); server.start(); server.join(); } diff --git a/examples/embedded/src/main/java/org/eclipse/jetty/embedded/JettyDistribution.java b/examples/embedded/src/main/java/org/eclipse/jetty/embedded/JettyDistribution.java index 5f707aca97f..a94825be6f0 100644 --- a/examples/embedded/src/main/java/org/eclipse/jetty/embedded/JettyDistribution.java +++ b/examples/embedded/src/main/java/org/eclipse/jetty/embedded/JettyDistribution.java @@ -1,29 +1,30 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.embedded; -import java.io.File; +import java.nio.file.Files; import java.nio.file.Path; +import java.nio.file.Paths; import org.eclipse.jetty.util.StringUtil; -import org.eclipse.jetty.util.log.Log; -import org.eclipse.jetty.util.log.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * A utility test class to locate a Jetty Distribution for testing purposes by searching: @@ -35,71 +36,104 @@ import org.eclipse.jetty.util.log.Logger; */ public class JettyDistribution { - private static final Logger LOG = Log.getLogger(JettyDistribution.class); + private static final Logger LOG = LoggerFactory.getLogger(JettyDistribution.class); public static final Path DISTRIBUTION; static { Path distro = asJettyDistribution(System.getProperty("jetty.home")); + LOG.debug("JettyDistribution(prop(jetty.home)) = " + distro); if (distro == null) + { distro = asJettyDistribution(System.getenv().get("JETTY_HOME")); + LOG.debug("JettyDistribution(env(JETTY_HOME)) = " + distro); + } if (distro == null) { try { - Path working = new File(".").getAbsoluteFile().getCanonicalFile().toPath(); + Path working = Paths.get(System.getProperty("user.dir")); + LOG.debug("JettyDistribution(prop(user.dir)) = " + working); while (distro == null && working != null) { distro = asJettyDistribution(working.resolve("jetty-distribution/target/distribution").toString()); working = working.getParent(); } + LOG.debug("JettyDistribution(working.resolve(...)) = " + distro); } catch (Throwable th) { - LOG.warn(th); + LOG.warn("Unable to resolve Jetty Distribution location", th); } } + + if (distro == null) + { + LOG.info("JettyDistribution() FAILURE: NOT FOUND"); + } + else + { + LOG.debug("JettyDistribution() FOUND = " + distro); + } DISTRIBUTION = distro; } - private static Path asJettyDistribution(String test) + private static Path asJettyDistribution(String jettyHome) { try { - if (StringUtil.isBlank(test)) + if (jettyHome == null) { - LOG.info("asJettyDistribution {} is blank", test); return null; } - File dir = new File(test); - if (!dir.exists() || !dir.isDirectory()) + if (StringUtil.isBlank(jettyHome)) { - LOG.info("asJettyDistribution {} is not a directory", test); + LOG.debug("asJettyDistribution {} is blank", jettyHome); return null; } - File demoBase = new File(dir, "demo-base"); - if (!demoBase.exists() || !demoBase.isDirectory()) + Path dir = Paths.get(jettyHome); + if (!Files.exists(dir)) { - LOG.info("asJettyDistribution {} has no demo-base", test); + LOG.debug("asJettyDistribution {} does not exist", jettyHome); return null; } - LOG.info("asJettyDistribution {}", dir); - return dir.getAbsoluteFile().getCanonicalFile().toPath(); + if (!Files.isDirectory(dir)) + { + LOG.debug("asJettyDistribution {} is not a directory", jettyHome); + return null; + } + + Path demoBase = dir.resolve("demo-base"); + if (!Files.exists(demoBase) || !Files.isDirectory(demoBase)) + { + LOG.debug("asJettyDistribution {} has no demo-base", jettyHome); + return null; + } + + LOG.debug("asJettyDistribution {}", dir); + return dir.toAbsolutePath(); } catch (Exception e) { - LOG.ignore(e); + LOG.trace("IGNORED", e); } return null; } + public static Path get() + { + if (DISTRIBUTION == null) + throw new RuntimeException("jetty-distribution not found"); + return DISTRIBUTION; + } + public static Path resolve(String path) { - return DISTRIBUTION.resolve(path); + return get().resolve(path); } public static void main(String... arg) diff --git a/examples/embedded/src/main/java/org/eclipse/jetty/embedded/LikeJettyXml.java b/examples/embedded/src/main/java/org/eclipse/jetty/embedded/LikeJettyXml.java index 752d071f682..ea16f69c68b 100644 --- a/examples/embedded/src/main/java/org/eclipse/jetty/embedded/LikeJettyXml.java +++ b/examples/embedded/src/main/java/org/eclipse/jetty/embedded/LikeJettyXml.java @@ -1,29 +1,33 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.embedded; -import java.io.File; +import java.io.FileNotFoundException; import java.lang.management.ManagementFactory; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; import org.eclipse.jetty.annotations.AnnotationConfiguration; import org.eclipse.jetty.deploy.DeploymentManager; import org.eclipse.jetty.deploy.PropertiesConfigurationManager; +import org.eclipse.jetty.deploy.bindings.DebugListenerBinding; import org.eclipse.jetty.deploy.providers.WebAppProvider; import org.eclipse.jetty.http.HttpVersion; import org.eclipse.jetty.jmx.MBeanContainer; @@ -35,6 +39,7 @@ import org.eclipse.jetty.rewrite.handler.ValidUrlRule; import org.eclipse.jetty.security.HashLoginService; import org.eclipse.jetty.server.AsyncRequestLogWriter; import org.eclipse.jetty.server.CustomRequestLog; +import org.eclipse.jetty.server.DebugListener; import org.eclipse.jetty.server.Handler; import org.eclipse.jetty.server.HttpConfiguration; import org.eclipse.jetty.server.HttpConnectionFactory; @@ -59,21 +64,21 @@ import org.eclipse.jetty.webapp.Configurations; */ public class LikeJettyXml { - public static void main(String[] args) throws Exception + public static Server createServer(int port, int securePort, boolean addDebugListener) throws Exception { // Path to as-built jetty-distribution directory - String jettyHomeBuild = JettyDistribution.DISTRIBUTION.toString(); + Path jettyHomeBuild = JettyDistribution.get(); // Find jetty home and base directories - String homePath = System.getProperty("jetty.home", jettyHomeBuild); - File homeDir = new File(homePath); + String homePath = System.getProperty("jetty.home", jettyHomeBuild.toString()); + Path homeDir = Paths.get(homePath); - String basePath = System.getProperty("jetty.base", homeDir + "/demo-base"); - File baseDir = new File(basePath); + String basePath = System.getProperty("jetty.base", homeDir.resolve("demo-base").toString()); + Path baseDir = Paths.get(basePath); // Configure jetty.home and jetty.base system properties - String jettyHome = homeDir.getAbsolutePath(); - String jettyBase = baseDir.getAbsolutePath(); + String jettyHome = homeDir.toAbsolutePath().toString(); + String jettyBase = baseDir.toAbsolutePath().toString(); System.setProperty("jetty.home", jettyHome); System.setProperty("jetty.base", jettyBase); @@ -91,7 +96,7 @@ public class LikeJettyXml // HTTP Configuration HttpConfiguration httpConfig = new HttpConfiguration(); httpConfig.setSecureScheme("https"); - httpConfig.setSecurePort(8443); + httpConfig.setSecurePort(securePort); httpConfig.setOutputBufferSize(32768); httpConfig.setRequestHeaderSize(8192); httpConfig.setResponseHeaderSize(8192); @@ -105,11 +110,6 @@ public class LikeJettyXml handlers.setHandlers(new Handler[]{contexts, new DefaultHandler()}); server.setHandler(handlers); - // Extra options - server.setDumpAfterStart(true); - server.setDumpBeforeStop(false); - server.setStopAtShutdown(true); - // === jetty-jmx.xml === MBeanContainer mbContainer = new MBeanContainer( ManagementFactory.getPlatformMBeanServer()); @@ -118,24 +118,20 @@ public class LikeJettyXml // === jetty-http.xml === ServerConnector http = new ServerConnector(server, new HttpConnectionFactory(httpConfig)); - http.setPort(8080); + http.setPort(port); http.setIdleTimeout(30000); server.addConnector(http); // === jetty-https.xml === // SSL Context Factory + Path keystorePath = Paths.get("src/main/resources/etc/keystore.p12").toAbsolutePath(); + if (!Files.exists(keystorePath)) + throw new FileNotFoundException(keystorePath.toString()); SslContextFactory.Server sslContextFactory = new SslContextFactory.Server(); - sslContextFactory.setKeyStorePath(jettyHome + "/../../../jetty-server/src/test/config/etc/keystore"); - sslContextFactory.setKeyStorePassword("OBF:1vny1zlo1x8e1vnw1vn61x8g1zlu1vn4"); - sslContextFactory.setKeyManagerPassword("OBF:1u2u1wml1z7s1z7a1wnl1u2g"); - sslContextFactory.setTrustStorePath(jettyHome + "/../../../jetty-server/src/test/config/etc/keystore"); - sslContextFactory.setTrustStorePassword("OBF:1vny1zlo1x8e1vnw1vn61x8g1zlu1vn4"); - sslContextFactory.setExcludeCipherSuites("SSL_RSA_WITH_DES_CBC_SHA", - "SSL_DHE_RSA_WITH_DES_CBC_SHA", "SSL_DHE_DSS_WITH_DES_CBC_SHA", - "SSL_RSA_EXPORT_WITH_RC4_40_MD5", - "SSL_RSA_EXPORT_WITH_DES40_CBC_SHA", - "SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA", - "SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA"); + sslContextFactory.setKeyStorePath(keystorePath.toString()); + sslContextFactory.setKeyStorePassword("storepwd"); + sslContextFactory.setTrustStorePath(keystorePath.toString()); + sslContextFactory.setTrustStorePassword("storepwd"); // SSL HTTP Configuration HttpConfiguration httpsConfig = new HttpConfiguration(httpConfig); @@ -145,14 +141,17 @@ public class LikeJettyXml ServerConnector sslConnector = new ServerConnector(server, new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()), new HttpConnectionFactory(httpsConfig)); - sslConnector.setPort(8443); + sslConnector.setPort(securePort); server.addConnector(sslConnector); // === jetty-deploy.xml === DeploymentManager deployer = new DeploymentManager(); - //DebugListener debug = new DebugListener(System.out,true,true,true); - // server.addBean(debug); - // deployer.addLifeCycleBinding(new DebugListenerBinding(debug)); + if (addDebugListener) + { + DebugListener debug = new DebugListener(System.err, true, true, true); + server.addBean(debug); + deployer.addLifeCycleBinding(new DebugListenerBinding(debug)); + } deployer.setContexts(contexts); deployer.setContextAttribute( "org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern", @@ -208,6 +207,20 @@ public class LikeJettyXml login.setHotReload(false); server.addBean(login); + return server; + } + + public static void main(String[] args) throws Exception + { + int port = ExampleUtil.getPort(args, "jetty.http.port", 8080); + int securePort = ExampleUtil.getPort(args, "jetty.https.port", 8443); + Server server = createServer(port, securePort, true); + + // Extra options + server.setDumpAfterStart(true); + server.setDumpBeforeStop(false); + server.setStopAtShutdown(true); + // Start the server server.start(); server.join(); diff --git a/examples/embedded/src/main/java/org/eclipse/jetty/embedded/ManyConnectors.java b/examples/embedded/src/main/java/org/eclipse/jetty/embedded/ManyConnectors.java index fa8f86f1c97..40d4f1c2e34 100644 --- a/examples/embedded/src/main/java/org/eclipse/jetty/embedded/ManyConnectors.java +++ b/examples/embedded/src/main/java/org/eclipse/jetty/embedded/ManyConnectors.java @@ -1,25 +1,27 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.embedded; -import java.io.File; import java.io.FileNotFoundException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; import org.eclipse.jetty.http.HttpVersion; import org.eclipse.jetty.server.Connector; @@ -36,23 +38,13 @@ import org.eclipse.jetty.util.ssl.SslContextFactory; */ public class ManyConnectors { - public static void main(String[] args) throws Exception + public static Server createServer(int plainPort, int securePort) throws Exception { // Since this example shows off SSL configuration, we need a keystore - // with the appropriate key. These lookup of jetty.home is purely a hack - // to get access to a keystore that we use in many unit tests and should - // probably be a direct path to your own keystore. - - String jettyDistKeystore = "../../jetty-distribution/target/distribution/demo-base/etc/test-keystore"; - String keystorePath = System.getProperty("example.keystore", jettyDistKeystore); - File keystoreFile = new File(keystorePath); - if (!keystoreFile.exists()) - { - keystorePath = "jetty-distribution/target/distribution/demo-base/etc/keystore"; - keystoreFile = new File(keystorePath); - if (!keystoreFile.exists()) - throw new FileNotFoundException(keystoreFile.getAbsolutePath()); - } + // with the appropriate key. + Path keystorePath = Paths.get("src/main/resources/etc/keystore.p12").toAbsolutePath(); + if (!Files.exists(keystorePath)) + throw new FileNotFoundException(keystorePath.toString()); // Create a basic jetty server object without declaring the port. Since // we are configuring connectors directly we'll be setting ports on @@ -67,7 +59,7 @@ public class ManyConnectors // done. The port for secured communication is also set here. HttpConfiguration httpConfig = new HttpConfiguration(); httpConfig.setSecureScheme("https"); - httpConfig.setSecurePort(8443); + httpConfig.setSecurePort(securePort); httpConfig.setOutputBufferSize(32768); // HTTP connector @@ -77,7 +69,7 @@ public class ManyConnectors // configure an idle timeout. ServerConnector http = new ServerConnector(server, new HttpConnectionFactory(httpConfig)); - http.setPort(8080); + http.setPort(plainPort); http.setIdleTimeout(30000); // SSL Context Factory for HTTPS @@ -88,9 +80,8 @@ public class ManyConnectors // keystore to be used. SslContextFactory.Server sslContextFactory = new SslContextFactory.Server(); - sslContextFactory.setKeyStorePath(keystoreFile.getAbsolutePath()); - sslContextFactory.setKeyStorePassword("OBF:1vny1zlo1x8e1vnw1vn61x8g1zlu1vn4"); - sslContextFactory.setKeyManagerPassword("OBF:1u2u1wml1z7s1z7a1wnl1u2g"); + sslContextFactory.setKeyStorePath(keystorePath.toString()); + sslContextFactory.setKeyStorePassword("storepwd"); // OPTIONAL: Un-comment the following to use Conscrypt for SSL instead of // the native JSSE implementation. @@ -118,7 +109,7 @@ public class ManyConnectors ServerConnector https = new ServerConnector(server, new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()), new HttpConnectionFactory(httpsConfig)); - https.setPort(8443); + https.setPort(securePort); https.setIdleTimeout(500000); // Here you see the server having multiple connectors registered with @@ -132,7 +123,14 @@ public class ManyConnectors // Set a handler server.setHandler(new HelloHandler()); + return server; + } + public static void main(String[] args) throws Exception + { + int port = ExampleUtil.getPort(args, "jetty.http.port", 8080); + int securePort = ExampleUtil.getPort(args, "jetty.https.port", 8443); + Server server = createServer(port, securePort); // Start the server server.start(); server.dumpStdErr(); diff --git a/examples/embedded/src/main/java/org/eclipse/jetty/embedded/ManyContexts.java b/examples/embedded/src/main/java/org/eclipse/jetty/embedded/ManyContexts.java index 944cce31853..d68a7d3d00e 100644 --- a/examples/embedded/src/main/java/org/eclipse/jetty/embedded/ManyContexts.java +++ b/examples/embedded/src/main/java/org/eclipse/jetty/embedded/ManyContexts.java @@ -1,56 +1,59 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.embedded; -import org.eclipse.jetty.server.Handler; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.handler.ContextHandler; import org.eclipse.jetty.server.handler.ContextHandlerCollection; public class ManyContexts { - public static void main(String[] args) throws Exception + public static Server createServer(int port) { - final Server server = new Server(8080); + Server server = new Server(port); ContextHandler context = new ContextHandler("/"); context.setContextPath("/"); context.setHandler(new HelloHandler("Root Hello")); ContextHandler contextFR = new ContextHandler("/fr"); - contextFR.setHandler(new HelloHandler("Bonjoir")); + contextFR.setHandler(new HelloHandler("Bonjour")); ContextHandler contextIT = new ContextHandler("/it"); - contextIT.setHandler(new HelloHandler("Bongiorno")); + contextIT.setHandler(new HelloHandler("Buongiorno")); ContextHandler contextV = new ContextHandler("/"); contextV.setVirtualHosts(new String[]{"127.0.0.2"}); contextV.setHandler(new HelloHandler("Virtual Hello")); - ContextHandlerCollection contexts = new ContextHandlerCollection(); - contexts.setHandlers(new Handler[]{ - context, contextFR, contextIT, - contextV - }); + ContextHandlerCollection contexts = new ContextHandlerCollection( + context, contextFR, contextIT, contextV + ); server.setHandler(contexts); + return server; + } + public static void main(String[] args) throws Exception + { + int port = ExampleUtil.getPort(args, "jetty.http.port", 8080); + Server server = createServer(port); server.start(); server.dumpStdErr(); server.join(); diff --git a/examples/embedded/src/main/java/org/eclipse/jetty/embedded/ManyHandlers.java b/examples/embedded/src/main/java/org/eclipse/jetty/embedded/ManyHandlers.java index 1cbc13d0d4f..77dd973eafe 100644 --- a/examples/embedded/src/main/java/org/eclipse/jetty/embedded/ManyHandlers.java +++ b/examples/embedded/src/main/java/org/eclipse/jetty/embedded/ManyHandlers.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.embedded; @@ -30,6 +30,8 @@ import org.eclipse.jetty.server.Handler; import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.handler.AbstractHandler; +import org.eclipse.jetty.server.handler.ContextHandler; +import org.eclipse.jetty.server.handler.ContextHandlerCollection; import org.eclipse.jetty.server.handler.DefaultHandler; import org.eclipse.jetty.server.handler.HandlerCollection; import org.eclipse.jetty.server.handler.HandlerList; @@ -81,7 +83,7 @@ public class ManyHandlers if (!params.isEmpty()) { response.setContentType("text/plain"); - response.getWriter().println(JSON.toString(params)); + response.getWriter().println(new JSON().toJSON(params)); baseRequest.setHandled(true); } } @@ -99,20 +101,23 @@ public class ManyHandlers HttpServletResponse response) throws IOException, ServletException { - request.setAttribute("welcome", "Hello"); + response.setHeader("X-Welcome", "Greetings from WelcomeWrapHandler"); super.handle(target, baseRequest, request, response); } } - public static void main(String[] args) throws Exception + public static Server createServer(int port) throws IOException { - final Server server = new Server(8080); + Server server = new Server(port); // create the handlers - final Handler param = new ParamHandler(); - final HandlerWrapper wrapper = new WelcomeWrapHandler(); - final Handler hello = new HelloHandler(); - final Handler dft = new DefaultHandler(); + Handler param = new ParamHandler(); + HandlerWrapper wrapper = new WelcomeWrapHandler(); + Handler hello = new HelloHandler(); + GzipHandler gzipHandler = new GzipHandler(); + gzipHandler.setMinGzipSize(10); + gzipHandler.addIncludedMimeTypes("text/plain"); + gzipHandler.addIncludedMimeTypes("text/html"); // configure request logging File requestLogFile = File.createTempFile("demo", "log"); @@ -120,16 +125,47 @@ public class ManyHandlers server.setRequestLog(ncsaLog); // create the handler collections - HandlerCollection handlers = new HandlerCollection(); - HandlerList list = new HandlerList(); + HandlerList handlers = new HandlerList(); - // link them all together + // wrap contexts around specific handlers wrapper.setHandler(hello); - list.setHandlers(new Handler[]{param, new GzipHandler()}); - handlers.setHandlers(new Handler[]{list, dft}); + ContextHandler helloContext = new ContextHandler("/hello"); + helloContext.setHandler(wrapper); + ContextHandler paramContext = new ContextHandler("/params"); + paramContext.setHandler(param); + + ContextHandlerCollection contexts = new ContextHandlerCollection(helloContext, paramContext); + + // Wrap Contexts with GZIP + gzipHandler.setHandler(contexts); + + // Set the top level Handler List + handlers.addHandler(gzipHandler); + handlers.addHandler(new DefaultHandler()); server.setHandler(handlers); + /* At this point you have the following handler hierarchy. + * + * Server.handler: + * HandlerList + * \- GzipHandler + * | \- ContextHandlerCollection + * | \- ContextHandler ("/hello") + * | | \- WelcomeWrapHandler + * | | \- HelloHandler + * | \- ContextHandler ("/params") + * | \- ParamHandler + * \- DefaultHandler + */ + + return server; + } + + public static void main(String[] args) throws Exception + { + int port = ExampleUtil.getPort(args, "jetty.http.port", 8080); + Server server = createServer(port); server.start(); server.join(); } diff --git a/examples/embedded/src/main/java/org/eclipse/jetty/embedded/ManyServletContexts.java b/examples/embedded/src/main/java/org/eclipse/jetty/embedded/ManyServletContexts.java index 53fa7317c04..c68ea874575 100644 --- a/examples/embedded/src/main/java/org/eclipse/jetty/embedded/ManyServletContexts.java +++ b/examples/embedded/src/main/java/org/eclipse/jetty/embedded/ManyServletContexts.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.embedded; @@ -29,9 +29,9 @@ import org.eclipse.jetty.servlet.ServletHolder; public class ManyServletContexts { - public static void main(String[] args) throws Exception + public static Server createServer(int port) { - Server server = new Server(8080); + Server server = new Server(port); // Setup JMX MBeanContainer mbContainer = new MBeanContainer( @@ -48,7 +48,7 @@ public class ManyServletContexts // Add servlets to root context root.addServlet(new ServletHolder(new HelloServlet("Hello")), "/"); root.addServlet(new ServletHolder(new HelloServlet("Ciao")), "/it/*"); - root.addServlet(new ServletHolder(new HelloServlet("Bonjoir")), "/fr/*"); + root.addServlet(new ServletHolder(new HelloServlet("Bonjour")), "/fr/*"); // Configure context "/other" for servlets ServletContextHandler other = new ServletContextHandler(contexts, @@ -57,6 +57,13 @@ public class ManyServletContexts other.addServlet(DefaultServlet.class.getCanonicalName(), "/"); other.addServlet(new ServletHolder(new HelloServlet("YO!")), "*.yo"); + return server; + } + + public static void main(String[] args) throws Exception + { + int port = ExampleUtil.getPort(args, "jetty.http.port", 8080); + Server server = createServer(port); server.start(); server.dumpStdErr(); server.join(); diff --git a/examples/embedded/src/main/java/org/eclipse/jetty/embedded/MinimalServlets.java b/examples/embedded/src/main/java/org/eclipse/jetty/embedded/MinimalServlets.java index 5ce9a24016c..3dcf2d53729 100644 --- a/examples/embedded/src/main/java/org/eclipse/jetty/embedded/MinimalServlets.java +++ b/examples/embedded/src/main/java/org/eclipse/jetty/embedded/MinimalServlets.java @@ -1,25 +1,24 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.embedded; import java.io.IOException; -import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -29,13 +28,13 @@ import org.eclipse.jetty.servlet.ServletHandler; public class MinimalServlets { - public static void main(String[] args) throws Exception + + public static Server createServer(int port) { - // Create a basic jetty server object that will listen on port 8080. // Note that if you set this to port 0 then a randomly available port // will be assigned that you can either look in the logs for the port, // or programmatically obtain it for use in test cases. - Server server = new Server(8080); + Server server = new Server(port); // The ServletHandler is a dead simple way to create a context handler // that is backed by an instance of a Servlet. @@ -51,13 +50,20 @@ public class MinimalServlets // through a web.xml @WebServlet annotation, or anything similar. handler.addServletWithMapping(HelloServlet.class, "/*"); + return server; + } + + public static void main(String[] args) throws Exception + { + // Create a basic jetty server object that will listen on port 8080. + int port = ExampleUtil.getPort(args, "jetty.http.port", 8080); + Server server = createServer(port); + // Start things up! server.start(); // The use of server.join() the will make the current thread join and - // wait until the server is done executing. - // See - // http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#join() + // wait until the server thread is done executing. server.join(); } @@ -66,11 +72,11 @@ public class MinimalServlets { @Override protected void doGet(HttpServletRequest request, - HttpServletResponse response) throws ServletException, - IOException + HttpServletResponse response) throws IOException { - response.setContentType("text/html"); response.setStatus(HttpServletResponse.SC_OK); + response.setContentType("text/html"); + response.setCharacterEncoding("utf-8"); response.getWriter().println("Applies an ordering to the {@link ServletContainerInitializer}s for the context, using + * the value of the "org.eclipse.jetty.containerInitializerOrder" context attribute. + * The attribute value is a list of classnames of ServletContainerInitializers in the order in which + * they are to be called. One name only in the list can be "*", which is a * wildcard which matches any other ServletContainerInitializer name not already - * matched. + * matched.
*/ public class ServletContainerInitializerOrdering { @@ -331,17 +332,16 @@ public class AnnotationConfiguration extends AbstractConfiguration _discoverableAnnotationHandlers.add(handler); } - /** - * @see org.eclipse.jetty.webapp.AbstractConfiguration#configure(org.eclipse.jetty.webapp.WebAppContext) - */ @Override public void configure(WebAppContext context) throws Exception { + //handle introspectable annotations (postconstruct,predestroy, multipart etc etc) context.getObjectFactory().addDecorator(new AnnotationDecorator(context)); if (!context.getMetaData().isMetaDataComplete()) { - //If metadata isn't complete, if this is a servlet 3 webapp or isConfigDiscovered is true, we need to search for annotations + //If web.xml not metadata-complete, if this is a servlet 3 webapp or above + //or configDiscovered is true, we need to search for annotations if (context.getServletContext().getEffectiveMajorVersion() >= 3 || context.isConfigurationDiscovered()) { _discoverableAnnotationHandlers.add(new WebServletAnnotationHandler(context)); @@ -370,9 +370,6 @@ public class AnnotationConfiguration extends AbstractConfiguration } } - /** - * @see org.eclipse.jetty.webapp.AbstractConfiguration#postConfigure(org.eclipse.jetty.webapp.WebAppContext) - */ @Override public void postConfigure(WebAppContext context) throws Exception { @@ -413,7 +410,8 @@ public class AnnotationConfiguration extends AbstractConfiguration } /** - * Perform scanning of classes for annotations + * Perform scanning of classes for discoverable + * annotations such as WebServlet/WebFilter/WebListener * * @param context the context for the scan * @throws Exception if unable to scan @@ -436,6 +434,7 @@ public class AnnotationConfiguration extends AbstractConfiguration isUseMultiThreading(context), getMaxScanWait(context)); + //scan selected jars on the container classpath first parseContainerPath(context, parser); //email from Rajiv Mordani jsrs 315 7 April 2010 // If there is aA {@link ServletContainerInitializer} that introspects for a CDI API + * implementation within a web application and applies an integration + * mode if CDI is found. CDI integration modes can be selected per webapp with + * the "org.eclipse.jetty.cdi" init parameter or default to the mode set by the + * "org.eclipse.jetty.cdi" server attribute. Supported modes are:
+ *+ * public <T> T decorate(T o) + * { + * BeanManager manager = CDI.current().getBeanManager(); + * manager.createInjectionTarget(manager.createAnnotatedType((Class<T>)o.getClass())) + * .inject(o,manager.createCreationalContext(null)); + * return o; + * } + *+ */ +public class CdiSpiDecorator implements Decorator +{ + private static final Logger LOG = LoggerFactory.getLogger(CdiServletContainerInitializer.class); + public static final String MODE = "CdiSpiDecorator"; + + private final ServletContextHandler _context; + private final Map
Accepts the given connection to be managed by this ConnectionPool.
+ * + * @param connection the connection to accept + * @return whether the connection has been accepted + */ + boolean accept(Connection connection); + /** *Returns the given connection, previously obtained via {@link #acquire()}, * back to this ConnectionPool.
@@ -70,11 +78,6 @@ public interface ConnectionPool extends Closeable */ boolean remove(Connection connection); - /** - * Closes this ConnectionPool. - * - * @see #isClosed() - */ @Override void close(); diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/ContentDecoder.java b/jetty-client/src/main/java/org/eclipse/jetty/client/ContentDecoder.java index eb69c1d5734..43f26f2b080 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/ContentDecoder.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/ContentDecoder.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.client; diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/ContinueProtocolHandler.java b/jetty-client/src/main/java/org/eclipse/jetty/client/ContinueProtocolHandler.java index fde872d55ce..1ca229175b8 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/ContinueProtocolHandler.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/ContinueProtocolHandler.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.client; diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/DuplexConnectionPool.java b/jetty-client/src/main/java/org/eclipse/jetty/client/DuplexConnectionPool.java index bfccf42c6b3..73f4b1b734d 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/DuplexConnectionPool.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/DuplexConnectionPool.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.client; @@ -37,14 +37,14 @@ import org.eclipse.jetty.util.annotation.ManagedAttribute; import org.eclipse.jetty.util.annotation.ManagedObject; import org.eclipse.jetty.util.component.Dumpable; import org.eclipse.jetty.util.component.DumpableCollection; -import org.eclipse.jetty.util.log.Log; -import org.eclipse.jetty.util.log.Logger; import org.eclipse.jetty.util.thread.Sweeper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; @ManagedObject public class DuplexConnectionPool extends AbstractConnectionPool implements Sweeper.Sweepable { - private static final Logger LOG = Log.getLogger(DuplexConnectionPool.class); + private static final Logger LOG = LoggerFactory.getLogger(DuplexConnectionPool.class); private final ReentrantLock lock = new ReentrantLock(); private final DequeHttpClient provides an efficient, asynchronous, non-blocking implementation
@@ -122,9 +122,9 @@ import org.eclipse.jetty.util.thread.ThreadPool;
public class HttpClient extends ContainerLifeCycle
{
public static final String USER_AGENT = "Jetty/" + Jetty.VERSION;
- private static final Logger LOG = Log.getLogger(HttpClient.class);
+ private static final Logger LOG = LoggerFactory.getLogger(HttpClient.class);
- private final ConcurrentMap
* While the {@link HttpClient} APIs define the HTTP semantic (request, response, headers, etc.)
- * how a HTTP exchange is carried over the network depends on implementations of this class.
+ * how an HTTP exchange is carried over the network depends on implementations of this class.
*
* The default implementation uses the HTTP protocol to carry over the network the HTTP exchange,
* but the HTTP exchange may also be carried using the FCGI protocol, the HTTP/2 protocol or,
@@ -50,16 +50,24 @@ public interface HttpClientTransport extends ClientConnectionFactory
*/
public void setHttpClient(HttpClient client);
+ /**
+ * Creates a new Origin with the given request.
+ *
+ * @param request the request that triggers the creation of the Origin
+ * @return an Origin that identifies a destination
+ */
+ public Origin newOrigin(HttpRequest request);
+
/**
* Creates a new, transport-specific, {@link HttpDestination} object.
*
* {@link HttpDestination} controls the destination-connection cardinality: protocols like
* HTTP have 1-N cardinality, while multiplexed protocols like HTTP/2 have a 1-1 cardinality.
*
- * @param key the destination key
+ * @param origin the destination origin
* @return a new, transport-specific, {@link HttpDestination} object
*/
- public HttpDestination newHttpDestination(HttpDestination.Key key);
+ public HttpDestination newHttpDestination(Origin origin);
/**
* Establishes a physical connection to the given {@code address}.
@@ -78,20 +86,4 @@ public interface HttpClientTransport extends ClientConnectionFactory
* @param factory the factory for ConnectionPool instances
*/
public void setConnectionPoolFactory(ConnectionPool.Factory factory);
-
- /**
- * Specifies whether a {@link HttpClientTransport} is dynamic.
- */
- @FunctionalInterface
- public interface Dynamic
- {
- /**
- * Creates a new Key with the given request and origin.
- *
- * @param request the request that triggers the creation of the Key
- * @param origin the origin of the server for the request
- * @return a Key that identifies a destination
- */
- public HttpDestination.Key newDestinationKey(HttpRequest request, Origin origin);
- }
}
diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpConnection.java b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpConnection.java
index 53cb43a7430..cb6cc8f844c 100644
--- a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpConnection.java
+++ b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpConnection.java
@@ -1,19 +1,19 @@
//
-// ========================================================================
-// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd.
-// ------------------------------------------------------------------------
-// All rights reserved. This program and the accompanying materials
-// are made available under the terms of the Eclipse Public License v1.0
-// and Apache License v2.0 which accompanies this distribution.
+// ========================================================================
+// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others.
//
-// The Eclipse Public License is available at
-// http://www.eclipse.org/legal/epl-v10.html
+// 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
//
-// The Apache License v2.0 is available at
-// http://www.opensource.org/licenses/apache2.0.php
+// 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
//
-// You may elect to redistribute this code under either of these licenses.
-// ========================================================================
+// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
+// ========================================================================
//
package org.eclipse.jetty.client;
@@ -34,12 +34,12 @@ import org.eclipse.jetty.http.HttpFields;
import org.eclipse.jetty.http.HttpHeader;
import org.eclipse.jetty.http.HttpVersion;
import org.eclipse.jetty.util.HttpCookieStore;
-import org.eclipse.jetty.util.log.Log;
-import org.eclipse.jetty.util.log.Logger;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public abstract class HttpConnection implements IConnection
{
- private static final Logger LOG = Log.getLogger(HttpConnection.class);
+ private static final Logger LOG = LoggerFactory.getLogger(HttpConnection.class);
private final HttpDestination destination;
private int idleTimeoutGuard;
@@ -123,10 +123,16 @@ public abstract class HttpConnection implements IConnection
protected void normalizeRequest(Request request)
{
- final HttpVersion version = request.getVersion();
- final HttpFields headers = request.getHeaders();
- final ContentProvider content = request.getContent();
- final ProxyConfiguration.Proxy proxy = destination.getProxy();
+ boolean normalized = ((HttpRequest)request).normalized();
+ if (LOG.isDebugEnabled())
+ LOG.debug("Normalizing {} {}", !normalized, request);
+ if (normalized)
+ return;
+
+ HttpVersion version = request.getVersion();
+ HttpFields headers = request.getHeaders();
+ ContentProvider content = request.getContent();
+ ProxyConfiguration.Proxy proxy = destination.getProxy();
// Make sure the path is there
String path = request.getPath();
diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpContent.java b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpContent.java
index efb5e983e4d..dc9bf42b7e9 100644
--- a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpContent.java
+++ b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpContent.java
@@ -1,19 +1,19 @@
//
-// ========================================================================
-// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd.
-// ------------------------------------------------------------------------
-// All rights reserved. This program and the accompanying materials
-// are made available under the terms of the Eclipse Public License v1.0
-// and Apache License v2.0 which accompanies this distribution.
+// ========================================================================
+// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others.
//
-// The Eclipse Public License is available at
-// http://www.eclipse.org/legal/epl-v10.html
+// 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
//
-// The Apache License v2.0 is available at
-// http://www.opensource.org/licenses/apache2.0.php
+// 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
//
-// You may elect to redistribute this code under either of these licenses.
-// ========================================================================
+// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
+// ========================================================================
//
package org.eclipse.jetty.client;
@@ -26,13 +26,14 @@ import java.util.Iterator;
import org.eclipse.jetty.client.api.ContentProvider;
import org.eclipse.jetty.util.BufferUtil;
import org.eclipse.jetty.util.Callback;
-import org.eclipse.jetty.util.log.Log;
-import org.eclipse.jetty.util.log.Logger;
+import org.eclipse.jetty.util.IO;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* {@link HttpContent} is a stateful, linear representation of the request content provided
* by a {@link ContentProvider} that can be traversed one-way to obtain content buffers to
- * send to a HTTP server.
+ * send to an HTTP server.
*
* {@link HttpContent} offers the notion of a one-way cursor to traverse the content.
* The cursor starts in a virtual "before" position and can be advanced using {@link #advance()}
@@ -65,7 +66,7 @@ import org.eclipse.jetty.util.log.Logger;
*/
public class HttpContent implements Callback, Closeable
{
- private static final Logger LOG = Log.getLogger(HttpContent.class);
+ private static final Logger LOG = LoggerFactory.getLogger(HttpContent.class);
private static final ByteBuffer AFTER = ByteBuffer.allocate(0);
private static final ByteBuffer CLOSE = ByteBuffer.allocate(0);
@@ -218,15 +219,8 @@ public class HttpContent implements Callback, Closeable
@Override
public void close()
{
- try
- {
- if (iterator instanceof Closeable)
- ((Closeable)iterator).close();
- }
- catch (Throwable x)
- {
- LOG.ignore(x);
- }
+ if (iterator instanceof Closeable)
+ IO.close((Closeable)iterator);
}
@Override
diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpContentResponse.java b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpContentResponse.java
index 2a1aec0cc4b..471f6e5f03e 100644
--- a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpContentResponse.java
+++ b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpContentResponse.java
@@ -1,19 +1,19 @@
//
-// ========================================================================
-// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd.
-// ------------------------------------------------------------------------
-// All rights reserved. This program and the accompanying materials
-// are made available under the terms of the Eclipse Public License v1.0
-// and Apache License v2.0 which accompanies this distribution.
+// ========================================================================
+// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others.
//
-// The Eclipse Public License is available at
-// http://www.eclipse.org/legal/epl-v10.html
+// 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
//
-// The Apache License v2.0 is available at
-// http://www.opensource.org/licenses/apache2.0.php
+// 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
//
-// You may elect to redistribute this code under either of these licenses.
-// ========================================================================
+// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
+// ========================================================================
//
package org.eclipse.jetty.client;
diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpConversation.java b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpConversation.java
index d1151d27b63..1eddf461326 100644
--- a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpConversation.java
+++ b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpConversation.java
@@ -1,19 +1,19 @@
//
-// ========================================================================
-// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd.
-// ------------------------------------------------------------------------
-// All rights reserved. This program and the accompanying materials
-// are made available under the terms of the Eclipse Public License v1.0
-// and Apache License v2.0 which accompanies this distribution.
+// ========================================================================
+// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others.
//
-// The Eclipse Public License is available at
-// http://www.eclipse.org/legal/epl-v10.html
+// 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
//
-// The Apache License v2.0 is available at
-// http://www.opensource.org/licenses/apache2.0.php
+// 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
//
-// You may elect to redistribute this code under either of these licenses.
-// ========================================================================
+// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
+// ========================================================================
//
package org.eclipse.jetty.client;
@@ -25,12 +25,12 @@ import java.util.concurrent.ConcurrentLinkedDeque;
import org.eclipse.jetty.client.api.Response;
import org.eclipse.jetty.util.AttributesMap;
-import org.eclipse.jetty.util.log.Log;
-import org.eclipse.jetty.util.log.Logger;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class HttpConversation extends AttributesMap
{
- private static final Logger LOG = Log.getLogger(HttpConversation.class);
+ private static final Logger LOG = LoggerFactory.getLogger(HttpConversation.class);
private final Deque Class that groups the elements that uniquely identify a destination. The elements are an {@link Origin}, a {@link Protocol} and an opaque
- * string that further distinguishes destinations that have the same origin
- * and protocol. In general it is possible that, for the same origin, the server can
- * speak different protocols (for example, clear-text HTTP/1.1 and clear-text
- * HTTP/2), so the {@link Protocol} makes that distinction. Furthermore, it may be desirable to have different destinations for
- * the same origin and protocol (for example, when using the PROXY protocol
- * in a reverse proxy server, you want to be able to map the client ip:port
- * to the destination {@code kind}, so that all the connections to the server
- * associated to that destination can specify the PROXY protocol bytes for
- * that particular client connection. The representation of a network protocol. A network protocol may have multiple protocol names
- * associated to it, for example {@code ["h2", "h2-17", "h2-16"]}. A Protocol is then rendered into a {@link ClientConnectionFactory}
- * chain, for example in
- * {@link HttpClientTransportDynamic#newConnection(EndPoint, Map)}.
@@ -116,13 +176,12 @@ public abstract class HttpReceiver
if (!updateResponseState(ResponseState.IDLE, ResponseState.TRANSIENT))
return false;
- final HttpConversation conversation = exchange.getConversation();
- final HttpResponse response = exchange.getResponse();
+ HttpConversation conversation = exchange.getConversation();
+ HttpResponse response = exchange.getResponse();
// Probe the protocol handlers
- final HttpDestination destination = getHttpDestination();
- final HttpClient client = destination.getHttpClient();
- final ProtocolHandler protocolHandler = client.findProtocolHandler(exchange.getRequest(), response);
-
+ HttpDestination destination = getHttpDestination();
+ HttpClient client = destination.getHttpClient();
+ ProtocolHandler protocolHandler = client.findProtocolHandler(exchange.getRequest(), response);
Response.Listener handlerListener = null;
if (protocolHandler != null)
{
@@ -227,7 +286,7 @@ public abstract class HttpReceiver
catch (IOException x)
{
if (LOG.isDebugEnabled())
- LOG.debug(x);
+ LOG.debug("Unable to store cookies {} from {}", field, uri, x);
}
}
@@ -241,23 +300,17 @@ public abstract class HttpReceiver
*/
protected boolean responseHeaders(HttpExchange exchange)
{
- out:
while (true)
{
ResponseState current = responseState.get();
- switch (current)
+ if (current == ResponseState.BEGIN || current == ResponseState.HEADER)
{
- case BEGIN:
- case HEADER:
- {
- if (updateResponseState(current, ResponseState.TRANSIENT))
- break out;
+ if (updateResponseState(current, ResponseState.TRANSIENT))
break;
- }
- default:
- {
- return false;
- }
+ }
+ else
+ {
+ return false;
}
}
@@ -267,29 +320,35 @@ public abstract class HttpReceiver
ResponseNotifier notifier = getHttpDestination().getResponseNotifier();
List
* Subclasses should override (but remember to call {@code super}) to reset their own state.
*
@@ -456,13 +555,11 @@ public abstract class HttpReceiver
*/
protected void reset()
{
- contentListeners = null;
- destroyDecoder(decoder);
- decoder = null;
+ cleanup();
}
/**
- * Disposes this {@link HttpReceiver} state.
+ * Disposes the state of this HttpReceiver.
*
* Subclasses should override (but remember to call {@code super}) to dispose their own state.
*
@@ -470,41 +567,32 @@ public abstract class HttpReceiver
*/
protected void dispose()
{
- destroyDecoder(decoder);
- decoder = null;
+ cleanup();
}
- private static void destroyDecoder(ContentDecoder decoder)
+ private void cleanup()
{
- if (decoder instanceof Destroyable)
- {
- ((Destroyable)decoder).destroy();
- }
+ contentListeners = null;
+ if (decoder != null)
+ decoder.destroy();
+ decoder = null;
+ demand = 0;
+ stalled = false;
}
public boolean abort(HttpExchange exchange, Throwable failure)
{
// Update the state to avoid more response processing.
boolean terminate;
- out:
while (true)
{
ResponseState current = responseState.get();
- switch (current)
+ if (current == ResponseState.FAILURE)
+ return false;
+ if (updateResponseState(current, ResponseState.FAILURE))
{
- case FAILURE:
- {
- return false;
- }
- default:
- {
- if (updateResponseState(current, ResponseState.FAILURE))
- {
- terminate = current != ResponseState.TRANSIENT;
- break out;
- }
- break;
- }
+ terminate = current != ResponseState.TRANSIENT;
+ break;
}
}
@@ -514,17 +602,19 @@ public abstract class HttpReceiver
HttpResponse response = exchange.getResponse();
if (LOG.isDebugEnabled())
- LOG.debug("Response failure {} {} on {}: {}", response, exchange, getHttpChannel(), failure);
+ LOG.debug("Response abort {} {} on {}: {}", response, exchange, getHttpChannel(), failure);
List Wraps a list of content listeners, notifies them about content events and
+ * tracks individual listener demand to produce a global demand for content. A HttpUpgrader that upgrades to a given protocol. Works in conjunction with {@link HttpClientTransportDynamic}
+ * so that the protocol to upgrade to must be one of the application
+ * protocols supported by HttpClientTransportDynamic. A {@link ContentProvider} for form uploads with the {@code "multipart/form-data"}
@@ -65,7 +66,7 @@ import org.eclipse.jetty.util.log.Logger;
*/
public class MultiPartContentProvider extends AbstractTypedContentProvider implements AsyncContentProvider, Closeable
{
- private static final Logger LOG = Log.getLogger(MultiPartContentProvider.class);
+ private static final Logger LOG = LoggerFactory.getLogger(MultiPartContentProvider.class);
private static final byte[] COLON_SPACE_BYTES = new byte[]{':', ' '};
private static final byte[] CR_LF_BYTES = new byte[]{'\r', '\n'};
@@ -345,10 +346,16 @@ public class MultiPartContentProvider extends AbstractTypedContentProvider imple
if (iterator.hasNext())
return iterator.next();
++index;
- if (index == parts.size())
- state = State.LAST_BOUNDARY;
- else
+ if (index < parts.size())
+ {
state = State.MIDDLE_BOUNDARY;
+ if (iterator instanceof Closeable)
+ IO.close((Closeable)iterator);
+ }
+ else
+ {
+ state = State.LAST_BOUNDARY;
+ }
break;
}
case MIDDLE_BOUNDARY:
@@ -383,14 +390,14 @@ public class MultiPartContentProvider extends AbstractTypedContentProvider imple
@Override
public void succeeded()
{
- if (iterator instanceof Callback)
+ if (state == State.CONTENT && iterator instanceof Callback)
((Callback)iterator).succeeded();
}
@Override
public void failed(Throwable x)
{
- if (iterator instanceof Callback)
+ if (state == State.CONTENT && iterator instanceof Callback)
((Callback)iterator).failed(x);
}
diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/util/OutputStreamContentProvider.java b/jetty-client/src/main/java/org/eclipse/jetty/client/util/OutputStreamContentProvider.java
index 096c4a85c17..edffa00bd68 100644
--- a/jetty-client/src/main/java/org/eclipse/jetty/client/util/OutputStreamContentProvider.java
+++ b/jetty-client/src/main/java/org/eclipse/jetty/client/util/OutputStreamContentProvider.java
@@ -1,19 +1,19 @@
//
-// ========================================================================
-// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd.
-// ------------------------------------------------------------------------
-// All rights reserved. This program and the accompanying materials
-// are made available under the terms of the Eclipse Public License v1.0
-// and Apache License v2.0 which accompanies this distribution.
+// ========================================================================
+// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others.
//
-// The Eclipse Public License is available at
-// http://www.eclipse.org/legal/epl-v10.html
+// 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
//
-// The Apache License v2.0 is available at
-// http://www.opensource.org/licenses/apache2.0.php
+// 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
//
-// You may elect to redistribute this code under either of these licenses.
-// ========================================================================
+// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
+// ========================================================================
//
package org.eclipse.jetty.client.util;
diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/util/PathContentProvider.java b/jetty-client/src/main/java/org/eclipse/jetty/client/util/PathContentProvider.java
index aa562e5111b..ffa41c752bb 100644
--- a/jetty-client/src/main/java/org/eclipse/jetty/client/util/PathContentProvider.java
+++ b/jetty-client/src/main/java/org/eclipse/jetty/client/util/PathContentProvider.java
@@ -1,19 +1,19 @@
//
-// ========================================================================
-// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd.
-// ------------------------------------------------------------------------
-// All rights reserved. This program and the accompanying materials
-// are made available under the terms of the Eclipse Public License v1.0
-// and Apache License v2.0 which accompanies this distribution.
+// ========================================================================
+// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others.
//
-// The Eclipse Public License is available at
-// http://www.eclipse.org/legal/epl-v10.html
+// 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
//
-// The Apache License v2.0 is available at
-// http://www.opensource.org/licenses/apache2.0.php
+// 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
//
-// You may elect to redistribute this code under either of these licenses.
-// ========================================================================
+// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
+// ========================================================================
//
package org.eclipse.jetty.client.util;
@@ -32,8 +32,9 @@ import java.util.NoSuchElementException;
import org.eclipse.jetty.client.api.ContentProvider;
import org.eclipse.jetty.io.ByteBufferPool;
-import org.eclipse.jetty.util.log.Log;
-import org.eclipse.jetty.util.log.Logger;
+import org.eclipse.jetty.util.BufferUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* A {@link ContentProvider} for files using JDK 7's {@code java.nio.file} APIs. Implementation of the SPNEGO (or "Negotiate") authentication defined in RFC 4559.
*
Parser for FastCGI frame headers.
@@ -41,7 +41,7 @@ import org.eclipse.jetty.util.log.Logger; */ public class HeaderParser { - private static final Logger LOG = Log.getLogger(Parser.class); + private static final Logger LOG = LoggerFactory.getLogger(Parser.class); private State state = State.VERSION; private int cursor; diff --git a/jetty-fcgi/fcgi-client/src/main/java/org/eclipse/jetty/fcgi/parser/ParamsContentParser.java b/jetty-fcgi/fcgi-client/src/main/java/org/eclipse/jetty/fcgi/parser/ParamsContentParser.java index 888f12a1863..538d229db9f 100644 --- a/jetty-fcgi/fcgi-client/src/main/java/org/eclipse/jetty/fcgi/parser/ParamsContentParser.java +++ b/jetty-fcgi/fcgi-client/src/main/java/org/eclipse/jetty/fcgi/parser/ParamsContentParser.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.fcgi.parser; @@ -23,8 +23,8 @@ import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import org.eclipse.jetty.http.HttpField; -import org.eclipse.jetty.util.log.Log; -import org.eclipse.jetty.util.log.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** *Parser for the PARAMS frame body.
@@ -60,7 +60,7 @@ import org.eclipse.jetty.util.log.Logger; */ public class ParamsContentParser extends ContentParser { - private static final Logger LOG = Log.getLogger(ParamsContentParser.class); + private static final Logger LOG = LoggerFactory.getLogger(ParamsContentParser.class); private final ServerParser.Listener listener; private State state = State.LENGTH; diff --git a/jetty-fcgi/fcgi-client/src/main/java/org/eclipse/jetty/fcgi/parser/Parser.java b/jetty-fcgi/fcgi-client/src/main/java/org/eclipse/jetty/fcgi/parser/Parser.java index 8eee11f53b1..b4abccd8268 100644 --- a/jetty-fcgi/fcgi-client/src/main/java/org/eclipse/jetty/fcgi/parser/Parser.java +++ b/jetty-fcgi/fcgi-client/src/main/java/org/eclipse/jetty/fcgi/parser/Parser.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.fcgi.parser; @@ -22,8 +22,8 @@ import java.nio.ByteBuffer; import org.eclipse.jetty.fcgi.FCGI; import org.eclipse.jetty.http.HttpField; -import org.eclipse.jetty.util.log.Log; -import org.eclipse.jetty.util.log.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** *The FastCGI protocol exchanges frames.
@@ -47,7 +47,7 @@ import org.eclipse.jetty.util.log.Logger; */ public abstract class Parser { - private static final Logger LOG = Log.getLogger(Parser.class); + private static final Logger LOG = LoggerFactory.getLogger(Parser.class); protected final HeaderParser headerParser = new HeaderParser(); private State state = State.HEADER; @@ -135,7 +135,11 @@ public abstract class Parser { public void onHeader(int request, HttpField field); - public void onHeaders(int request); + /** + * @param request the request id + * @return true to signal to the parser to stop parsing, false to continue parsing + */ + public boolean onHeaders(int request); /** * @param request the request id @@ -158,8 +162,9 @@ public abstract class Parser } @Override - public void onHeaders(int request) + public boolean onHeaders(int request) { + return false; } @Override diff --git a/jetty-fcgi/fcgi-client/src/main/java/org/eclipse/jetty/fcgi/parser/ResponseContentParser.java b/jetty-fcgi/fcgi-client/src/main/java/org/eclipse/jetty/fcgi/parser/ResponseContentParser.java index 51742bde50b..ade1a39b03c 100644 --- a/jetty-fcgi/fcgi-client/src/main/java/org/eclipse/jetty/fcgi/parser/ResponseContentParser.java +++ b/jetty-fcgi/fcgi-client/src/main/java/org/eclipse/jetty/fcgi/parser/ResponseContentParser.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.fcgi.parser; @@ -32,8 +32,8 @@ import org.eclipse.jetty.http.HttpHeader; import org.eclipse.jetty.http.HttpParser; import org.eclipse.jetty.http.HttpStatus; import org.eclipse.jetty.http.HttpVersion; -import org.eclipse.jetty.util.log.Log; -import org.eclipse.jetty.util.log.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** *The parser for STDOUT type frame bodies.
@@ -45,7 +45,7 @@ import org.eclipse.jetty.util.log.Logger; */ public class ResponseContentParser extends StreamContentParser { - private static final Logger LOG = Log.getLogger(ResponseContentParser.class); + private static final Logger LOG = LoggerFactory.getLogger(ResponseContentParser.class); private final MapA stream content parser parses frame bodies of type STDIN, STDOUT and STDERR.
@@ -30,7 +30,7 @@ import org.eclipse.jetty.util.log.Logger; */ public class StreamContentParser extends ContentParser { - private static final Logger LOG = Log.getLogger(StreamContentParser.class); + private static final Logger LOG = LoggerFactory.getLogger(StreamContentParser.class); private final FCGI.StreamType streamType; private final Parser.Listener listener; diff --git a/jetty-fcgi/fcgi-client/src/test/java/org/eclipse/jetty/fcgi/generator/ClientGeneratorTest.java b/jetty-fcgi/fcgi-client/src/test/java/org/eclipse/jetty/fcgi/generator/ClientGeneratorTest.java index 67e6fe9761b..3900eadef18 100644 --- a/jetty-fcgi/fcgi-client/src/test/java/org/eclipse/jetty/fcgi/generator/ClientGeneratorTest.java +++ b/jetty-fcgi/fcgi-client/src/test/java/org/eclipse/jetty/fcgi/generator/ClientGeneratorTest.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.fcgi.generator; @@ -109,10 +109,11 @@ public class ClientGeneratorTest } @Override - public void onHeaders(int request) + public boolean onHeaders(int request) { assertEquals(id, request); params.set(params.get() * primes[4]); + return false; } }); diff --git a/jetty-fcgi/fcgi-client/src/test/java/org/eclipse/jetty/fcgi/parser/ClientParserTest.java b/jetty-fcgi/fcgi-client/src/test/java/org/eclipse/jetty/fcgi/parser/ClientParserTest.java index 7e9e9dbb2b6..9238a48eef8 100644 --- a/jetty-fcgi/fcgi-client/src/test/java/org/eclipse/jetty/fcgi/parser/ClientParserTest.java +++ b/jetty-fcgi/fcgi-client/src/test/java/org/eclipse/jetty/fcgi/parser/ClientParserTest.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.fcgi.parser; @@ -91,10 +91,11 @@ public class ClientParserTest } @Override - public void onHeaders(int request) + public boolean onHeaders(int request) { assertEquals(id, request); params.set(params.get() * primes[2]); + return false; } }); diff --git a/jetty-fcgi/fcgi-client/src/test/resources/jetty-logging.properties b/jetty-fcgi/fcgi-client/src/test/resources/jetty-logging.properties index b8df62d071d..4e7406f1b54 100644 --- a/jetty-fcgi/fcgi-client/src/test/resources/jetty-logging.properties +++ b/jetty-fcgi/fcgi-client/src/test/resources/jetty-logging.properties @@ -1,3 +1,3 @@ -org.eclipse.jetty.util.log.class=org.eclipse.jetty.util.log.StdErrLog +# Jetty Logging using jetty-slf4j-impl #org.eclipse.jetty.client.LEVEL=DEBUG #org.eclipse.jetty.fcgi.LEVEL=DEBUG diff --git a/jetty-fcgi/fcgi-server/pom.xml b/jetty-fcgi/fcgi-server/pom.xml index 742fcf5a9fe..7eb70468863 100644 --- a/jetty-fcgi/fcgi-server/pom.xml +++ b/jetty-fcgi/fcgi-server/pom.xml @@ -15,6 +15,10 @@- * This servlet accepts a HTTP request and transforms it into a FastCGI request + * This servlet accepts an HTTP request and transforms it into a FastCGI request * that is sent to the FastCGI server specified in the {@code proxyTo} * init-param. *
@@ -260,7 +260,7 @@ public class FastCGIProxyServlet extends AsyncProxyServlet.Transparent
fcgi.put(field.getName(), field.getValue());
}
String eol = System.lineSeparator();
- _log.debug("FastCGI variables{}{}", eol, fcgi.entrySet().stream()
+ _log.debug("FastCGI variables {}{}", eol, fcgi.entrySet().stream()
.map(entry -> String.format("%s: %s", entry.getKey(), entry.getValue()))
.collect(Collectors.joining(eol)));
}
diff --git a/jetty-fcgi/fcgi-server/src/main/java/org/eclipse/jetty/fcgi/server/proxy/TryFilesFilter.java b/jetty-fcgi/fcgi-server/src/main/java/org/eclipse/jetty/fcgi/server/proxy/TryFilesFilter.java
index 7a047c6c1cc..edfa3f8bdd4 100644
--- a/jetty-fcgi/fcgi-server/src/main/java/org/eclipse/jetty/fcgi/server/proxy/TryFilesFilter.java
+++ b/jetty-fcgi/fcgi-server/src/main/java/org/eclipse/jetty/fcgi/server/proxy/TryFilesFilter.java
@@ -1,19 +1,19 @@
//
-// ========================================================================
-// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd.
-// ------------------------------------------------------------------------
-// All rights reserved. This program and the accompanying materials
-// are made available under the terms of the Eclipse Public License v1.0
-// and Apache License v2.0 which accompanies this distribution.
+// ========================================================================
+// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others.
//
-// The Eclipse Public License is available at
-// http://www.eclipse.org/legal/epl-v10.html
+// 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
//
-// The Apache License v2.0 is available at
-// http://www.opensource.org/licenses/apache2.0.php
+// 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
//
-// You may elect to redistribute this code under either of these licenses.
-// ========================================================================
+// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
+// ========================================================================
//
package org.eclipse.jetty.fcgi.server.proxy;
diff --git a/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/AbstractHttpClientServerTest.java b/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/AbstractHttpClientServerTest.java
index 3a95b768888..9e791a2513f 100644
--- a/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/AbstractHttpClientServerTest.java
+++ b/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/AbstractHttpClientServerTest.java
@@ -1,19 +1,19 @@
//
-// ========================================================================
-// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd.
-// ------------------------------------------------------------------------
-// All rights reserved. This program and the accompanying materials
-// are made available under the terms of the Eclipse Public License v1.0
-// and Apache License v2.0 which accompanies this distribution.
+// ========================================================================
+// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others.
//
-// The Eclipse Public License is available at
-// http://www.eclipse.org/legal/epl-v10.html
+// 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
//
-// The Apache License v2.0 is available at
-// http://www.opensource.org/licenses/apache2.0.php
+// 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
//
-// You may elect to redistribute this code under either of these licenses.
-// ========================================================================
+// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
+// ========================================================================
//
package org.eclipse.jetty.fcgi.server;
diff --git a/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/EmptyServerHandler.java b/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/EmptyServerHandler.java
index 708231649b1..760ea2b5ae9 100644
--- a/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/EmptyServerHandler.java
+++ b/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/EmptyServerHandler.java
@@ -1,19 +1,19 @@
//
-// ========================================================================
-// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd.
-// ------------------------------------------------------------------------
-// All rights reserved. This program and the accompanying materials
-// are made available under the terms of the Eclipse Public License v1.0
-// and Apache License v2.0 which accompanies this distribution.
+// ========================================================================
+// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others.
//
-// The Eclipse Public License is available at
-// http://www.eclipse.org/legal/epl-v10.html
+// 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
//
-// The Apache License v2.0 is available at
-// http://www.opensource.org/licenses/apache2.0.php
+// 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
//
-// You may elect to redistribute this code under either of these licenses.
-// ========================================================================
+// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
+// ========================================================================
//
package org.eclipse.jetty.fcgi.server;
diff --git a/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/ExternalFastCGIServerTest.java b/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/ExternalFastCGIServerTest.java
index 1aade944611..6791ea37954 100644
--- a/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/ExternalFastCGIServerTest.java
+++ b/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/ExternalFastCGIServerTest.java
@@ -1,19 +1,19 @@
//
-// ========================================================================
-// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd.
-// ------------------------------------------------------------------------
-// All rights reserved. This program and the accompanying materials
-// are made available under the terms of the Eclipse Public License v1.0
-// and Apache License v2.0 which accompanies this distribution.
+// ========================================================================
+// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others.
//
-// The Eclipse Public License is available at
-// http://www.eclipse.org/legal/epl-v10.html
+// 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
//
-// The Apache License v2.0 is available at
-// http://www.opensource.org/licenses/apache2.0.php
+// 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
//
-// You may elect to redistribute this code under either of these licenses.
-// ========================================================================
+// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
+// ========================================================================
//
package org.eclipse.jetty.fcgi.server;
diff --git a/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/HttpClientTest.java b/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/HttpClientTest.java
index 8a4b959b9d4..f2727aab175 100644
--- a/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/HttpClientTest.java
+++ b/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/HttpClientTest.java
@@ -1,19 +1,19 @@
//
-// ========================================================================
-// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd.
-// ------------------------------------------------------------------------
-// All rights reserved. This program and the accompanying materials
-// are made available under the terms of the Eclipse Public License v1.0
-// and Apache License v2.0 which accompanies this distribution.
+// ========================================================================
+// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others.
//
-// The Eclipse Public License is available at
-// http://www.eclipse.org/legal/epl-v10.html
+// 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
//
-// The Apache License v2.0 is available at
-// http://www.opensource.org/licenses/apache2.0.php
+// 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
//
-// You may elect to redistribute this code under either of these licenses.
-// ========================================================================
+// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
+// ========================================================================
//
package org.eclipse.jetty.fcgi.server;
@@ -45,11 +45,11 @@ import org.eclipse.jetty.client.util.DeferredContentProvider;
import org.eclipse.jetty.client.util.FutureResponseListener;
import org.eclipse.jetty.http.HttpMethod;
import org.eclipse.jetty.io.MappedByteBufferPool;
+import org.eclipse.jetty.logging.StacklessLogging;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.toolchain.test.IO;
import org.eclipse.jetty.toolchain.test.Net;
import org.eclipse.jetty.util.Callback;
-import org.eclipse.jetty.util.log.StacklessLogging;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledIfSystemProperty;
@@ -64,6 +64,8 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
public class HttpClientTest extends AbstractHttpClientServerTest
{
+ // @checkstyle-disable-check : AvoidEscapedUnicodeCharactersCheck
+
@Test
public void testGETResponseWithoutContent() throws Exception
{
diff --git a/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/proxy/DrupalHTTP2FastCGIProxyServer.java b/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/proxy/DrupalHTTP2FastCGIProxyServer.java
index 9584ead7dd2..0a81190dcd8 100644
--- a/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/proxy/DrupalHTTP2FastCGIProxyServer.java
+++ b/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/proxy/DrupalHTTP2FastCGIProxyServer.java
@@ -1,19 +1,19 @@
//
-// ========================================================================
-// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd.
-// ------------------------------------------------------------------------
-// All rights reserved. This program and the accompanying materials
-// are made available under the terms of the Eclipse Public License v1.0
-// and Apache License v2.0 which accompanies this distribution.
+// ========================================================================
+// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others.
//
-// The Eclipse Public License is available at
-// http://www.eclipse.org/legal/epl-v10.html
+// 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
//
-// The Apache License v2.0 is available at
-// http://www.opensource.org/licenses/apache2.0.php
+// 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
//
-// You may elect to redistribute this code under either of these licenses.
-// ========================================================================
+// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
+// ========================================================================
//
package org.eclipse.jetty.fcgi.server.proxy;
@@ -37,21 +37,19 @@ public class DrupalHTTP2FastCGIProxyServer
public static void main(String[] args) throws Exception
{
SslContextFactory.Server sslContextFactory = new SslContextFactory.Server();
- sslContextFactory.setKeyStorePath("src/test/resources/keystore.jks");
+ sslContextFactory.setKeyStorePath("src/test/resources/keystore.p12");
sslContextFactory.setKeyStorePassword("storepwd");
- sslContextFactory.setTrustStorePath("src/test/resources/truststore.jks");
- sslContextFactory.setTrustStorePassword("storepwd");
sslContextFactory.setCipherComparator(new HTTP2Cipher.CipherComparator());
Server server = new Server();
// HTTP(S) Configuration
HttpConfiguration config = new HttpConfiguration();
- HttpConfiguration https_config = new HttpConfiguration(config);
- https_config.addCustomizer(new SecureRequestCustomizer());
+ HttpConfiguration httpsConfig = new HttpConfiguration(config);
+ httpsConfig.addCustomizer(new SecureRequestCustomizer());
// HTTP2 factory
- HTTP2ServerConnectionFactory h2 = new HTTP2ServerConnectionFactory(https_config);
+ HTTP2ServerConnectionFactory h2 = new HTTP2ServerConnectionFactory(httpsConfig);
ALPNServerConnectionFactory alpn = new ALPNServerConnectionFactory();
alpn.setDefaultProtocol(h2.getProtocol());
@@ -60,7 +58,7 @@ public class DrupalHTTP2FastCGIProxyServer
// HTTP2 Connector
ServerConnector http2Connector =
- new ServerConnector(server, ssl, alpn, h2, new HttpConnectionFactory(https_config));
+ new ServerConnector(server, ssl, alpn, h2, new HttpConnectionFactory(httpsConfig));
http2Connector.setPort(8443);
http2Connector.setIdleTimeout(15000);
server.addConnector(http2Connector);
diff --git a/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/proxy/FastCGIProxyServletTest.java b/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/proxy/FastCGIProxyServletTest.java
index e3a93abb663..68919b66ede 100644
--- a/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/proxy/FastCGIProxyServletTest.java
+++ b/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/proxy/FastCGIProxyServletTest.java
@@ -1,19 +1,19 @@
//
-// ========================================================================
-// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd.
-// ------------------------------------------------------------------------
-// All rights reserved. This program and the accompanying materials
-// are made available under the terms of the Eclipse Public License v1.0
-// and Apache License v2.0 which accompanies this distribution.
+// ========================================================================
+// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others.
//
-// The Eclipse Public License is available at
-// http://www.eclipse.org/legal/epl-v10.html
+// 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
//
-// The Apache License v2.0 is available at
-// http://www.opensource.org/licenses/apache2.0.php
+// 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
//
-// You may elect to redistribute this code under either of these licenses.
-// ========================================================================
+// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
+// ========================================================================
//
package org.eclipse.jetty.fcgi.server.proxy;
diff --git a/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/proxy/TryFilesFilterTest.java b/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/proxy/TryFilesFilterTest.java
index f42aaae0a6a..dc785eb841e 100644
--- a/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/proxy/TryFilesFilterTest.java
+++ b/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/proxy/TryFilesFilterTest.java
@@ -1,19 +1,19 @@
//
-// ========================================================================
-// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd.
-// ------------------------------------------------------------------------
-// All rights reserved. This program and the accompanying materials
-// are made available under the terms of the Eclipse Public License v1.0
-// and Apache License v2.0 which accompanies this distribution.
+// ========================================================================
+// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others.
//
-// The Eclipse Public License is available at
-// http://www.eclipse.org/legal/epl-v10.html
+// 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
//
-// The Apache License v2.0 is available at
-// http://www.opensource.org/licenses/apache2.0.php
+// 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
//
-// You may elect to redistribute this code under either of these licenses.
-// ========================================================================
+// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
+// ========================================================================
//
package org.eclipse.jetty.fcgi.server.proxy;
@@ -55,7 +55,7 @@ public class TryFilesFilterTest
server.addConnector(connector);
SslContextFactory.Server serverSslContextFactory = new SslContextFactory.Server();
- serverSslContextFactory.setKeyStorePath("src/test/resources/keystore.jks");
+ serverSslContextFactory.setKeyStorePath("src/test/resources/keystore.p12");
serverSslContextFactory.setKeyStorePassword("storepwd");
sslConnector = new ServerConnector(server, serverSslContextFactory);
server.addConnector(sslConnector);
@@ -71,10 +71,8 @@ public class TryFilesFilterTest
ClientConnector clientConnector = new ClientConnector();
SslContextFactory.Client clientSslContextFactory = new SslContextFactory.Client();
clientSslContextFactory.setEndpointIdentificationAlgorithm(null);
- clientSslContextFactory.setKeyStorePath("src/test/resources/keystore.jks");
+ clientSslContextFactory.setKeyStorePath("src/test/resources/keystore.p12");
clientSslContextFactory.setKeyStorePassword("storepwd");
- clientSslContextFactory.setTrustStorePath("src/test/resources/truststore.jks");
- clientSslContextFactory.setTrustStorePassword("storepwd");
clientConnector.setSslContextFactory(clientSslContextFactory);
client = new HttpClient(new HttpClientTransportOverHTTP(clientConnector));
server.addBean(client);
diff --git a/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/proxy/WordPressHTTP2FastCGIProxyServer.java b/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/proxy/WordPressHTTP2FastCGIProxyServer.java
index 0818d1dae93..f8aa371c7bd 100644
--- a/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/proxy/WordPressHTTP2FastCGIProxyServer.java
+++ b/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/proxy/WordPressHTTP2FastCGIProxyServer.java
@@ -1,19 +1,19 @@
//
-// ========================================================================
-// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd.
-// ------------------------------------------------------------------------
-// All rights reserved. This program and the accompanying materials
-// are made available under the terms of the Eclipse Public License v1.0
-// and Apache License v2.0 which accompanies this distribution.
+// ========================================================================
+// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others.
//
-// The Eclipse Public License is available at
-// http://www.eclipse.org/legal/epl-v10.html
+// 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
//
-// The Apache License v2.0 is available at
-// http://www.opensource.org/licenses/apache2.0.php
+// 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
//
-// You may elect to redistribute this code under either of these licenses.
-// ========================================================================
+// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
+// ========================================================================
//
package org.eclipse.jetty.fcgi.server.proxy;
@@ -43,21 +43,19 @@ public class WordPressHTTP2FastCGIProxyServer
int tlsPort = 8443;
SslContextFactory.Server sslContextFactory = new SslContextFactory.Server();
- sslContextFactory.setKeyStorePath("src/test/resources/keystore.jks");
+ sslContextFactory.setKeyStorePath("src/test/resources/keystore.p12");
sslContextFactory.setKeyStorePassword("storepwd");
- sslContextFactory.setTrustStorePath("src/test/resources/truststore.jks");
- sslContextFactory.setTrustStorePassword("storepwd");
sslContextFactory.setCipherComparator(new HTTP2Cipher.CipherComparator());
Server server = new Server();
// HTTP(S) Configuration
- HttpConfiguration config = new HttpConfiguration();
- HttpConfiguration https_config = new HttpConfiguration(config);
- https_config.addCustomizer(new SecureRequestCustomizer());
+ HttpConfiguration httpConfig = new HttpConfiguration();
+ HttpConfiguration httpsConfig = new HttpConfiguration(httpConfig);
+ httpsConfig.addCustomizer(new SecureRequestCustomizer());
// HTTP2 factory
- HTTP2ServerConnectionFactory h2 = new HTTP2ServerConnectionFactory(https_config);
+ HTTP2ServerConnectionFactory h2 = new HTTP2ServerConnectionFactory(httpsConfig);
ALPNServerConnectionFactory alpn = new ALPNServerConnectionFactory();
alpn.setDefaultProtocol(h2.getProtocol());
@@ -66,7 +64,7 @@ public class WordPressHTTP2FastCGIProxyServer
// HTTP2 Connector
ServerConnector http2Connector =
- new ServerConnector(server, ssl, alpn, h2, new HttpConnectionFactory(https_config));
+ new ServerConnector(server, ssl, alpn, h2, new HttpConnectionFactory(httpsConfig));
http2Connector.setPort(tlsPort);
http2Connector.setIdleTimeout(15000);
server.addConnector(http2Connector);
diff --git a/jetty-fcgi/fcgi-server/src/test/resources/jetty-logging.properties b/jetty-fcgi/fcgi-server/src/test/resources/jetty-logging.properties
index b8df62d071d..4e7406f1b54 100644
--- a/jetty-fcgi/fcgi-server/src/test/resources/jetty-logging.properties
+++ b/jetty-fcgi/fcgi-server/src/test/resources/jetty-logging.properties
@@ -1,3 +1,3 @@
-org.eclipse.jetty.util.log.class=org.eclipse.jetty.util.log.StdErrLog
+# Jetty Logging using jetty-slf4j-impl
#org.eclipse.jetty.client.LEVEL=DEBUG
#org.eclipse.jetty.fcgi.LEVEL=DEBUG
diff --git a/jetty-fcgi/fcgi-server/src/test/resources/keystore.jks b/jetty-fcgi/fcgi-server/src/test/resources/keystore.jks
deleted file mode 100644
index 428ba54776e..00000000000
Binary files a/jetty-fcgi/fcgi-server/src/test/resources/keystore.jks and /dev/null differ
diff --git a/jetty-fcgi/fcgi-server/src/test/resources/keystore.p12 b/jetty-fcgi/fcgi-server/src/test/resources/keystore.p12
new file mode 100644
index 00000000000..8ab40f72afd
Binary files /dev/null and b/jetty-fcgi/fcgi-server/src/test/resources/keystore.p12 differ
diff --git a/jetty-fcgi/fcgi-server/src/test/resources/truststore.jks b/jetty-fcgi/fcgi-server/src/test/resources/truststore.jks
deleted file mode 100644
index 839cb8c3515..00000000000
Binary files a/jetty-fcgi/fcgi-server/src/test/resources/truststore.jks and /dev/null differ
diff --git a/jetty-gcloud/jetty-gcloud-session-manager/pom.xml b/jetty-gcloud/jetty-gcloud-session-manager/pom.xml
index 4e2c291d2b7..5044d383aed 100644
--- a/jetty-gcloud/jetty-gcloud-session-manager/pom.xml
+++ b/jetty-gcloud/jetty-gcloud-session-manager/pom.xml
@@ -16,6 +16,10 @@
Informational
message category as defined in the http://user@host:port/path/info;param?query#fragment
* this class will split it into the following undecoded optional elements:A HttpField that will be cached and used many times can be created as + *
An HttpField that will be cached and used many times can be created as
* a {@link PreEncodedHttpField}, which will use the {@link HttpFieldPreEncoder}
* instances discovered by the {@link ServiceLoader} to pre-encode the header
* for each version of HTTP in use. This will save garbage
@@ -38,26 +38,26 @@ import org.eclipse.jetty.util.log.Logger;
*/
public class PreEncodedHttpField extends HttpField
{
- private static final Logger LOG = Log.getLogger(PreEncodedHttpField.class);
+ private static final Logger LOG = LoggerFactory.getLogger(PreEncodedHttpField.class);
private static final HttpFieldPreEncoder[] __encoders;
static
{
List
A HTTP/2 specific handler of events for normal and tunneled exchanges.
+ */ +public interface HTTP2Channel +{ + /** + *A client specific handler for events that happen after + * a {@code HEADERS} response frame is received.
+ *{@code DATA} frames may be handled as response content + * or as opaque tunnelled data.
+ */ + public interface Client + { + public void onData(DataFrame frame, Callback callback); + + public boolean onTimeout(Throwable failure); + + public void onFailure(Throwable failure, Callback callback); + } + + /** + *A server specific handler for events that happen after + * a {@code HEADERS} request frame is received.
+ *{@code DATA} frames may be handled as request content + * or as opaque tunnelled data.
+ */ + public interface Server + { + public Runnable onData(DataFrame frame, Callback callback); + + public Runnable onTrailer(HeadersFrame frame); + + public boolean onTimeout(Throwable failure, ConsumerCreates a new stream allocating a stream id if the given HEADERS frame does not have one.
+ *The new HEADERS frame with the newly allocated stream id is returned as the first element + * of the array parameter.
+ * + * @param frameIn the HEADERS frame that triggered the stream creation + * @param frameOut an array of size 1 to return the HEADERS frame with the newly + * allocated stream id, or null if not interested in the modified headers frame + * @return a new stream + */ + public IStream newStream(HeadersFrame frameIn, HeadersFrame[] frameOut) { - return new HTTP2Stream(scheduler, this, streamId, local); + HeadersFrame frame = frameIn; + int streamId = frameIn.getStreamId(); + if (streamId <= 0) + { + streamId = localStreamIds.getAndAdd(2); + PriorityFrame priority = frameIn.getPriority(); + priority = priority == null ? null : new PriorityFrame(streamId, priority.getParentStreamId(), + priority.getWeight(), priority.isExclusive()); + frame = new HeadersFrame(streamId, frameIn.getMetaData(), priority, frameIn.isEndStream()); + } + if (frameOut != null) + frameOut[0] = frame; + return createLocalStream(streamId, (MetaData.Request)frame.getMetaData()); + } + + protected IStream newStream(int streamId, MetaData.Request request, boolean local) + { + return new HTTP2Stream(scheduler, this, streamId, request, local); } @Override @@ -622,7 +617,7 @@ public abstract class HTTP2Session extends ContainerLifeCycle implements ISessio int streamId = localStreamIds.getAndAdd(2); frame = new PushPromiseFrame(frame.getStreamId(), streamId, frame.getMetaData()); - IStream pushStream = createLocalStream(streamId); + IStream pushStream = createLocalStream(streamId, frame.getMetaData()); pushStream.setListener(listener); ControlEntry entry = new ControlEntry(frame, pushStream, new StreamPromiseCallback(promise, pushStream)); @@ -684,30 +679,42 @@ public abstract class HTTP2Session extends ContainerLifeCycle implements ISessio @Override public boolean close(int error, String reason, Callback callback) { - while (true) + if (closed.compareAndSet(CloseState.NOT_CLOSED, CloseState.LOCALLY_CLOSED)) { - CloseState current = closed.get(); - switch (current) - { - case NOT_CLOSED: - { - if (closed.compareAndSet(current, CloseState.LOCALLY_CLOSED)) - { - closeFrame = newGoAwayFrame(CloseState.LOCALLY_CLOSED, error, reason); - control(null, callback, closeFrame); - return true; - } - break; - } - default: - { - if (LOG.isDebugEnabled()) - LOG.debug("Ignoring close {}/{}, already closed", error, reason); - callback.succeeded(); - return false; - } - } + if (LOG.isDebugEnabled()) + LOG.debug("Closing {}/{}", error, reason); + closeFrame = newGoAwayFrame(CloseState.LOCALLY_CLOSED, error, reason); + control(null, callback, closeFrame); + return true; } + + if (LOG.isDebugEnabled()) + LOG.debug("Ignoring close {}/{}, already closed", error, reason); + callback.succeeded(); + return false; + } + + @Override + public CompletableFutureThe SPI interface for implementing a HTTP/2 session.
+ *The SPI interface for implementing an HTTP/2 session.
*This class extends {@link Session} by adding the methods required to * implement the HTTP/2 session functionalities.
*/ @@ -151,4 +152,14 @@ public interface ISession extends Session * @param callback the callback to notify when the frame has been processed */ public void onData(DataFrame frame, Callback callback); + + /** + *Gracefully closes the session, returning a {@code CompletableFuture} that + * is completed when all the streams currently being processed are completed.
+ *Implementation is idempotent, i.e. calling this method a second time + * or concurrently results in a no-operation.
+ * + * @return a {@code CompletableFuture} that is completed when all the streams are completed + */ + public CompletableFutureThe SPI interface for implementing a HTTP/2 stream.
+ *The SPI interface for implementing an HTTP/2 stream.
*This class extends {@link Stream} by adding the methods required to * implement the HTTP/2 stream functionalities.
*/ diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/SimpleFlowControlStrategy.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/SimpleFlowControlStrategy.java index 430a79b1fe3..d597d7e5ad3 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/SimpleFlowControlStrategy.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/SimpleFlowControlStrategy.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.http2; diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/api/Session.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/api/Session.java index 39888cd8613..5b5aa5c6ade 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/api/Session.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/api/Session.java @@ -1,23 +1,24 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.http2.api; +import java.net.InetSocketAddress; import java.util.Collection; import java.util.Map; @@ -32,7 +33,7 @@ import org.eclipse.jetty.util.Callback; import org.eclipse.jetty.util.Promise; /** - *A {@link Session} represents the client-side endpoint of a HTTP/2 connection to a single origin server.
+ *A {@link Session} represents the client-side endpoint of an HTTP/2 connection to a single origin server.
*Once a {@link Session} has been obtained, it can be used to open HTTP/2 streams:
** Session session = ...; @@ -125,9 +126,21 @@ public interface Session */ public Stream getStream(int streamId); + /** + * @return the local network address this session is bound to, + * or {@code null} if this session is not bound to a network address + */ + public InetSocketAddress getLocalAddress(); + + /** + * @return the remote network address this session is connected to, + * or {@code null} if this session is not connected to a network address + */ + public InetSocketAddress getRemoteAddress(); + /** *A {@link Listener} is the passive counterpart of a {@link Session} and - * receives events happening on a HTTP/2 connection.
+ * receives events happening on an HTTP/2 connection. * * @see Session */ @@ -151,9 +164,9 @@ public interface Session /** *Callback method invoked when a new stream is being created upon - * receiving a HEADERS frame representing a HTTP request.
+ * receiving a HEADERS frame representing an HTTP request. *Applications should implement this method to process HTTP requests, - * typically providing a HTTP response via + * typically providing an HTTP response via * {@link Stream#headers(HeadersFrame, Callback)}.
*Applications can detect whether request DATA frames will be arriving * by testing {@link HeadersFrame#isEndStream()}. If the application is diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/api/Stream.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/api/Stream.java index 6f02b828825..cfba9e089e9 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/api/Stream.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/api/Stream.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.http2.api; @@ -29,8 +29,8 @@ import org.eclipse.jetty.util.Promise; *
A {@link Stream} represents a bidirectional exchange of data on top of a {@link Session}.
*Differently from socket streams, where the input and output streams are permanently associated * with the socket (and hence with the connection that the socket represents), there can be multiple - * HTTP/2 streams present concurrent for a HTTP/2 session.
- *A {@link Stream} maps to a HTTP request/response cycle, and after the request/response cycle is + * HTTP/2 streams present concurrently for an HTTP/2 session.
+ *A {@link Stream} maps to an HTTP request/response cycle, and after the request/response cycle is * completed, the stream is closed and removed from the session.
*Like {@link Session}, {@link Stream} is the active part and by calling its API applications * can generate events on the stream; conversely, {@link Stream.Listener} is the passive part, and @@ -51,7 +51,7 @@ public interface Stream public Session getSession(); /** - *
Sends the given HEADERS {@code frame} representing a HTTP response.
+ *Sends the given HEADERS {@code frame} representing an HTTP response.
* * @param frame the HEADERS frame to send * @param callback the callback that gets notified when the frame has been sent @@ -129,14 +129,40 @@ public interface Stream */ public void setIdleTimeout(long idleTimeout); + /** + *Demands {@code n} more {@code DATA} frames for this stream.
+ * + * @param n the increment of the demand, must be greater than zero + * @see Listener#onDataDemanded(Stream, DataFrame, Callback) + */ + public void demand(long n); + /** *A {@link Stream.Listener} is the passive counterpart of a {@link Stream} and receives - * events happening on a HTTP/2 stream.
+ * events happening on an HTTP/2 stream. + *HTTP/2 data is flow controlled - this means that only a finite number of data events + * are delivered, until the flow control window is exhausted.
+ *Applications control the delivery of data events by requesting them via + * {@link Stream#demand(long)}; the first event is always delivered, while subsequent + * events must be explicitly demanded.
+ *Applications control the HTTP/2 flow control by completing the callback associated + * with data events - this allows the implementation to recycle the data buffer and + * eventually to enlarge the flow control window so that the sender can send more data.
* * @see Stream */ public interface Listener { + /** + *Callback method invoked when a stream is created locally by + * {@link Session#newStream(HeadersFrame, Promise, Listener)}.
+ * + * @param stream the newly created stream + */ + public default void onNewStream(Stream stream) + { + } + /** *Callback method invoked when a HEADERS frame representing the HTTP response has been received.
* @@ -154,15 +180,42 @@ public interface Stream */ public Listener onPush(Stream stream, PushPromiseFrame frame); + /** + *Callback method invoked before notifying the first DATA frame.
+ *The default implementation initializes the demand for DATA frames.
+ * + * @param stream the stream + */ + public default void onBeforeData(Stream stream) + { + stream.demand(1); + } + /** *Callback method invoked when a DATA frame has been received.
* * @param stream the stream * @param frame the DATA frame received * @param callback the callback to complete when the bytes of the DATA frame have been consumed + * @see #onDataDemanded(Stream, DataFrame, Callback) */ public void onData(Stream stream, DataFrame frame, Callback callback); + /** + *Callback method invoked when a DATA frame has been demanded.
+ *Implementations of this method must arrange to call (within the + * method or otherwise asynchronously) {@link #demand(long)}.
+ * + * @param stream the stream + * @param frame the DATA frame received + * @param callback the callback to complete when the bytes of the DATA frame have been consumed + */ + public default void onDataDemanded(Stream stream, DataFrame frame, Callback callback) + { + onData(stream, frame, callback); + stream.demand(1); + } + /** *Callback method invoked when a RST_STREAM frame has been received for this stream.
* diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/api/server/ServerSessionListener.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/api/server/ServerSessionListener.java index d11e3251d0a..d02174f1a08 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/api/server/ServerSessionListener.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/api/server/ServerSessionListener.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.http2.api.server; diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/ContinuationFrame.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/ContinuationFrame.java new file mode 100644 index 00000000000..fda0ad84a65 --- /dev/null +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/ContinuationFrame.java @@ -0,0 +1,48 @@ +// +// ======================================================================== +// 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.http2.frames; + +public class ContinuationFrame extends Frame +{ + private final int streamId; + private final boolean endHeaders; + + public ContinuationFrame(int streamId, boolean endHeaders) + { + super(FrameType.CONTINUATION); + this.streamId = streamId; + this.endHeaders = endHeaders; + } + + public int getStreamId() + { + return streamId; + } + + public boolean isEndHeaders() + { + return endHeaders; + } + + @Override + public String toString() + { + return String.format("%s#%d{end=%b}", super.toString(), getStreamId(), isEndHeaders()); + } +} diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/DataFrame.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/DataFrame.java index 5f0c95b62b5..c44b3bc74be 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/DataFrame.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/DataFrame.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.http2.frames; diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/DisconnectFrame.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/DisconnectFrame.java index b2a590f9d5b..8531d4c1735 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/DisconnectFrame.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/DisconnectFrame.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.http2.frames; diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/FailureFrame.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/FailureFrame.java index 17b913c05f4..1f889a50069 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/FailureFrame.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/FailureFrame.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.http2.frames; diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/Frame.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/Frame.java index bca3f38a9bd..26c2e47921c 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/Frame.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/Frame.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.http2.frames; diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/FrameType.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/FrameType.java index 3ab19fec249..6af30bf6c5a 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/FrameType.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/FrameType.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.http2.frames; diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/GoAwayFrame.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/GoAwayFrame.java index 64b855f2d2e..1b006eef4c3 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/GoAwayFrame.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/GoAwayFrame.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.http2.frames; diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/HeadersFrame.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/HeadersFrame.java index d3868f7c782..c72b4933628 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/HeadersFrame.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/HeadersFrame.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.http2.frames; diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/PingFrame.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/PingFrame.java index 450b0aa5434..91f4b1e0b18 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/PingFrame.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/PingFrame.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.http2.frames; diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/PrefaceFrame.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/PrefaceFrame.java index e1aff2b723c..7bb022de790 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/PrefaceFrame.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/PrefaceFrame.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.http2.frames; diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/PriorityFrame.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/PriorityFrame.java index b2bd59a491a..a7fad1a5129 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/PriorityFrame.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/PriorityFrame.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.http2.frames; diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/PushPromiseFrame.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/PushPromiseFrame.java index b6a0d9faf4a..4d7d9f2e6cd 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/PushPromiseFrame.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/PushPromiseFrame.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.http2.frames; @@ -24,9 +24,9 @@ public class PushPromiseFrame extends Frame { private final int streamId; private final int promisedStreamId; - private final MetaData metaData; + private final MetaData.Request metaData; - public PushPromiseFrame(int streamId, int promisedStreamId, MetaData metaData) + public PushPromiseFrame(int streamId, int promisedStreamId, MetaData.Request metaData) { super(FrameType.PUSH_PROMISE); this.streamId = streamId; @@ -44,7 +44,7 @@ public class PushPromiseFrame extends Frame return promisedStreamId; } - public MetaData getMetaData() + public MetaData.Request getMetaData() { return metaData; } diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/ResetFrame.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/ResetFrame.java index 672c030883b..d8d2c6d2fbb 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/ResetFrame.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/ResetFrame.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.http2.frames; diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/SettingsFrame.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/SettingsFrame.java index c4f78e1371a..dc5c10c38d0 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/SettingsFrame.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/SettingsFrame.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.http2.frames; @@ -30,6 +30,7 @@ public class SettingsFrame extends Frame public static final int INITIAL_WINDOW_SIZE = 4; public static final int MAX_FRAME_SIZE = 5; public static final int MAX_HEADER_LIST_SIZE = 6; + public static final int ENABLE_CONNECT_PROTOCOL = 8; private final Mapsettings; private final boolean reply; @@ -54,6 +55,6 @@ public class SettingsFrame extends Frame @Override public String toString() { - return String.format("%s,reply=%b:%s", super.toString(), reply, settings); + return String.format("%s,reply=%b,params=%s", super.toString(), reply, settings); } } diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/UnknownFrame.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/UnknownFrame.java new file mode 100644 index 00000000000..a4affaa7127 --- /dev/null +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/UnknownFrame.java @@ -0,0 +1,36 @@ +// +// ======================================================================== +// 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.http2.frames; + +public class UnknownFrame extends Frame +{ + private final int frameType; + + public UnknownFrame(int frameType) + { + super(null); + this.frameType = frameType; + } + + @Override + public String toString() + { + return String.format("%s,t=%d", super.toString(), frameType); + } +} diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/WindowUpdateFrame.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/WindowUpdateFrame.java index 0ad323d3afe..da9abf7c026 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/WindowUpdateFrame.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/WindowUpdateFrame.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.http2.frames; diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/generator/DataGenerator.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/generator/DataGenerator.java index 284f41fb517..d5139e73753 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/generator/DataGenerator.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/generator/DataGenerator.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.http2.generator; diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/generator/DisconnectGenerator.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/generator/DisconnectGenerator.java index 7085f71d786..db374b78125 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/generator/DisconnectGenerator.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/generator/DisconnectGenerator.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.http2.generator; diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/generator/FrameGenerator.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/generator/FrameGenerator.java index 0194beccc27..2b3aa464a73 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/generator/FrameGenerator.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/generator/FrameGenerator.java @@ -1,27 +1,30 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.http2.generator; import java.nio.ByteBuffer; +import org.eclipse.jetty.http.MetaData; import org.eclipse.jetty.http2.frames.Frame; import org.eclipse.jetty.http2.frames.FrameType; +import org.eclipse.jetty.http2.hpack.HpackEncoder; +import org.eclipse.jetty.http2.hpack.HpackException; import org.eclipse.jetty.io.ByteBufferPool; public abstract class FrameGenerator @@ -33,7 +36,7 @@ public abstract class FrameGenerator this.headerGenerator = headerGenerator; } - public abstract int generate(ByteBufferPool.Lease lease, Frame frame); + public abstract int generate(ByteBufferPool.Lease lease, Frame frame) throws HpackException; protected ByteBuffer generateHeader(ByteBufferPool.Lease lease, FrameType frameType, int length, int flags, int streamId) { @@ -44,4 +47,24 @@ public abstract class FrameGenerator { return headerGenerator.getMaxFrameSize(); } + + public boolean isUseDirectByteBuffers() + { + return headerGenerator.isUseDirectByteBuffers(); + } + + protected ByteBuffer encode(HpackEncoder encoder, ByteBufferPool.Lease lease, MetaData metaData, int maxFrameSize) throws HpackException + { + ByteBuffer hpacked = lease.acquire(maxFrameSize, isUseDirectByteBuffers()); + try + { + encoder.encode(hpacked, metaData); + return hpacked; + } + catch (HpackException x) + { + lease.release(hpacked); + throw x; + } + } } diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/generator/Generator.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/generator/Generator.java index b7288d3897a..61daf3056ea 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/generator/Generator.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/generator/Generator.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.http2.generator; @@ -22,6 +22,7 @@ import org.eclipse.jetty.http2.frames.DataFrame; import org.eclipse.jetty.http2.frames.Frame; import org.eclipse.jetty.http2.frames.FrameType; import org.eclipse.jetty.http2.hpack.HpackEncoder; +import org.eclipse.jetty.http2.hpack.HpackException; import org.eclipse.jetty.io.ByteBufferPool; public class Generator @@ -38,10 +39,15 @@ public class Generator } public Generator(ByteBufferPool byteBufferPool, int maxDynamicTableSize, int maxHeaderBlockFragment) + { + this(byteBufferPool, true, maxDynamicTableSize, maxHeaderBlockFragment); + } + + public Generator(ByteBufferPool byteBufferPool, boolean useDirectByteBuffers, int maxDynamicTableSize, int maxHeaderBlockFragment) { this.byteBufferPool = byteBufferPool; - headerGenerator = new HeaderGenerator(); + headerGenerator = new HeaderGenerator(useDirectByteBuffers); hpackEncoder = new HpackEncoder(maxDynamicTableSize); this.generators = new FrameGenerator[FrameType.values().length]; @@ -65,6 +71,11 @@ public class Generator return byteBufferPool; } + public void setValidateHpackEncoding(boolean validateEncoding) + { + hpackEncoder.setValidateEncoding(validateEncoding); + } + public void setHeaderTableSize(int headerTableSize) { hpackEncoder.setRemoteMaxDynamicTableSize(headerTableSize); @@ -75,7 +86,7 @@ public class Generator headerGenerator.setMaxFrameSize(maxFrameSize); } - public int control(ByteBufferPool.Lease lease, Frame frame) + public int control(ByteBufferPool.Lease lease, Frame frame) throws HpackException { return generators[frame.getType().getType()].generate(lease, frame); } diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/generator/GoAwayGenerator.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/generator/GoAwayGenerator.java index 1e04094fc0b..2775033c268 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/generator/GoAwayGenerator.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/generator/GoAwayGenerator.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.http2.generator; diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/generator/HeaderGenerator.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/generator/HeaderGenerator.java index 33283a72389..debd94f64f8 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/generator/HeaderGenerator.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/generator/HeaderGenerator.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.http2.generator; @@ -27,10 +27,26 @@ import org.eclipse.jetty.io.ByteBufferPool; public class HeaderGenerator { private int maxFrameSize = Frame.DEFAULT_MAX_LENGTH; + private final boolean useDirectByteBuffers; + + public HeaderGenerator() + { + this(true); + } + + public HeaderGenerator(boolean useDirectByteBuffers) + { + this.useDirectByteBuffers = useDirectByteBuffers; + } + + public boolean isUseDirectByteBuffers() + { + return useDirectByteBuffers; + } public ByteBuffer generate(ByteBufferPool.Lease lease, FrameType frameType, int capacity, int length, int flags, int streamId) { - ByteBuffer header = lease.acquire(capacity, true); + ByteBuffer header = lease.acquire(capacity, isUseDirectByteBuffers()); header.put((byte)((length & 0x00_FF_00_00) >>> 16)); header.put((byte)((length & 0x00_00_FF_00) >>> 8)); header.put((byte)((length & 0x00_00_00_FF))); diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/generator/HeadersGenerator.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/generator/HeadersGenerator.java index 4ff03bd28e5..93ac1db9916 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/generator/HeadersGenerator.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/generator/HeadersGenerator.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.http2.generator; @@ -27,6 +27,7 @@ import org.eclipse.jetty.http2.frames.FrameType; import org.eclipse.jetty.http2.frames.HeadersFrame; import org.eclipse.jetty.http2.frames.PriorityFrame; import org.eclipse.jetty.http2.hpack.HpackEncoder; +import org.eclipse.jetty.http2.hpack.HpackException; import org.eclipse.jetty.io.ByteBufferPool; import org.eclipse.jetty.util.BufferUtil; @@ -50,13 +51,13 @@ public class HeadersGenerator extends FrameGenerator } @Override - public int generate(ByteBufferPool.Lease lease, Frame frame) + public int generate(ByteBufferPool.Lease lease, Frame frame) throws HpackException { HeadersFrame headersFrame = (HeadersFrame)frame; return generateHeaders(lease, headersFrame.getStreamId(), headersFrame.getMetaData(), headersFrame.getPriority(), headersFrame.isEndStream()); } - public int generateHeaders(ByteBufferPool.Lease lease, int streamId, MetaData metaData, PriorityFrame priority, boolean endStream) + public int generateHeaders(ByteBufferPool.Lease lease, int streamId, MetaData metaData, PriorityFrame priority, boolean endStream) throws HpackException { if (streamId < 0) throw new IllegalArgumentException("Invalid stream id: " + streamId); @@ -66,10 +67,7 @@ public class HeadersGenerator extends FrameGenerator if (priority != null) flags = Flags.PRIORITY; - int maxFrameSize = getMaxFrameSize(); - ByteBuffer hpacked = lease.acquire(maxFrameSize, false); - BufferUtil.clearToFill(hpacked); - encoder.encode(hpacked, metaData); + ByteBuffer hpacked = encode(encoder, lease, metaData, getMaxFrameSize()); int hpackedLength = hpacked.position(); BufferUtil.flipToFlush(hpacked, 0); diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/generator/PingGenerator.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/generator/PingGenerator.java index 99ac42b47a6..a681f107f7b 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/generator/PingGenerator.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/generator/PingGenerator.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.http2.generator; diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/generator/PrefaceGenerator.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/generator/PrefaceGenerator.java index 76cf4694bbc..20b721bb365 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/generator/PrefaceGenerator.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/generator/PrefaceGenerator.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.http2.generator; diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/generator/PriorityGenerator.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/generator/PriorityGenerator.java index 9b72800d562..95dd1a37ff0 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/generator/PriorityGenerator.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/generator/PriorityGenerator.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.http2.generator; diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/generator/PushPromiseGenerator.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/generator/PushPromiseGenerator.java index d4fe2640ef9..c6906ad9ee3 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/generator/PushPromiseGenerator.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/generator/PushPromiseGenerator.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.http2.generator; @@ -26,6 +26,7 @@ import org.eclipse.jetty.http2.frames.Frame; import org.eclipse.jetty.http2.frames.FrameType; import org.eclipse.jetty.http2.frames.PushPromiseFrame; import org.eclipse.jetty.http2.hpack.HpackEncoder; +import org.eclipse.jetty.http2.hpack.HpackException; import org.eclipse.jetty.io.ByteBufferPool; import org.eclipse.jetty.util.BufferUtil; @@ -40,13 +41,13 @@ public class PushPromiseGenerator extends FrameGenerator } @Override - public int generate(ByteBufferPool.Lease lease, Frame frame) + public int generate(ByteBufferPool.Lease lease, Frame frame) throws HpackException { PushPromiseFrame pushPromiseFrame = (PushPromiseFrame)frame; return generatePushPromise(lease, pushPromiseFrame.getStreamId(), pushPromiseFrame.getPromisedStreamId(), pushPromiseFrame.getMetaData()); } - public int generatePushPromise(ByteBufferPool.Lease lease, int streamId, int promisedStreamId, MetaData metaData) + public int generatePushPromise(ByteBufferPool.Lease lease, int streamId, int promisedStreamId, MetaData metaData) throws HpackException { if (streamId < 0) throw new IllegalArgumentException("Invalid stream id: " + streamId); @@ -58,9 +59,7 @@ public class PushPromiseGenerator extends FrameGenerator int extraSpace = 4; maxFrameSize -= extraSpace; - ByteBuffer hpacked = lease.acquire(maxFrameSize, false); - BufferUtil.clearToFill(hpacked); - encoder.encode(hpacked, metaData); + ByteBuffer hpacked = encode(encoder, lease, metaData, maxFrameSize); int hpackedLength = hpacked.position(); BufferUtil.flipToFlush(hpacked, 0); diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/generator/ResetGenerator.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/generator/ResetGenerator.java index 2a0533a8f08..e85d6d9174b 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/generator/ResetGenerator.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/generator/ResetGenerator.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.http2.generator; diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/generator/SettingsGenerator.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/generator/SettingsGenerator.java index dcb9831ff14..aae1e95a413 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/generator/SettingsGenerator.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/generator/SettingsGenerator.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.http2.generator; diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/generator/WindowUpdateGenerator.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/generator/WindowUpdateGenerator.java index cd7a265caf8..8a9bc8f8a47 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/generator/WindowUpdateGenerator.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/generator/WindowUpdateGenerator.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.http2.generator; diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/BodyParser.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/BodyParser.java index 82d18f96a84..2c06fd20e90 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/BodyParser.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/BodyParser.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.http2.parser; @@ -32,8 +32,8 @@ import org.eclipse.jetty.http2.frames.ResetFrame; import org.eclipse.jetty.http2.frames.SettingsFrame; import org.eclipse.jetty.http2.frames.WindowUpdateFrame; import org.eclipse.jetty.util.BufferUtil; -import org.eclipse.jetty.util.log.Log; -import org.eclipse.jetty.util.log.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * The base parser for the frame body of HTTP/2 frames.
@@ -44,7 +44,7 @@ import org.eclipse.jetty.util.log.Logger; */ public abstract class BodyParser { - protected static final Logger LOG = Log.getLogger(BodyParser.class); + protected static final Logger LOG = LoggerFactory.getLogger(BodyParser.class); private final HeaderParser headerParser; private final Parser.Listener listener; @@ -96,6 +96,11 @@ public abstract class BodyParser return headerParser.getLength(); } + protected int getFrameType() + { + return headerParser.getFrameType(); + } + protected void notifyData(DataFrame frame) { try @@ -223,9 +228,10 @@ public abstract class BodyParser } } - protected void streamFailure(int streamId, int error, String reason) + protected boolean streamFailure(int streamId, int error, String reason) { notifyStreamFailure(streamId, error, reason); + return false; } private void notifyStreamFailure(int streamId, int error, String reason) @@ -239,4 +245,9 @@ public abstract class BodyParser LOG.info("Failure while notifying listener " + listener, x); } } + + protected boolean rateControlOnEvent(Object o) + { + return headerParser.getRateControl().onEvent(o); + } } diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/ContinuationBodyParser.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/ContinuationBodyParser.java index 65e47d1c827..f19e7272fe9 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/ContinuationBodyParser.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/ContinuationBodyParser.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.http2.parser; @@ -23,6 +23,7 @@ import java.nio.ByteBuffer; import org.eclipse.jetty.http.MetaData; import org.eclipse.jetty.http2.ErrorCode; import org.eclipse.jetty.http2.Flags; +import org.eclipse.jetty.http2.frames.ContinuationFrame; import org.eclipse.jetty.http2.frames.HeadersFrame; public class ContinuationBodyParser extends BodyParser @@ -43,7 +44,15 @@ public class ContinuationBodyParser extends BodyParser protected void emptyBody(ByteBuffer buffer) { if (hasFlag(Flags.END_HEADERS)) - onHeaders(); + { + onHeaders(buffer); + } + else + { + ContinuationFrame frame = new ContinuationFrame(getStreamId(), hasFlag(Flags.END_HEADERS)); + if (!rateControlOnEvent(frame)) + connectionFailure(buffer, ErrorCode.ENHANCE_YOUR_CALM_ERROR.code, "invalid_continuation_frame_rate"); + } } @Override @@ -81,7 +90,7 @@ public class ContinuationBodyParser extends BodyParser headerBlockFragments.storeFragment(buffer, length, last); reset(); if (last) - return onHeaders(); + return onHeaders(buffer); return true; } } @@ -94,15 +103,21 @@ public class ContinuationBodyParser extends BodyParser return false; } - private boolean onHeaders() + private boolean onHeaders(ByteBuffer buffer) { ByteBuffer headerBlock = headerBlockFragments.complete(); MetaData metaData = headerBlockParser.parse(headerBlock, headerBlock.remaining()); + headerBlockFragments.getByteBufferPool().release(headerBlock); + if (metaData == null) + return true; if (metaData == HeaderBlockParser.SESSION_FAILURE) return false; - if (metaData == null || metaData == HeaderBlockParser.STREAM_FAILURE) - return true; HeadersFrame frame = new HeadersFrame(getStreamId(), metaData, headerBlockFragments.getPriorityFrame(), headerBlockFragments.isEndStream()); + if (metaData == HeaderBlockParser.STREAM_FAILURE) + { + if (!rateControlOnEvent(frame)) + return connectionFailure(buffer, ErrorCode.ENHANCE_YOUR_CALM_ERROR.code, "invalid_continuation_frame_rate"); + } notifyHeaders(frame); return true; } diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/DataBodyParser.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/DataBodyParser.java index ac9e7bab991..b46a320a284 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/DataBodyParser.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/DataBodyParser.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.http2.parser; @@ -48,9 +48,17 @@ public class DataBodyParser extends BodyParser protected void emptyBody(ByteBuffer buffer) { if (isPadding()) + { connectionFailure(buffer, ErrorCode.PROTOCOL_ERROR.code, "invalid_data_frame"); + } else - onData(BufferUtil.EMPTY_BUFFER, false, 0); + { + DataFrame frame = new DataFrame(getStreamId(), BufferUtil.EMPTY_BUFFER, isEndStream()); + if (!isEndStream() && !rateControlOnEvent(frame)) + connectionFailure(buffer, ErrorCode.ENHANCE_YOUR_CALM_ERROR.code, "invalid_data_frame_rate"); + else + onData(frame); + } } @Override @@ -134,7 +142,11 @@ public class DataBodyParser extends BodyParser private void onData(ByteBuffer buffer, boolean fragment, int padding) { - DataFrame frame = new DataFrame(getStreamId(), buffer, !fragment && isEndStream(), padding); + onData(new DataFrame(getStreamId(), buffer, !fragment && isEndStream(), padding)); + } + + private void onData(DataFrame frame) + { notifyData(frame); } diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/GoAwayBodyParser.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/GoAwayBodyParser.java index b84e229fc11..31d9591adfd 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/GoAwayBodyParser.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/GoAwayBodyParser.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.http2.parser; diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/HeaderBlockFragments.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/HeaderBlockFragments.java index 71ca1b3814d..7011bd7d9e1 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/HeaderBlockFragments.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/HeaderBlockFragments.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.http2.parser; @@ -21,20 +21,33 @@ package org.eclipse.jetty.http2.parser; import java.nio.ByteBuffer; import org.eclipse.jetty.http2.frames.PriorityFrame; +import org.eclipse.jetty.io.ByteBufferPool; public class HeaderBlockFragments { + private final ByteBufferPool byteBufferPool; private PriorityFrame priorityFrame; private boolean endStream; private int streamId; private ByteBuffer storage; + public HeaderBlockFragments(ByteBufferPool byteBufferPool) + { + this.byteBufferPool = byteBufferPool; + } + + public ByteBufferPool getByteBufferPool() + { + return byteBufferPool; + } + public void storeFragment(ByteBuffer fragment, int length, boolean last) { if (storage == null) { int space = last ? length : length * 2; - storage = ByteBuffer.allocate(space); + storage = byteBufferPool.acquire(space, fragment.isDirect()); + storage.clear(); } // Grow the storage if necessary. @@ -42,9 +55,11 @@ public class HeaderBlockFragments { int space = last ? length : length * 2; int capacity = storage.position() + space; - ByteBuffer newStorage = ByteBuffer.allocate(capacity); + ByteBuffer newStorage = byteBufferPool.acquire(capacity, storage.isDirect()); + newStorage.clear(); storage.flip(); newStorage.put(storage); + byteBufferPool.release(storage); storage = newStorage; } diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/HeaderBlockParser.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/HeaderBlockParser.java index 54e4661da67..11a922a81ce 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/HeaderBlockParser.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/HeaderBlockParser.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.http2.parser; @@ -27,14 +27,14 @@ import org.eclipse.jetty.http2.hpack.HpackDecoder; import org.eclipse.jetty.http2.hpack.HpackException; import org.eclipse.jetty.io.ByteBufferPool; import org.eclipse.jetty.util.BufferUtil; -import org.eclipse.jetty.util.log.Log; -import org.eclipse.jetty.util.log.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class HeaderBlockParser { public static final MetaData STREAM_FAILURE = new MetaData(HttpVersion.HTTP_2, null); public static final MetaData SESSION_FAILURE = new MetaData(HttpVersion.HTTP_2, null); - private static final Logger LOG = Log.getLogger(HeaderBlockParser.class); + private static final Logger LOG = LoggerFactory.getLogger(HeaderBlockParser.class); private final HeaderParser headerParser; private final ByteBufferPool byteBufferPool; @@ -73,7 +73,7 @@ public class HeaderBlockParser { if (blockBuffer == null) { - blockBuffer = byteBufferPool.acquire(blockLength, false); + blockBuffer = byteBufferPool.acquire(blockLength, buffer.isDirect()); BufferUtil.clearToFill(blockBuffer); } blockBuffer.put(buffer); @@ -102,21 +102,21 @@ public class HeaderBlockParser catch (HpackException.StreamException x) { if (LOG.isDebugEnabled()) - LOG.debug(x); + LOG.debug("Stream error, stream={}", headerParser.getStreamId(), x); notifier.streamFailure(headerParser.getStreamId(), ErrorCode.PROTOCOL_ERROR.code, "invalid_hpack_block"); return STREAM_FAILURE; } catch (HpackException.CompressionException x) { if (LOG.isDebugEnabled()) - LOG.debug(x); + LOG.debug("Compression error, buffer={}", BufferUtil.toDetailString(buffer), x); notifier.connectionFailure(buffer, ErrorCode.COMPRESSION_ERROR.code, "invalid_hpack_block"); return SESSION_FAILURE; } catch (HpackException.SessionException x) { if (LOG.isDebugEnabled()) - LOG.debug(x); + LOG.debug("Session error, buffer={}", BufferUtil.toDetailString(buffer), x); notifier.connectionFailure(buffer, ErrorCode.PROTOCOL_ERROR.code, "invalid_hpack_block"); return SESSION_FAILURE; } diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/HeaderParser.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/HeaderParser.java index 0e4d2dc5e9e..e24802f29f0 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/HeaderParser.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/HeaderParser.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.http2.parser; @@ -30,14 +30,24 @@ import org.eclipse.jetty.http2.frames.FrameType; */ public class HeaderParser { + private final RateControl rateControl; private State state = State.LENGTH; private int cursor; - private int length; private int type; private int flags; private int streamId; + public HeaderParser(RateControl rateControl) + { + this.rateControl = rateControl; + } + + public RateControl getRateControl() + { + return rateControl; + } + protected void reset() { state = State.LENGTH; diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/HeadersBodyParser.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/HeadersBodyParser.java index febdefb6c25..3d15959c28c 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/HeadersBodyParser.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/HeadersBodyParser.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.http2.parser; @@ -61,17 +61,23 @@ public class HeadersBodyParser extends BodyParser @Override protected void emptyBody(ByteBuffer buffer) { - if (hasFlag(Flags.END_HEADERS)) + if (hasFlag(Flags.PRIORITY)) + { + connectionFailure(buffer, ErrorCode.PROTOCOL_ERROR.code, "invalid_headers_priority_frame"); + } + else if (hasFlag(Flags.END_HEADERS)) { MetaData metaData = headerBlockParser.parse(BufferUtil.EMPTY_BUFFER, 0); - onHeaders(0, 0, false, metaData); + HeadersFrame frame = new HeadersFrame(getStreamId(), metaData, null, isEndStream()); + if (!rateControlOnEvent(frame)) + connectionFailure(buffer, ErrorCode.ENHANCE_YOUR_CALM_ERROR.code, "invalid_headers_frame_rate"); + else + onHeaders(frame); } else { headerBlockFragments.setStreamId(getStreamId()); headerBlockFragments.setEndStream(isEndStream()); - if (hasFlag(Flags.PRIORITY)) - connectionFailure(buffer, ErrorCode.PROTOCOL_ERROR.code, "invalid_headers_priority_frame"); } } @@ -179,7 +185,15 @@ public class HeadersBodyParser extends BodyParser state = State.PADDING; loop = paddingLength == 0; if (metaData != HeaderBlockParser.STREAM_FAILURE) + { onHeaders(parentStreamId, weight, exclusive, metaData); + } + else + { + HeadersFrame frame = new HeadersFrame(getStreamId(), metaData, null, isEndStream()); + if (!rateControlOnEvent(frame)) + connectionFailure(buffer, ErrorCode.ENHANCE_YOUR_CALM_ERROR.code, "invalid_headers_frame_rate"); + } } } else @@ -230,6 +244,11 @@ public class HeadersBodyParser extends BodyParser if (hasFlag(Flags.PRIORITY)) priorityFrame = new PriorityFrame(getStreamId(), parentStreamId, weight, exclusive); HeadersFrame frame = new HeadersFrame(getStreamId(), metaData, priorityFrame, isEndStream()); + onHeaders(frame); + } + + private void onHeaders(HeadersFrame frame) + { notifyHeaders(frame); } diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/Parser.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/Parser.java index 6ac14471695..5997c00d199 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/Parser.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/Parser.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.http2.parser; @@ -36,8 +36,8 @@ import org.eclipse.jetty.http2.frames.SettingsFrame; import org.eclipse.jetty.http2.frames.WindowUpdateFrame; import org.eclipse.jetty.http2.hpack.HpackDecoder; import org.eclipse.jetty.io.ByteBufferPool; -import org.eclipse.jetty.util.log.Log; -import org.eclipse.jetty.util.log.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** *The HTTP/2 protocol parser.
@@ -46,7 +46,7 @@ import org.eclipse.jetty.util.log.Logger; */ public class Parser { - private static final Logger LOG = Log.getLogger(Parser.class); + private static final Logger LOG = LoggerFactory.getLogger(Parser.class); private final ByteBufferPool byteBufferPool; private final Listener listener; @@ -54,18 +54,22 @@ public class Parser private final HpackDecoder hpackDecoder; private final BodyParser[] bodyParsers; private UnknownBodyParser unknownBodyParser; - private int maxFrameLength; + private int maxFrameLength = Frame.DEFAULT_MAX_LENGTH; private int maxSettingsKeys = SettingsFrame.DEFAULT_MAX_KEYS; private boolean continuation; private State state = State.HEADER; public Parser(ByteBufferPool byteBufferPool, Listener listener, int maxDynamicTableSize, int maxHeaderSize) + { + this(byteBufferPool, listener, maxDynamicTableSize, maxHeaderSize, RateControl.NO_RATE_CONTROL); + } + + public Parser(ByteBufferPool byteBufferPool, Listener listener, int maxDynamicTableSize, int maxHeaderSize, RateControl rateControl) { this.byteBufferPool = byteBufferPool; this.listener = listener; - this.headerParser = new HeaderParser(); + this.headerParser = new HeaderParser(rateControl == null ? RateControl.NO_RATE_CONTROL : rateControl); this.hpackDecoder = new HpackDecoder(maxDynamicTableSize, maxHeaderSize); - this.maxFrameLength = Frame.DEFAULT_MAX_LENGTH; this.bodyParsers = new BodyParser[FrameType.values().length]; } @@ -74,7 +78,7 @@ public class Parser Listener listener = wrapper.apply(this.listener); unknownBodyParser = new UnknownBodyParser(headerParser, listener); HeaderBlockParser headerBlockParser = new HeaderBlockParser(headerParser, byteBufferPool, hpackDecoder, unknownBodyParser); - HeaderBlockFragments headerBlockFragments = new HeaderBlockFragments(); + HeaderBlockFragments headerBlockFragments = new HeaderBlockFragments(byteBufferPool); bodyParsers[FrameType.DATA.getType()] = new DataBodyParser(headerParser, listener); bodyParsers[FrameType.HEADERS.getType()] = new HeadersBodyParser(headerParser, listener, headerBlockParser, headerBlockFragments); bodyParsers[FrameType.PRIORITY.getType()] = new PriorityBodyParser(headerParser, listener); @@ -134,7 +138,7 @@ public class Parser catch (Throwable x) { if (LOG.isDebugEnabled()) - LOG.debug(x); + LOG.debug("Parse failed", x); connectionFailure(buffer, ErrorCode.PROTOCOL_ERROR, "parser_error"); } } diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/PingBodyParser.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/PingBodyParser.java index 8cee350e91e..ff6014f4426 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/PingBodyParser.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/PingBodyParser.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.http2.parser; @@ -66,7 +66,7 @@ public class PingBodyParser extends BodyParser if (buffer.remaining() >= 8) { buffer.get(payload); - return onPing(payload); + return onPing(buffer, payload); } else { @@ -80,7 +80,7 @@ public class PingBodyParser extends BodyParser payload[8 - cursor] = buffer.get(); --cursor; if (cursor == 0) - return onPing(payload); + return onPing(buffer, payload); break; } default: @@ -92,9 +92,11 @@ public class PingBodyParser extends BodyParser return false; } - private boolean onPing(byte[] payload) + private boolean onPing(ByteBuffer buffer, byte[] payload) { PingFrame frame = new PingFrame(payload, hasFlag(Flags.ACK)); + if (!rateControlOnEvent(frame)) + return connectionFailure(buffer, ErrorCode.ENHANCE_YOUR_CALM_ERROR.code, "invalid_ping_frame_rate"); reset(); notifyPing(frame); return true; diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/PrefaceParser.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/PrefaceParser.java index 3a6058878a4..0dc6a052d3d 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/PrefaceParser.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/PrefaceParser.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.http2.parser; @@ -23,12 +23,12 @@ import java.nio.ByteBuffer; import org.eclipse.jetty.http2.ErrorCode; import org.eclipse.jetty.http2.frames.PrefaceFrame; import org.eclipse.jetty.util.BufferUtil; -import org.eclipse.jetty.util.log.Log; -import org.eclipse.jetty.util.log.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class PrefaceParser { - private static final Logger LOG = Log.getLogger(PrefaceParser.class); + private static final Logger LOG = LoggerFactory.getLogger(PrefaceParser.class); private final Parser.Listener listener; private int cursor; @@ -42,7 +42,7 @@ public class PrefaceParser *Advances this parser after the {@link PrefaceFrame#PREFACE_PREAMBLE_BYTES}.
*This allows the HTTP/1.1 parser to parse the preamble of the preface, * which is a legal HTTP/1.1 request, and this parser will parse the remaining - * bytes, that are not parseable by a HTTP/1.1 parser.
+ * bytes, that are not parseable by an HTTP/1.1 parser. */ protected void directUpgrade() { diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/PriorityBodyParser.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/PriorityBodyParser.java index a9d11398987..d9e4fdcef69 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/PriorityBodyParser.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/PriorityBodyParser.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.http2.parser; @@ -103,7 +103,7 @@ public class PriorityBodyParser extends BodyParser if (getStreamId() == parentStreamId) return connectionFailure(buffer, ErrorCode.PROTOCOL_ERROR.code, "invalid_priority_frame"); int weight = (buffer.get() & 0xFF) + 1; - return onPriority(parentStreamId, weight, exclusive); + return onPriority(buffer, parentStreamId, weight, exclusive); } default: { @@ -114,9 +114,11 @@ public class PriorityBodyParser extends BodyParser return false; } - private boolean onPriority(int parentStreamId, int weight, boolean exclusive) + private boolean onPriority(ByteBuffer buffer, int parentStreamId, int weight, boolean exclusive) { PriorityFrame frame = new PriorityFrame(getStreamId(), parentStreamId, weight, exclusive); + if (!rateControlOnEvent(frame)) + return connectionFailure(buffer, ErrorCode.ENHANCE_YOUR_CALM_ERROR.code, "invalid_priority_frame_rate"); reset(); notifyPriority(frame); return true; diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/PushPromiseBodyParser.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/PushPromiseBodyParser.java index 9e4341acb00..2b712431424 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/PushPromiseBodyParser.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/PushPromiseBodyParser.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.http2.parser; @@ -124,7 +124,7 @@ public class PushPromiseBodyParser extends BodyParser } case HEADERS: { - MetaData metaData = headerBlockParser.parse(buffer, length); + MetaData.Request metaData = (MetaData.Request)headerBlockParser.parse(buffer, length); if (metaData == HeaderBlockParser.SESSION_FAILURE) return false; if (metaData != null) @@ -157,7 +157,7 @@ public class PushPromiseBodyParser extends BodyParser return false; } - private void onPushPromise(int streamId, MetaData metaData) + private void onPushPromise(int streamId, MetaData.Request metaData) { PushPromiseFrame frame = new PushPromiseFrame(getStreamId(), streamId, metaData); notifyPushPromise(frame); diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/RateControl.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/RateControl.java new file mode 100644 index 00000000000..2d716e07a49 --- /dev/null +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/RateControl.java @@ -0,0 +1,56 @@ +// +// ======================================================================== +// 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.http2.parser; + +import org.eclipse.jetty.io.EndPoint; + +/** + * Controls rate of events via {@link #onEvent(Object)}. + */ +public interface RateControl +{ + public static final RateControl NO_RATE_CONTROL = event -> true; + + /** + *Applications should call this method when they want to signal an + * event that is subject to rate control.
+ *Implementations should return true if the event does not exceed + * the desired rate, or false to signal that the event exceeded the + * desired rate.
+ * + * @param event the event subject to rate control. + * @return true IFF the rate is within limits + */ + public boolean onEvent(Object event); + + /** + * Factory to create RateControl instances. + */ + public interface Factory + { + /** + * @return a new RateControl instance for the given EndPoint + * @param endPoint the EndPoint for which the RateControl is created + */ + public default RateControl newRateControl(EndPoint endPoint) + { + return NO_RATE_CONTROL; + } + } +} diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/ResetBodyParser.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/ResetBodyParser.java index 45d99104d18..062aecb79c9 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/ResetBodyParser.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/ResetBodyParser.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.http2.parser; diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/ServerParser.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/ServerParser.java index 1b17ddfa73c..21aaf5aa6cd 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/ServerParser.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/ServerParser.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.http2.parser; @@ -25,21 +25,21 @@ import org.eclipse.jetty.http2.Flags; import org.eclipse.jetty.http2.frames.FrameType; import org.eclipse.jetty.io.ByteBufferPool; import org.eclipse.jetty.util.BufferUtil; -import org.eclipse.jetty.util.log.Log; -import org.eclipse.jetty.util.log.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class ServerParser extends Parser { - private static final Logger LOG = Log.getLogger(ServerParser.class); + private static final Logger LOG = LoggerFactory.getLogger(ServerParser.class); private final Listener listener; private final PrefaceParser prefaceParser; private State state = State.PREFACE; private boolean notifyPreface = true; - public ServerParser(ByteBufferPool byteBufferPool, Listener listener, int maxDynamicTableSize, int maxHeaderSize) + public ServerParser(ByteBufferPool byteBufferPool, Listener listener, int maxDynamicTableSize, int maxHeaderSize, RateControl rateControl) { - super(byteBufferPool, listener, maxDynamicTableSize, maxHeaderSize); + super(byteBufferPool, listener, maxDynamicTableSize, maxHeaderSize, rateControl); this.listener = listener; this.prefaceParser = new PrefaceParser(listener); } @@ -124,7 +124,7 @@ public class ServerParser extends Parser } catch (Throwable x) { - LOG.debug(x); + LOG.debug("Parse error", x); BufferUtil.clear(buffer); notifyConnectionFailure(ErrorCode.PROTOCOL_ERROR.code, "parser_error"); } diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/SettingsBodyParser.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/SettingsBodyParser.java index 741dd95981d..1854ab3371d 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/SettingsBodyParser.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/SettingsBodyParser.java @@ -1,24 +1,25 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.http2.parser; import java.nio.ByteBuffer; +import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicReference; @@ -27,12 +28,12 @@ import org.eclipse.jetty.http2.ErrorCode; import org.eclipse.jetty.http2.Flags; import org.eclipse.jetty.http2.frames.Frame; import org.eclipse.jetty.http2.frames.SettingsFrame; -import org.eclipse.jetty.util.log.Log; -import org.eclipse.jetty.util.log.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class SettingsBodyParser extends BodyParser { - private static final Logger LOG = Log.getLogger(SettingsBodyParser.class); + private static final Logger LOG = LoggerFactory.getLogger(SettingsBodyParser.class); private final int maxKeys; private State state = State.PREPARE; @@ -72,11 +73,21 @@ public class SettingsBodyParser extends BodyParser @Override protected void emptyBody(ByteBuffer buffer) { - onSettings(buffer, new HashMap<>()); + boolean isReply = hasFlag(Flags.ACK); + SettingsFrame frame = new SettingsFrame(Collections.emptyMap(), isReply); + if (!isReply && !rateControlOnEvent(frame)) + connectionFailure(buffer, ErrorCode.ENHANCE_YOUR_CALM_ERROR.code, "invalid_settings_frame_rate"); + else + onSettings(frame); } @Override public boolean parse(ByteBuffer buffer) + { + return parse(buffer, getStreamId(), getBodyLength()); + } + + private boolean parse(ByteBuffer buffer, int streamId, int bodyLength) { while (buffer.hasRemaining()) { @@ -85,9 +96,9 @@ public class SettingsBodyParser extends BodyParser case PREPARE: { // SPEC: wrong streamId is treated as connection error. - if (getStreamId() != 0) + if (streamId != 0) return connectionFailure(buffer, ErrorCode.PROTOCOL_ERROR.code, "invalid_settings_frame"); - length = getBodyLength(); + length = bodyLength; settings = new HashMap<>(); state = State.SETTING_ID; break; @@ -200,47 +211,44 @@ public class SettingsBodyParser extends BodyParser return connectionFailure(buffer, ErrorCode.PROTOCOL_ERROR.code, "invalid_settings_max_frame_size"); SettingsFrame frame = new SettingsFrame(settings, hasFlag(Flags.ACK)); + return onSettings(frame); + } + + private boolean onSettings(SettingsFrame frame) + { reset(); notifySettings(frame); return true; } + /** + *Parses the given buffer containing the whole body of a {@code SETTINGS} frame + * (without header bytes), typically from the {@code HTTP2-Settings} header.
+ * + * @param buffer the buffer containing the body of {@code SETTINGS} frame + * @return the {@code SETTINGS} frame from the parsed body bytes + */ public static SettingsFrame parseBody(final ByteBuffer buffer) { - final int bodyLength = buffer.remaining(); - final AtomicReferenceframeRef = new AtomicReference<>(); - SettingsBodyParser parser = new SettingsBodyParser(null, null) + AtomicReference frameRef = new AtomicReference<>(); + SettingsBodyParser parser = new SettingsBodyParser(new HeaderParser(RateControl.NO_RATE_CONTROL), new Parser.Listener.Adapter() { @Override - protected int getStreamId() + public void onSettings(SettingsFrame frame) { - return 0; + frameRef.set(frame); } @Override - protected int getBodyLength() - { - return bodyLength; - } - - @Override - protected boolean onSettings(ByteBuffer buffer, Map settings) - { - frameRef.set(new SettingsFrame(settings, false)); - return true; - } - - @Override - protected boolean connectionFailure(ByteBuffer buffer, int error, String reason) + public void onConnectionFailure(int error, String reason) { frameRef.set(null); - return false; } - }; - if (bodyLength == 0) - parser.emptyBody(buffer); + }); + if (buffer.hasRemaining()) + parser.parse(buffer, 0, buffer.remaining()); else - parser.parse(buffer); + parser.emptyBody(buffer); return frameRef.get(); } diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/UnknownBodyParser.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/UnknownBodyParser.java index dbb29bfede2..61f226d7ee5 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/UnknownBodyParser.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/UnknownBodyParser.java @@ -1,25 +1,28 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.http2.parser; import java.nio.ByteBuffer; +import org.eclipse.jetty.http2.ErrorCode; +import org.eclipse.jetty.http2.frames.UnknownFrame; + public class UnknownBodyParser extends BodyParser { private int cursor; @@ -34,7 +37,11 @@ public class UnknownBodyParser extends BodyParser { int length = cursor == 0 ? getBodyLength() : cursor; cursor = consume(buffer, length); - return cursor == 0; + boolean parsed = cursor == 0; + if (parsed && !rateControlOnEvent(new UnknownFrame(getFrameType()))) + return connectionFailure(buffer, ErrorCode.ENHANCE_YOUR_CALM_ERROR.code, "invalid_unknown_frame_rate"); + + return parsed; } private int consume(ByteBuffer buffer, int length) diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/WindowRateControl.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/WindowRateControl.java new file mode 100644 index 00000000000..da8e2e46ea6 --- /dev/null +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/WindowRateControl.java @@ -0,0 +1,103 @@ +// +// ======================================================================== +// 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.http2.parser; + +import java.time.Duration; +import java.util.Queue; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.atomic.AtomicInteger; + +import org.eclipse.jetty.io.EndPoint; + +/** + * An implementation of {@link RateControl} that limits the number of + * events within a time period.
+ *Events are kept in a queue and for each event the queue is first + * drained of the old events outside the time window, and then the new + * event is added to the queue. The size of the queue is maintained + * separately in an AtomicInteger and if it exceeds the max + * number of events then {@link #onEvent(Object)} returns {@code false}.
+ */ +public class WindowRateControl implements RateControl +{ + private final Queueevents = new ConcurrentLinkedQueue<>(); + private final AtomicInteger size = new AtomicInteger(); + private final int maxEvents; + private final long window; + + public static WindowRateControl fromEventsPerSecond(int maxEvents) + { + return new WindowRateControl(maxEvents, Duration.ofSeconds(1)); + } + + public WindowRateControl(int maxEvents, Duration window) + { + this.maxEvents = maxEvents; + this.window = window.toNanos(); + if (this.window == 0) + throw new IllegalArgumentException("Invalid duration " + window); + } + + public int getEventsPerSecond() + { + try + { + long rate = maxEvents * 1_000_000_000L / window; + return Math.toIntExact(rate); + } + catch (ArithmeticException x) + { + return Integer.MAX_VALUE; + } + } + + @Override + public boolean onEvent(Object event) + { + long now = System.nanoTime(); + while (true) + { + Long time = events.peek(); + if (time == null) + break; + if (now < time) + break; + if (events.remove(time)) + size.decrementAndGet(); + } + events.add(now + window); + return size.incrementAndGet() <= maxEvents; + } + + public static class Factory implements RateControl.Factory + { + private final int maxEventRate; + + public Factory(int maxEventRate) + { + this.maxEventRate = maxEventRate; + } + + @Override + public RateControl newRateControl(EndPoint endPoint) + { + return WindowRateControl.fromEventsPerSecond(maxEventRate); + } + } +} diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/WindowUpdateBodyParser.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/WindowUpdateBodyParser.java index 78505540939..adb00e82f6c 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/WindowUpdateBodyParser.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/WindowUpdateBodyParser.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.http2.parser; @@ -61,7 +61,7 @@ public class WindowUpdateBodyParser extends BodyParser if (buffer.remaining() >= 4) { windowDelta = buffer.getInt() & 0x7F_FF_FF_FF; - return onWindowUpdate(windowDelta); + return onWindowUpdate(buffer, windowDelta); } else { @@ -78,7 +78,7 @@ public class WindowUpdateBodyParser extends BodyParser if (cursor == 0) { windowDelta &= 0x7F_FF_FF_FF; - return onWindowUpdate(windowDelta); + return onWindowUpdate(buffer, windowDelta); } break; } @@ -91,9 +91,17 @@ public class WindowUpdateBodyParser extends BodyParser return false; } - private boolean onWindowUpdate(int windowDelta) + private boolean onWindowUpdate(ByteBuffer buffer, int windowDelta) { - WindowUpdateFrame frame = new WindowUpdateFrame(getStreamId(), windowDelta); + int streamId = getStreamId(); + if (windowDelta == 0) + { + if (streamId == 0) + return connectionFailure(buffer, ErrorCode.PROTOCOL_ERROR.code, "invalid_window_update_frame"); + else + return streamFailure(streamId, ErrorCode.PROTOCOL_ERROR.code, "invalid_window_update_frame"); + } + WindowUpdateFrame frame = new WindowUpdateFrame(streamId, windowDelta); reset(); notifyWindowUpdate(frame); return true; diff --git a/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/ContinuationParseTest.java b/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/ContinuationParseTest.java index 4db00c3db4b..3a6d00aa356 100644 --- a/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/ContinuationParseTest.java +++ b/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/ContinuationParseTest.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.http2.frames; diff --git a/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/DataGenerateParseTest.java b/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/DataGenerateParseTest.java index 3b018233a83..195744f8c74 100644 --- a/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/DataGenerateParseTest.java +++ b/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/DataGenerateParseTest.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.http2.frames; diff --git a/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/FrameFloodTest.java b/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/FrameFloodTest.java new file mode 100644 index 00000000000..36f33ae1217 --- /dev/null +++ b/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/FrameFloodTest.java @@ -0,0 +1,161 @@ +// +// ======================================================================== +// 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.http2.frames; + +import java.nio.ByteBuffer; +import java.time.Duration; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.UnaryOperator; + +import org.eclipse.jetty.http.HttpVersion; +import org.eclipse.jetty.http.MetaData; +import org.eclipse.jetty.http2.Flags; +import org.eclipse.jetty.http2.hpack.HpackEncoder; +import org.eclipse.jetty.http2.parser.Parser; +import org.eclipse.jetty.http2.parser.WindowRateControl; +import org.eclipse.jetty.io.ByteBufferPool; +import org.eclipse.jetty.io.MappedByteBufferPool; +import org.junit.jupiter.api.Test; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.lessThan; + +public class FrameFloodTest +{ + private final ByteBufferPool byteBufferPool = new MappedByteBufferPool(); + + // Frame structure: + // | Len0 | Len1 | Len2 | Type | Flags | StreamID0 |StreamID1 |StreamID2 |StreamID3 | Payload... | + + private byte[] frameFrom(int length, int frameType, int flags, int streamId, byte[] payload) + { + byte[] result = new byte[3 + 1 + 1 + 4 + payload.length]; + result[0] = (byte)((length >>> 16) & 0xFF); + result[1] = (byte)((length >>> 8) & 0xFF); + result[2] = (byte)(length & 0xFF); + result[3] = (byte)frameType; + result[4] = (byte)flags; + result[5] = (byte)((streamId >>> 24) & 0xFF); + result[6] = (byte)((streamId >>> 16) & 0xFF); + result[7] = (byte)((streamId >>> 8) & 0xFF); + result[8] = (byte)(streamId & 0xFF); + System.arraycopy(payload, 0, result, 9, payload.length); + return result; + } + + @Test + public void testDataFrameFlood() + { + byte[] payload = new byte[0]; + testFrameFlood(null, frameFrom(payload.length, FrameType.DATA.getType(), 0, 13, payload)); + } + + @Test + public void testHeadersFrameFlood() + { + byte[] payload = new byte[0]; + testFrameFlood(null, frameFrom(payload.length, FrameType.HEADERS.getType(), Flags.END_HEADERS, 13, payload)); + } + + @Test + public void testInvalidHeadersFrameFlood() throws Exception + { + // Invalid MetaData (no method, no scheme, etc). + MetaData.Request metadata = new MetaData.Request(null, (String)null, null, null, HttpVersion.HTTP_2, null, -1); + HpackEncoder encoder = new HpackEncoder(); + ByteBuffer buffer = ByteBuffer.allocate(1024); + encoder.encode(buffer, metadata); + buffer.flip(); + byte[] payload = new byte[buffer.remaining()]; + buffer.get(payload); + testFrameFlood(null, frameFrom(payload.length, FrameType.HEADERS.getType(), Flags.END_HEADERS, 13, payload)); + } + + @Test + public void testPriorityFrameFlood() + { + byte[] payload = new byte[]{0, 0, 0, 7, 0}; + testFrameFlood(null, frameFrom(payload.length, FrameType.PRIORITY.getType(), 0, 13, payload)); + } + + @Test + public void testSettingsFrameFlood() + { + byte[] payload = new byte[0]; + testFrameFlood(null, frameFrom(payload.length, FrameType.SETTINGS.getType(), 0, 0, payload)); + } + + @Test + public void testPingFrameFlood() + { + byte[] payload = {0, 0, 0, 0, 0, 0, 0, 0}; + testFrameFlood(null, frameFrom(payload.length, FrameType.PING.getType(), 0, 0, payload)); + } + + @Test + public void testContinuationFrameFlood() + { + int streamId = 13; + byte[] headersPayload = new byte[0]; + byte[] headersBytes = frameFrom(headersPayload.length, FrameType.HEADERS.getType(), 0, streamId, headersPayload); + byte[] continuationPayload = new byte[0]; + testFrameFlood(headersBytes, frameFrom(continuationPayload.length, FrameType.CONTINUATION.getType(), 0, streamId, continuationPayload)); + } + + @Test + public void testUnknownFrameFlood() + { + byte[] payload = {0, 0, 0, 0}; + testFrameFlood(null, frameFrom(payload.length, 64, 0, 0, payload)); + } + + private void testFrameFlood(byte[] preamble, byte[] bytes) + { + AtomicBoolean failed = new AtomicBoolean(); + Parser parser = new Parser(byteBufferPool, new Parser.Listener.Adapter() + { + @Override + public void onConnectionFailure(int error, String reason) + { + failed.set(true); + } + }, 4096, 8192, new WindowRateControl(8, Duration.ofSeconds(1))); + parser.init(UnaryOperator.identity()); + + if (preamble != null) + { + ByteBuffer buffer = ByteBuffer.wrap(preamble); + while (buffer.hasRemaining()) + { + parser.parse(buffer); + } + } + + int count = 0; + while (!failed.get()) + { + ByteBuffer buffer = ByteBuffer.wrap(bytes); + while (buffer.hasRemaining()) + { + parser.parse(buffer); + } + assertThat("too many frames allowed", ++count, lessThan(1024)); + } + } +} diff --git a/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/GoAwayGenerateParseTest.java b/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/GoAwayGenerateParseTest.java index 0cc7e37c870..d4036427586 100644 --- a/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/GoAwayGenerateParseTest.java +++ b/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/GoAwayGenerateParseTest.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.http2.frames; diff --git a/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/HeadersGenerateParseTest.java b/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/HeadersGenerateParseTest.java index b67fe45d589..fbf03eb9180 100644 --- a/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/HeadersGenerateParseTest.java +++ b/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/HeadersGenerateParseTest.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.http2.frames; diff --git a/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/MaxFrameSizeParseTest.java b/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/MaxFrameSizeParseTest.java index 43a97f0da81..d15de77a83f 100644 --- a/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/MaxFrameSizeParseTest.java +++ b/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/MaxFrameSizeParseTest.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.http2.frames; diff --git a/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/PingGenerateParseTest.java b/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/PingGenerateParseTest.java index 0b7c31f9674..4d1200523c5 100644 --- a/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/PingGenerateParseTest.java +++ b/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/PingGenerateParseTest.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.http2.frames; diff --git a/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/PriorityGenerateParseTest.java b/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/PriorityGenerateParseTest.java index ecbdd10caf8..25ce0a0b499 100644 --- a/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/PriorityGenerateParseTest.java +++ b/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/PriorityGenerateParseTest.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.http2.frames; diff --git a/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/PushPromiseGenerateParseTest.java b/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/PushPromiseGenerateParseTest.java index 3d6d8db2938..886d6e3a4fd 100644 --- a/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/PushPromiseGenerateParseTest.java +++ b/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/PushPromiseGenerateParseTest.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.http2.frames; diff --git a/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/ResetGenerateParseTest.java b/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/ResetGenerateParseTest.java index 4a2f9a35d8e..2fb731da3e0 100644 --- a/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/ResetGenerateParseTest.java +++ b/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/ResetGenerateParseTest.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.http2.frames; diff --git a/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/SettingsGenerateParseTest.java b/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/SettingsGenerateParseTest.java index 9fcdb743dc6..ca4f81f9791 100644 --- a/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/SettingsGenerateParseTest.java +++ b/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/SettingsGenerateParseTest.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.http2.frames; diff --git a/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/UnknownParseTest.java b/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/UnknownParseTest.java index 9f81bfed88d..a9e4a5583ef 100644 --- a/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/UnknownParseTest.java +++ b/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/UnknownParseTest.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.http2.frames; diff --git a/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/WindowUpdateGenerateParseTest.java b/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/WindowUpdateGenerateParseTest.java index 04825a5e7a6..693cbb22905 100644 --- a/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/WindowUpdateGenerateParseTest.java +++ b/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/WindowUpdateGenerateParseTest.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.http2.frames; diff --git a/jetty-http2/http2-common/src/test/resources/jetty-logging.properties b/jetty-http2/http2-common/src/test/resources/jetty-logging.properties index b4e43807801..874ebdbc1eb 100644 --- a/jetty-http2/http2-common/src/test/resources/jetty-logging.properties +++ b/jetty-http2/http2-common/src/test/resources/jetty-logging.properties @@ -1,2 +1,2 @@ -org.eclipse.jetty.util.log.class=org.eclipse.jetty.util.log.StdErrLog +# Jetty Logging using jetty-slf4j-impl org.eclipse.jetty.http2.LEVEL=INFO diff --git a/jetty-http2/http2-hpack/pom.xml b/jetty-http2/http2-hpack/pom.xml index 6f154432a16..0c49d1bb8fc 100644 --- a/jetty-http2/http2-hpack/pom.xml +++ b/jetty-http2/http2-hpack/pom.xml @@ -48,6 +48,10 @@ jetty-io ${project.version}
Sets the factory that creates a per-connection RateControl object.
+ * + * @param rateControlFactory the factory that creates RateControl objects + */ + public void setRateControlFactory(RateControl.Factory rateControlFactory) + { + this.rateControlFactory = Objects.requireNonNull(rateControlFactory); + } + + @ManagedAttribute("Whether to use direct ByteBuffers for reading") + public boolean isUseInputDirectByteBuffers() + { + return useInputDirectByteBuffers; + } + + public void setUseInputDirectByteBuffers(boolean useInputDirectByteBuffers) + { + this.useInputDirectByteBuffers = useInputDirectByteBuffers; + } + + @ManagedAttribute("Whether to use direct ByteBuffers for writing") + public boolean isUseOutputDirectByteBuffers() + { + return useOutputDirectByteBuffers; + } + + public void setUseOutputDirectByteBuffers(boolean useOutputDirectByteBuffers) + { + this.useOutputDirectByteBuffers = useOutputDirectByteBuffers; + } + public HttpConfiguration getHttpConfiguration() { return httpConfiguration; @@ -192,6 +255,7 @@ public abstract class AbstractHTTP2ServerConnectionFactory extends AbstractConne if (maxConcurrentStreams >= 0) settings.put(SettingsFrame.MAX_CONCURRENT_STREAMS, maxConcurrentStreams); settings.put(SettingsFrame.MAX_HEADER_LIST_SIZE, getHttpConfiguration().getRequestHeaderSize()); + settings.put(SettingsFrame.ENABLE_CONNECT_PROTOCOL, isConnectProtocolEnabled() ? 1 : 0); return settings; } @@ -200,7 +264,7 @@ public abstract class AbstractHTTP2ServerConnectionFactory extends AbstractConne { ServerSessionListener listener = newSessionListener(connector, endPoint); - Generator generator = new Generator(connector.getByteBufferPool(), getMaxDynamicTableSize(), getMaxHeaderBlockFragment()); + Generator generator = new Generator(connector.getByteBufferPool(), isUseOutputDirectByteBuffers(), getMaxDynamicTableSize(), getMaxHeaderBlockFragment()); FlowControlStrategy flowControl = getFlowControlStrategyFactory().newFlowControlStrategy(); HTTP2ServerSession session = new HTTP2ServerSession(connector.getScheduler(), endPoint, generator, listener, flowControl); session.setMaxLocalStreams(getMaxConcurrentStreams()); @@ -210,46 +274,51 @@ public abstract class AbstractHTTP2ServerConnectionFactory extends AbstractConne // the typical case is that the connection will be busier and the // stream idle timeout will expire earlier than the connection's. long streamIdleTimeout = getStreamIdleTimeout(); - if (streamIdleTimeout <= 0) - streamIdleTimeout = endPoint.getIdleTimeout(); - session.setStreamIdleTimeout(streamIdleTimeout); + if (streamIdleTimeout > 0) + session.setStreamIdleTimeout(streamIdleTimeout); session.setInitialSessionRecvWindow(getInitialSessionRecvWindow()); session.setWriteThreshold(getHttpConfiguration().getOutputBufferSize()); + session.setConnectProtocolEnabled(isConnectProtocolEnabled()); - ServerParser parser = newServerParser(connector, session); + ServerParser parser = newServerParser(connector, session, getRateControlFactory().newRateControl(endPoint)); parser.setMaxFrameLength(getMaxFrameLength()); parser.setMaxSettingsKeys(getMaxSettingsKeys()); HTTP2Connection connection = new HTTP2ServerConnection(connector.getByteBufferPool(), connector.getExecutor(), endPoint, httpConfiguration, parser, session, getInputBufferSize(), listener); - connection.addListener(sessionContainer); + connection.setUseInputDirectByteBuffers(isUseInputDirectByteBuffers()); + connection.setUseOutputDirectByteBuffers(isUseOutputDirectByteBuffers()); + connection.addEventListener(sessionContainer); return configure(connection, connector, endPoint); } protected abstract ServerSessionListener newSessionListener(Connector connector, EndPoint endPoint); - protected ServerParser newServerParser(Connector connector, ServerParser.Listener listener) + protected ServerParser newServerParser(Connector connector, ServerParser.Listener listener, RateControl rateControl) { - return new ServerParser(connector.getByteBufferPool(), listener, getMaxDynamicTableSize(), getHttpConfiguration().getRequestHeaderSize()); + return new ServerParser(connector.getByteBufferPool(), listener, getMaxDynamicTableSize(), getHttpConfiguration().getRequestHeaderSize(), rateControl); } @ManagedObject("The container of HTTP/2 sessions") - public static class HTTP2SessionContainer implements Connection.Listener, Dumpable + public static class HTTP2SessionContainer implements Connection.Listener, Graceful, Dumpable { - private final SetIf used in combination with a {@link HttpConnectionFactory} as the
* default protocol, this factory can support the non-standard direct
- * update mechanism, where a HTTP1 request of the form "PRI * HTTP/2.0"
- * is used to trigger a switch to a HTTP2 connection. This approach
+ * update mechanism, where an HTTP1 request of the form "PRI * HTTP/2.0"
+ * is used to trigger a switch to an HTTP2 connection. This approach
* allows a single port to accept either HTTP/1 or HTTP/2 direct
* connections.
*/
public class HTTP2CServerConnectionFactory extends HTTP2ServerConnectionFactory implements ConnectionFactory.Upgrading
{
- private static final Logger LOG = Log.getLogger(HTTP2CServerConnectionFactory.class);
+ private static final Logger LOG = LoggerFactory.getLogger(HTTP2CServerConnectionFactory.class);
public HTTP2CServerConnectionFactory(@Name("config") HttpConfiguration httpConfiguration)
{
@@ -74,13 +74,13 @@ public class HTTP2CServerConnectionFactory extends HTTP2ServerConnectionFactory
public Connection upgradeConnection(Connector connector, EndPoint endPoint, Request request, HttpFields response101) throws BadMessageException
{
if (LOG.isDebugEnabled())
- LOG.debug("{} upgraded {}{}", this, request.toString(), request.getFields());
+ LOG.debug("{} upgrading {}{}{}", this, request, System.lineSeparator(), request.getFields());
if (request.getContentLength() > 0)
return null;
HTTP2ServerConnection connection = (HTTP2ServerConnection)newConnection(connector, endPoint);
- if (connection.upgrade(request))
+ if (connection.upgrade(request, response101))
return connection;
return null;
}
diff --git a/jetty-http2/http2-server/src/main/java/org/eclipse/jetty/http2/server/HTTP2ServerConnection.java b/jetty-http2/http2-server/src/main/java/org/eclipse/jetty/http2/server/HTTP2ServerConnection.java
index 331696417d2..515f733dd16 100644
--- a/jetty-http2/http2-server/src/main/java/org/eclipse/jetty/http2/server/HTTP2ServerConnection.java
+++ b/jetty-http2/http2-server/src/main/java/org/eclipse/jetty/http2/server/HTTP2ServerConnection.java
@@ -1,26 +1,25 @@
//
-// ========================================================================
-// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd.
-// ------------------------------------------------------------------------
-// All rights reserved. This program and the accompanying materials
-// are made available under the terms of the Eclipse Public License v1.0
-// and Apache License v2.0 which accompanies this distribution.
+// ========================================================================
+// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others.
//
-// The Eclipse Public License is available at
-// http://www.eclipse.org/legal/epl-v10.html
+// 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
//
-// The Apache License v2.0 is available at
-// http://www.opensource.org/licenses/apache2.0.php
+// 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
//
-// You may elect to redistribute this code under either of these licenses.
-// ========================================================================
+// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
+// ========================================================================
//
package org.eclipse.jetty.http2.server;
import java.io.Closeable;
import java.io.IOException;
-import java.nio.ByteBuffer;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Base64;
@@ -33,11 +32,14 @@ import java.util.concurrent.atomic.AtomicLong;
import org.eclipse.jetty.http.BadMessageException;
import org.eclipse.jetty.http.HttpField;
+import org.eclipse.jetty.http.HttpFields;
import org.eclipse.jetty.http.HttpHeader;
import org.eclipse.jetty.http.HttpMethod;
+import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.http.MetaData;
import org.eclipse.jetty.http.MetaData.Request;
import org.eclipse.jetty.http2.ErrorCode;
+import org.eclipse.jetty.http2.HTTP2Channel;
import org.eclipse.jetty.http2.HTTP2Connection;
import org.eclipse.jetty.http2.ISession;
import org.eclipse.jetty.http2.IStream;
@@ -52,7 +54,6 @@ import org.eclipse.jetty.http2.frames.SettingsFrame;
import org.eclipse.jetty.http2.parser.ServerParser;
import org.eclipse.jetty.http2.parser.SettingsBodyParser;
import org.eclipse.jetty.io.ByteBufferPool;
-import org.eclipse.jetty.io.Connection;
import org.eclipse.jetty.io.EndPoint;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.HttpConfiguration;
@@ -61,10 +62,10 @@ import org.eclipse.jetty.util.Callback;
import org.eclipse.jetty.util.CountingCallback;
import org.eclipse.jetty.util.TypeUtil;
-public class HTTP2ServerConnection extends HTTP2Connection implements Connection.UpgradeTo
+public class HTTP2ServerConnection extends HTTP2Connection
{
/**
- * @param protocol A HTTP2 protocol variant
+ * @param protocol An HTTP2 protocol variant
* @return True if the protocol version is supported
*/
public static boolean isSupportedProtocol(String protocol)
@@ -86,7 +87,7 @@ public class HTTP2ServerConnection extends HTTP2Connection implements Connection
return false;
}
}
-
+
private final Queue
A convenience base implementation of {@link Connection}.
@@ -38,7 +39,7 @@ import org.eclipse.jetty.util.thread.Invocable; */ public abstract class AbstractConnection implements Connection { - private static final Logger LOG = Log.getLogger(AbstractConnection.class); + private static final Logger LOG = LoggerFactory.getLogger(AbstractConnection.class); private final Listtrue
if there are bytes remaining to be read from the encoded input
+ * @return {@code true} if there are bytes remaining to be read from the encoded input
*/
public boolean hasMore()
{
return getOutput().position() > 0;
}
- /*
- * @see org.eclipse.io.EndPoint#fill(org.eclipse.io.Buffer)
- */
@Override
public int fill(ByteBuffer buffer) throws IOException
{
int filled = 0;
- try (Locker.Lock lock = _locker.lock())
+ try (AutoLock lock = _lock.lock())
{
while (true)
{
@@ -411,14 +397,11 @@ public class ByteArrayEndPoint extends AbstractEndPoint
return filled;
}
- /*
- * @see org.eclipse.io.EndPoint#flush(org.eclipse.io.Buffer, org.eclipse.io.Buffer, org.eclipse.io.Buffer)
- */
@Override
public boolean flush(ByteBuffer... buffers) throws IOException
{
boolean flushed = true;
- try (Locker.Lock lock = _locker.lock())
+ try (AutoLock lock = _lock.lock())
{
if (!isOpen())
throw new IOException("CLOSED");
@@ -461,13 +444,10 @@ public class ByteArrayEndPoint extends AbstractEndPoint
return flushed;
}
- /**
- *
- */
@Override
public void reset()
{
- try (Locker.Lock lock = _locker.lock())
+ try (AutoLock lock = _lock.lock())
{
_inQ.clear();
_hasOutput.signalAll();
@@ -476,9 +456,6 @@ public class ByteArrayEndPoint extends AbstractEndPoint
super.reset();
}
- /*
- * @see org.eclipse.io.EndPoint#getConnection()
- */
@Override
public Object getTransport()
{
@@ -507,7 +484,7 @@ public class ByteArrayEndPoint extends AbstractEndPoint
int q;
ByteBuffer b;
String o;
- try (Locker.Lock lock = _locker.lock())
+ try (AutoLock lock = _lock.lock())
{
q = _inQ.size();
b = _inQ.peek();
diff --git a/jetty-io/src/main/java/org/eclipse/jetty/io/ByteBufferOutputStream.java b/jetty-io/src/main/java/org/eclipse/jetty/io/ByteBufferOutputStream.java
new file mode 100644
index 00000000000..1ac63d2ee9a
--- /dev/null
+++ b/jetty-io/src/main/java/org/eclipse/jetty/io/ByteBufferOutputStream.java
@@ -0,0 +1,62 @@
+//
+// ========================================================================
+// 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.io;
+
+import java.io.OutputStream;
+import java.nio.ByteBuffer;
+
+import org.eclipse.jetty.util.BufferUtil;
+
+/**
+ * Simple wrapper of a ByteBuffer as an OutputStream.
+ * The buffer does not grow and this class will throw an
+ * {@link java.nio.BufferOverflowException} if the buffer capacity is exceeded.
+ */
+public class ByteBufferOutputStream extends OutputStream
+{
+ final ByteBuffer _buffer;
+
+ public ByteBufferOutputStream(ByteBuffer buffer)
+ {
+ _buffer = buffer;
+ }
+
+ public void close()
+ {
+ }
+
+ public void flush()
+ {
+ }
+
+ public void write(byte[] b)
+ {
+ write(b, 0, b.length);
+ }
+
+ public void write(byte[] b, int off, int len)
+ {
+ BufferUtil.append(_buffer, b, off, len);
+ }
+
+ public void write(int b)
+ {
+ BufferUtil.append(_buffer, (byte)b);
+ }
+}
diff --git a/jetty-io/src/main/java/org/eclipse/jetty/io/ByteBufferPool.java b/jetty-io/src/main/java/org/eclipse/jetty/io/ByteBufferPool.java
index 68db0b2880b..06e64fd9406 100644
--- a/jetty-io/src/main/java/org/eclipse/jetty/io/ByteBufferPool.java
+++ b/jetty-io/src/main/java/org/eclipse/jetty/io/ByteBufferPool.java
@@ -1,19 +1,19 @@
//
-// ========================================================================
-// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd.
-// ------------------------------------------------------------------------
-// All rights reserved. This program and the accompanying materials
-// are made available under the terms of the Eclipse Public License v1.0
-// and Apache License v2.0 which accompanies this distribution.
+// ========================================================================
+// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others.
//
-// The Eclipse Public License is available at
-// http://www.eclipse.org/legal/epl-v10.html
+// 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
//
-// The Apache License v2.0 is available at
-// http://www.opensource.org/licenses/apache2.0.php
+// 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
//
-// You may elect to redistribute this code under either of these licenses.
-// ========================================================================
+// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
+// ========================================================================
//
package org.eclipse.jetty.io;
@@ -127,11 +127,16 @@ public interface ByteBufferPool
{
ByteBuffer buffer = buffers.get(i);
if (recycles.get(i))
- byteBufferPool.release(buffer);
+ release(buffer);
}
buffers.clear();
recycles.clear();
}
+
+ public void release(ByteBuffer buffer)
+ {
+ byteBufferPool.release(buffer);
+ }
}
public static class Bucket
diff --git a/jetty-io/src/main/java/org/eclipse/jetty/io/ChannelEndPoint.java b/jetty-io/src/main/java/org/eclipse/jetty/io/ChannelEndPoint.java
index 0d58fde8245..2c89a173753 100644
--- a/jetty-io/src/main/java/org/eclipse/jetty/io/ChannelEndPoint.java
+++ b/jetty-io/src/main/java/org/eclipse/jetty/io/ChannelEndPoint.java
@@ -1,19 +1,19 @@
//
-// ========================================================================
-// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd.
-// ------------------------------------------------------------------------
-// All rights reserved. This program and the accompanying materials
-// are made available under the terms of the Eclipse Public License v1.0
-// and Apache License v2.0 which accompanies this distribution.
+// ========================================================================
+// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others.
//
-// The Eclipse Public License is available at
-// http://www.eclipse.org/legal/epl-v10.html
+// 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
//
-// The Apache License v2.0 is available at
-// http://www.opensource.org/licenses/apache2.0.php
+// 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
//
-// You may elect to redistribute this code under either of these licenses.
-// ========================================================================
+// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
+// ========================================================================
//
package org.eclipse.jetty.io;
@@ -28,10 +28,10 @@ import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import org.eclipse.jetty.util.BufferUtil;
-import org.eclipse.jetty.util.log.Log;
-import org.eclipse.jetty.util.log.Logger;
import org.eclipse.jetty.util.thread.Invocable;
import org.eclipse.jetty.util.thread.Scheduler;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* Channel End Point.
@@ -39,7 +39,7 @@ import org.eclipse.jetty.util.thread.Scheduler;
*/
public abstract class ChannelEndPoint extends AbstractEndPoint implements ManagedSelector.Selectable
{
- private static final Logger LOG = Log.getLogger(ChannelEndPoint.class);
+ private static final Logger LOG = LoggerFactory.getLogger(ChannelEndPoint.class);
private final ByteChannel _channel;
private final GatheringByteChannel _gather;
@@ -89,7 +89,7 @@ public abstract class ChannelEndPoint extends AbstractEndPoint implements Manage
}
catch (Throwable x)
{
- LOG.warn(x);
+ LOG.warn("Unable to close ChannelEndPoint", x);
}
}
}
@@ -175,12 +175,6 @@ public abstract class ChannelEndPoint extends AbstractEndPoint implements Manage
_gather = (channel instanceof GatheringByteChannel) ? (GatheringByteChannel)channel : null;
}
- @Override
- public boolean isOptimizedForDirectBuffers()
- {
- return true;
- }
-
@Override
public boolean isOpen()
{
@@ -198,7 +192,7 @@ public abstract class ChannelEndPoint extends AbstractEndPoint implements Manage
}
catch (IOException e)
{
- LOG.debug(e);
+ LOG.debug("Unable to close channel", e);
}
finally
{
@@ -238,7 +232,7 @@ public abstract class ChannelEndPoint extends AbstractEndPoint implements Manage
}
catch (IOException e)
{
- LOG.debug(e);
+ LOG.debug("Unable to shutdown output", e);
shutdownInput();
filled = -1;
}
diff --git a/jetty-io/src/main/java/org/eclipse/jetty/io/ClientConnectionFactory.java b/jetty-io/src/main/java/org/eclipse/jetty/io/ClientConnectionFactory.java
index d6bcf20369b..4e555e7878e 100644
--- a/jetty-io/src/main/java/org/eclipse/jetty/io/ClientConnectionFactory.java
+++ b/jetty-io/src/main/java/org/eclipse/jetty/io/ClientConnectionFactory.java
@@ -1,24 +1,25 @@
//
-// ========================================================================
-// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd.
-// ------------------------------------------------------------------------
-// All rights reserved. This program and the accompanying materials
-// are made available under the terms of the Eclipse Public License v1.0
-// and Apache License v2.0 which accompanies this distribution.
+// ========================================================================
+// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others.
//
-// The Eclipse Public License is available at
-// http://www.eclipse.org/legal/epl-v10.html
+// 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
//
-// The Apache License v2.0 is available at
-// http://www.opensource.org/licenses/apache2.0.php
+// 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
//
-// You may elect to redistribute this code under either of these licenses.
-// ========================================================================
+// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
+// ========================================================================
//
package org.eclipse.jetty.io;
import java.io.IOException;
+import java.util.EventListener;
import java.util.List;
import java.util.Map;
@@ -43,16 +44,33 @@ public interface ClientConnectionFactory
{
ContainerLifeCycle client = (ContainerLifeCycle)context.get(CLIENT_CONTEXT_KEY);
if (client != null)
- client.getBeans(Connection.Listener.class).forEach(connection::addListener);
+ client.getBeans(EventListener.class).forEach(connection::addEventListener);
return connection;
}
+ /**
+ * Wraps another ClientConnectionFactory.
+ *This is typically done by protocols that send "preface" bytes with some metadata + * before other protocols. The metadata could be, for example, proxying information + * or authentication information.
+ */ + interface Decorator + { + /** + *Wraps the given {@code factory}.
+ * + * @param factory the ClientConnectionFactory to wrap + * @return the wrapping ClientConnectionFactory + */ + ClientConnectionFactory apply(ClientConnectionFactory factory); + } + /** *A holder for a list of protocol strings identifying a network protocol * (for example {@code ["h2", "h2-17", "h2-16"]}) and a {@link ClientConnectionFactory} * that creates connections that speak that network protocol.
*/ - public static class Info + public static class Info extends ContainerLifeCycle { private final ListRemoves a listener of connection events.
* * @param listener the listener to remove */ - public void removeListener(Listener listener); + public void removeEventListener(EventListener listener); /** *Callback method invoked when this connection is opened.
@@ -133,7 +134,7 @@ public interface Connection extends Closeable * the Connector or ConnectionFactory are added as listeners to all new connections * */ - public interface Listener + public interface Listener extends EventListener { public void onOpened(Connection connection); diff --git a/jetty-io/src/main/java/org/eclipse/jetty/io/ConnectionStatistics.java b/jetty-io/src/main/java/org/eclipse/jetty/io/ConnectionStatistics.java index bf062408cb0..1bade4e6320 100644 --- a/jetty-io/src/main/java/org/eclipse/jetty/io/ConnectionStatistics.java +++ b/jetty-io/src/main/java/org/eclipse/jetty/io/ConnectionStatistics.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.io; diff --git a/jetty-io/src/main/java/org/eclipse/jetty/io/CyclicTimeout.java b/jetty-io/src/main/java/org/eclipse/jetty/io/CyclicTimeout.java index 211b1e11ed2..f064941af8e 100644 --- a/jetty-io/src/main/java/org/eclipse/jetty/io/CyclicTimeout.java +++ b/jetty-io/src/main/java/org/eclipse/jetty/io/CyclicTimeout.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.io; @@ -22,9 +22,9 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import org.eclipse.jetty.util.component.Destroyable; -import org.eclipse.jetty.util.log.Log; -import org.eclipse.jetty.util.log.Logger; import org.eclipse.jetty.util.thread.Scheduler; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import static java.lang.Long.MAX_VALUE; @@ -50,7 +50,7 @@ import static java.lang.Long.MAX_VALUE; */ public abstract class CyclicTimeout implements Destroyable { - private static final Logger LOG = Log.getLogger(CyclicTimeout.class); + private static final Logger LOG = LoggerFactory.getLogger(CyclicTimeout.class); private static final Timeout NOT_SET = new Timeout(MAX_VALUE, null); private static final Scheduler.Task DESTROYED = () -> false; diff --git a/jetty-io/src/main/java/org/eclipse/jetty/io/EndPoint.java b/jetty-io/src/main/java/org/eclipse/jetty/io/EndPoint.java index 875ad2521da..09126f49124 100644 --- a/jetty-io/src/main/java/org/eclipse/jetty/io/EndPoint.java +++ b/jetty-io/src/main/java/org/eclipse/jetty/io/EndPoint.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.io; @@ -95,7 +95,17 @@ import org.eclipse.jetty.util.thread.Invocable; */ public interface EndPoint extends Closeable { - + /** + * Marks anEndPoint
that wraps another EndPoint
.
+ */
+ public interface Wrapper
+ {
+ /**
+ * @return The wrapped EndPoint
+ */
+ EndPoint unwrap();
+ }
+
/**
* @return The local Inet address to which this EndPoint
is bound, or null
* if this EndPoint
does not represent a network connection.
@@ -269,13 +279,6 @@ public interface EndPoint extends Closeable
*/
void onClose(Throwable cause);
- /**
- * Is the endpoint optimized for DirectBuffer usage
- *
- * @return True if direct buffers can be used optimally.
- */
- boolean isOptimizedForDirectBuffers();
-
/**
* Upgrade connections.
* Close the old connection, update the endpoint and open the new connection.
diff --git a/jetty-io/src/main/java/org/eclipse/jetty/io/EofException.java b/jetty-io/src/main/java/org/eclipse/jetty/io/EofException.java
index fc8c0aa21e0..de64ec54392 100644
--- a/jetty-io/src/main/java/org/eclipse/jetty/io/EofException.java
+++ b/jetty-io/src/main/java/org/eclipse/jetty/io/EofException.java
@@ -1,19 +1,19 @@
//
-// ========================================================================
-// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd.
-// ------------------------------------------------------------------------
-// All rights reserved. This program and the accompanying materials
-// are made available under the terms of the Eclipse Public License v1.0
-// and Apache License v2.0 which accompanies this distribution.
+// ========================================================================
+// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others.
//
-// The Eclipse Public License is available at
-// http://www.eclipse.org/legal/epl-v10.html
+// 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
//
-// The Apache License v2.0 is available at
-// http://www.opensource.org/licenses/apache2.0.php
+// 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
//
-// You may elect to redistribute this code under either of these licenses.
-// ========================================================================
+// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
+// ========================================================================
//
package org.eclipse.jetty.io;
diff --git a/jetty-io/src/main/java/org/eclipse/jetty/io/FillInterest.java b/jetty-io/src/main/java/org/eclipse/jetty/io/FillInterest.java
index 6a90d9c2153..b904638d665 100644
--- a/jetty-io/src/main/java/org/eclipse/jetty/io/FillInterest.java
+++ b/jetty-io/src/main/java/org/eclipse/jetty/io/FillInterest.java
@@ -1,19 +1,19 @@
//
-// ========================================================================
-// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd.
-// ------------------------------------------------------------------------
-// All rights reserved. This program and the accompanying materials
-// are made available under the terms of the Eclipse Public License v1.0
-// and Apache License v2.0 which accompanies this distribution.
+// ========================================================================
+// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others.
//
-// The Eclipse Public License is available at
-// http://www.eclipse.org/legal/epl-v10.html
+// 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
//
-// The Apache License v2.0 is available at
-// http://www.opensource.org/licenses/apache2.0.php
+// 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
//
-// You may elect to redistribute this code under either of these licenses.
-// ========================================================================
+// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
+// ========================================================================
//
package org.eclipse.jetty.io;
@@ -24,10 +24,10 @@ import java.nio.channels.ReadPendingException;
import java.util.concurrent.atomic.AtomicReference;
import org.eclipse.jetty.util.Callback;
-import org.eclipse.jetty.util.log.Log;
-import org.eclipse.jetty.util.log.Logger;
import org.eclipse.jetty.util.thread.Invocable;
import org.eclipse.jetty.util.thread.Invocable.InvocationType;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* A Utility class to help implement {@link EndPoint#fillInterested(Callback)}
@@ -35,7 +35,7 @@ import org.eclipse.jetty.util.thread.Invocable.InvocationType;
*/
public abstract class FillInterest
{
- private static final Logger LOG = Log.getLogger(FillInterest.class);
+ private static final Logger LOG = LoggerFactory.getLogger(FillInterest.class);
private final AtomicReference{@link ManagedSelector} wraps a {@link Selector} simplifying non-blocking operations on channels.
@@ -60,7 +62,7 @@ import org.eclipse.jetty.util.thread.strategy.EatWhatYouKill; */ public class ManagedSelector extends ContainerLifeCycle implements Dumpable { - private static final Logger LOG = Log.getLogger(ManagedSelector.class); + private static final Logger LOG = LoggerFactory.getLogger(ManagedSelector.class); private static final boolean FORCE_SELECT_NOW; static @@ -94,7 +96,6 @@ public class ManagedSelector extends ContainerLifeCycle implements Dumpable Executor executor = selectorManager.getExecutor(); _strategy = new EatWhatYouKill(producer, executor); addBean(_strategy, true); - setStopTimeout(5000); } public Selector getSelector() @@ -122,12 +123,20 @@ public class ManagedSelector extends ContainerLifeCycle implements Dumpable start._started.await(); } + protected void onSelectFailed(Throwable cause) + { + // override to change behavior + } + public int size() { Selector s = _selector; if (s == null) return 0; - return s.keys().size(); + Set{@link SelectorManager} manages a number of {@link ManagedSelector}s that @@ -57,7 +58,7 @@ import org.eclipse.jetty.util.thread.ThreadPoolBudget; public abstract class SelectorManager extends ContainerLifeCycle implements Dumpable { public static final int DEFAULT_CONNECT_TIMEOUT = 15000; - protected static final Logger LOG = Log.getLogger(SelectorManager.class); + protected static final Logger LOG = LoggerFactory.getLogger(SelectorManager.class); private final Executor executor; private final Scheduler scheduler; @@ -389,31 +390,37 @@ public abstract class SelectorManager extends ContainerLifeCycle implements Dump */ public abstract Connection newConnection(SelectableChannel channel, EndPoint endpoint, Object attachment) throws IOException; - public void addEventListener(EventListener listener) + /** + * @param listener An EventListener + * @see AcceptListener + * @see Container#addEventListener(EventListener) + */ + @Override + public boolean addEventListener(EventListener listener) { if (isRunning()) throw new IllegalStateException(this.toString()); - if (listener instanceof AcceptListener) - addAcceptListener(AcceptListener.class.cast(listener)); + if (super.addEventListener(listener)) + { + if (listener instanceof AcceptListener) + _acceptListeners.add((AcceptListener)listener); + return true; + } + return false; } - public void removeEventListener(EventListener listener) + @Override + public boolean removeEventListener(EventListener listener) { if (isRunning()) throw new IllegalStateException(this.toString()); - if (listener instanceof AcceptListener) - removeAcceptListener(AcceptListener.class.cast(listener)); - } - - public void addAcceptListener(AcceptListener listener) - { - if (!_acceptListeners.contains(listener)) - _acceptListeners.add(listener); - } - - public void removeAcceptListener(AcceptListener listener) - { - _acceptListeners.remove(listener); + if (super.removeEventListener(listener)) + { + if (listener instanceof AcceptListener) + _acceptListeners.remove(listener); + return true; + } + return false; } protected void onAccepting(SelectableChannel channel) @@ -426,7 +433,7 @@ public abstract class SelectorManager extends ContainerLifeCycle implements Dump } catch (Throwable x) { - LOG.warn(x); + LOG.warn("Failed to notify onAccepting on listener {}", l, x); } } } @@ -441,7 +448,7 @@ public abstract class SelectorManager extends ContainerLifeCycle implements Dump } catch (Throwable x) { - LOG.warn(x); + LOG.warn("Failed to notify onAcceptFailed on listener {}", l, x); } } } @@ -456,17 +463,21 @@ public abstract class SelectorManager extends ContainerLifeCycle implements Dump } catch (Throwable x) { - LOG.warn(x); + LOG.warn("Failed to notify onAccepted on listener {}", l, x); } } } + public interface SelectorManagerListener extends EventListener + { + } + /** *
A listener for accept events.
*This listener is called from either the selector or acceptor thread * and implementations must be non blocking and fast.
*/ - public interface AcceptListener extends EventListener + public interface AcceptListener extends SelectorManagerListener { /** * Called immediately after a new SelectableChannel is accepted, but diff --git a/jetty-io/src/main/java/org/eclipse/jetty/io/SocketChannelEndPoint.java b/jetty-io/src/main/java/org/eclipse/jetty/io/SocketChannelEndPoint.java index 249e8419d47..23809302b8c 100644 --- a/jetty-io/src/main/java/org/eclipse/jetty/io/SocketChannelEndPoint.java +++ b/jetty-io/src/main/java/org/eclipse/jetty/io/SocketChannelEndPoint.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.io; @@ -25,13 +25,13 @@ import java.nio.channels.SelectableChannel; import java.nio.channels.SelectionKey; import java.nio.channels.SocketChannel; -import org.eclipse.jetty.util.log.Log; -import org.eclipse.jetty.util.log.Logger; import org.eclipse.jetty.util.thread.Scheduler; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class SocketChannelEndPoint extends ChannelEndPoint { - private static final Logger LOG = Log.getLogger(SocketChannelEndPoint.class); + private static final Logger LOG = LoggerFactory.getLogger(SocketChannelEndPoint.class); private final Socket _socket; private final InetSocketAddress _local; private final InetSocketAddress _remote; @@ -77,7 +77,7 @@ public class SocketChannelEndPoint extends ChannelEndPoint } catch (IOException e) { - LOG.debug(e); + LOG.debug("Unable to shutdown output", e); } } } diff --git a/jetty-io/src/main/java/org/eclipse/jetty/io/WriteFlusher.java b/jetty-io/src/main/java/org/eclipse/jetty/io/WriteFlusher.java index 931052bc618..d75415dffee 100644 --- a/jetty-io/src/main/java/org/eclipse/jetty/io/WriteFlusher.java +++ b/jetty-io/src/main/java/org/eclipse/jetty/io/WriteFlusher.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.io; @@ -31,10 +31,10 @@ import java.util.concurrent.atomic.AtomicReference; import org.eclipse.jetty.util.BufferUtil; import org.eclipse.jetty.util.Callback; -import org.eclipse.jetty.util.log.Log; -import org.eclipse.jetty.util.log.Logger; import org.eclipse.jetty.util.thread.Invocable; import org.eclipse.jetty.util.thread.Invocable.InvocationType; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * A Utility class to help implement {@link EndPoint#write(Callback, ByteBuffer...)} by calling @@ -45,7 +45,7 @@ import org.eclipse.jetty.util.thread.Invocable.InvocationType; */ public abstract class WriteFlusher { - private static final Logger LOG = Log.getLogger(WriteFlusher.class); + private static final Logger LOG = LoggerFactory.getLogger(WriteFlusher.class); private static final boolean DEBUG = LOG.isDebugEnabled(); // Easy for the compiler to remove the code if DEBUG==false private static final ByteBuffer[] EMPTY_BUFFERS = new ByteBuffer[]{BufferUtil.EMPTY_BUFFER}; private static final EnumMapA listener of {@link WriteFlusher} events.
+ *A listener of {@link WriteFlusher} events. + * If implemented by a Connection class, the {@link #onFlushed(long)} event will be delivered to it.
*/ public interface Listener { diff --git a/jetty-io/src/main/java/org/eclipse/jetty/io/WriterOutputStream.java b/jetty-io/src/main/java/org/eclipse/jetty/io/WriterOutputStream.java index 126448c1cfc..589c34d7c62 100644 --- a/jetty-io/src/main/java/org/eclipse/jetty/io/WriterOutputStream.java +++ b/jetty-io/src/main/java/org/eclipse/jetty/io/WriterOutputStream.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.io; diff --git a/jetty-io/src/main/java/org/eclipse/jetty/io/package-info.java b/jetty-io/src/main/java/org/eclipse/jetty/io/package-info.java index f32f774ab72..fadd8c32b62 100644 --- a/jetty-io/src/main/java/org/eclipse/jetty/io/package-info.java +++ b/jetty-io/src/main/java/org/eclipse/jetty/io/package-info.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // /** diff --git a/jetty-io/src/main/java/org/eclipse/jetty/io/ssl/ALPNProcessor.java b/jetty-io/src/main/java/org/eclipse/jetty/io/ssl/ALPNProcessor.java index f25a50e05bd..b4fdbc82623 100644 --- a/jetty-io/src/main/java/org/eclipse/jetty/io/ssl/ALPNProcessor.java +++ b/jetty-io/src/main/java/org/eclipse/jetty/io/ssl/ALPNProcessor.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.io.ssl; diff --git a/jetty-io/src/main/java/org/eclipse/jetty/io/ssl/SslClientConnectionFactory.java b/jetty-io/src/main/java/org/eclipse/jetty/io/ssl/SslClientConnectionFactory.java index 45b0be514fd..8b03dad06e0 100644 --- a/jetty-io/src/main/java/org/eclipse/jetty/io/ssl/SslClientConnectionFactory.java +++ b/jetty-io/src/main/java/org/eclipse/jetty/io/ssl/SslClientConnectionFactory.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.io.ssl; @@ -46,7 +46,7 @@ public class SslClientConnectionFactory implements ClientConnectionFactory private final ClientConnectionFactory connectionFactory; private boolean _directBuffersForEncryption = true; private boolean _directBuffersForDecryption = true; - private boolean allowMissingCloseMessage = true; + private boolean _requireCloseMessage; public SslClientConnectionFactory(SslContextFactory sslContextFactory, ByteBufferPool byteBufferPool, Executor executor, ClientConnectionFactory connectionFactory) { @@ -56,6 +56,11 @@ public class SslClientConnectionFactory implements ClientConnectionFactory this.connectionFactory = connectionFactory; } + public ClientConnectionFactory getClientConnectionFactory() + { + return connectionFactory; + } + public void setDirectBuffersForEncryption(boolean useDirectBuffers) { this._directBuffersForEncryption = useDirectBuffers; @@ -76,14 +81,22 @@ public class SslClientConnectionFactory implements ClientConnectionFactory return _directBuffersForEncryption; } - public boolean isAllowMissingCloseMessage() + /** + * @return whether peers must send the TLS {@code close_notify} message + * @see SslConnection#isRequireCloseMessage() + */ + public boolean isRequireCloseMessage() { - return allowMissingCloseMessage; + return _requireCloseMessage; } - public void setAllowMissingCloseMessage(boolean allowMissingCloseMessage) + /** + * @param requireCloseMessage whether peers must send the TLS {@code close_notify} message + * @see SslConnection#setRequireCloseMessage(boolean) + */ + public void setRequireCloseMessage(boolean requireCloseMessage) { - this.allowMissingCloseMessage = allowMissingCloseMessage; + _requireCloseMessage = requireCloseMessage; } @Override @@ -95,7 +108,6 @@ public class SslClientConnectionFactory implements ClientConnectionFactory context.put(SSL_ENGINE_CONTEXT_KEY, engine); SslConnection sslConnection = newSslConnection(byteBufferPool, executor, endPoint, engine); - endPoint.setConnection(sslConnection); EndPoint appEndPoint = sslConnection.getDecryptedEndPoint(); appEndPoint.setConnection(connectionFactory.newConnection(appEndPoint, context)); @@ -119,7 +131,7 @@ public class SslClientConnectionFactory implements ClientConnectionFactory SslConnection sslConnection = (SslConnection)connection; sslConnection.setRenegotiationAllowed(sslContextFactory.isRenegotiationAllowed()); sslConnection.setRenegotiationLimit(sslContextFactory.getRenegotiationLimit()); - sslConnection.setAllowMissingCloseMessage(isAllowMissingCloseMessage()); + sslConnection.setRequireCloseMessage(isRequireCloseMessage()); ContainerLifeCycle client = (ContainerLifeCycle)context.get(ClientConnectionFactory.CLIENT_CONTEXT_KEY); if (client != null) client.getBeans(SslHandshakeListener.class).forEach(sslConnection::addHandshakeListener); diff --git a/jetty-io/src/main/java/org/eclipse/jetty/io/ssl/SslConnection.java b/jetty-io/src/main/java/org/eclipse/jetty/io/ssl/SslConnection.java index 35f603caa35..a23e92e9e9f 100644 --- a/jetty-io/src/main/java/org/eclipse/jetty/io/ssl/SslConnection.java +++ b/jetty-io/src/main/java/org/eclipse/jetty/io/ssl/SslConnection.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.io.ssl; @@ -25,12 +25,14 @@ import java.util.ArrayList; import java.util.List; import java.util.concurrent.Executor; import java.util.concurrent.atomic.AtomicReference; +import java.util.function.ToIntFunction; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLEngineResult; import javax.net.ssl.SSLEngineResult.HandshakeStatus; import javax.net.ssl.SSLEngineResult.Status; import javax.net.ssl.SSLException; import javax.net.ssl.SSLHandshakeException; +import javax.net.ssl.SSLSession; import org.eclipse.jetty.io.AbstractConnection; import org.eclipse.jetty.io.AbstractEndPoint; @@ -41,9 +43,9 @@ import org.eclipse.jetty.io.WriteFlusher; import org.eclipse.jetty.util.BufferUtil; import org.eclipse.jetty.util.Callback; import org.eclipse.jetty.util.StringUtil; -import org.eclipse.jetty.util.log.Log; -import org.eclipse.jetty.util.log.Logger; import org.eclipse.jetty.util.thread.Invocable; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * A Connection that acts as an interceptor between an EndPoint providing SSL encrypted data @@ -77,12 +79,13 @@ import org.eclipse.jetty.util.thread.Invocable; */ public class SslConnection extends AbstractConnection implements Connection.UpgradeTo { - private static final Logger LOG = Log.getLogger(SslConnection.class); + private static final Logger LOG = LoggerFactory.getLogger(SslConnection.class); private static final String TLS_1_3 = "TLSv1.3"; - private enum Handshake + private enum HandshakeState { INITIAL, + HANDSHAKE, SUCCEEDED, FAILED } @@ -113,10 +116,10 @@ public class SslConnection extends AbstractConnection implements Connection.Upgr private boolean _renegotiationAllowed; private int _renegotiationLimit = -1; private boolean _closedOutbound; - private boolean _allowMissingCloseMessage = true; + private boolean _requireCloseMessage; private FlushState _flushState = FlushState.IDLE; private FillState _fillState = FillState.IDLE; - private AtomicReferenceSets whether it is required that a peer send the TLS {@code close_notify} message + * to indicate the will to close the connection, otherwise it may be interpreted as a + * truncation attack.
+ *This option is only useful on clients, since typically servers cannot accept + * connection-delimited content that may be truncated.
+ * + * @param requireCloseMessage whether peers must send the TLS {@code close_notify} message + */ + public void setRequireCloseMessage(boolean requireCloseMessage) { - this._allowMissingCloseMessage = allowMissingCloseMessage; + _requireCloseMessage = requireCloseMessage; + } + + private boolean isHandshakeInitial() + { + return _handshake.get() == HandshakeState.INITIAL; + } + + private boolean isHandshakeSucceeded() + { + return _handshake.get() == HandshakeState.SUCCEEDED; + } + + private boolean isHandshakeComplete() + { + HandshakeState state = _handshake.get(); + return state == HandshakeState.SUCCEEDED || state == HandshakeState.FAILED; + } + + private int getApplicationBufferSize() + { + return getBufferSize(SSLSession::getApplicationBufferSize); + } + + private int getPacketBufferSize() + { + return getBufferSize(SSLSession::getPacketBufferSize); + } + + private int getBufferSize(ToIntFunctionCallback method invoked when the TLS handshake succeeds.
* * @param event the event object carrying information about the TLS handshake event + * @throws SSLException if any error happen during handshake */ default void handshakeSucceeded(Event event) throws SSLException { diff --git a/jetty-io/src/main/java/org/eclipse/jetty/io/ssl/package-info.java b/jetty-io/src/main/java/org/eclipse/jetty/io/ssl/package-info.java index 42403dc5dfe..49ddb335d5a 100644 --- a/jetty-io/src/main/java/org/eclipse/jetty/io/ssl/package-info.java +++ b/jetty-io/src/main/java/org/eclipse/jetty/io/ssl/package-info.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // /** diff --git a/jetty-io/src/test/java/org/eclipse/jetty/io/ArrayByteBufferPoolTest.java b/jetty-io/src/test/java/org/eclipse/jetty/io/ArrayByteBufferPoolTest.java index 57d6b496a6d..0f290c12800 100644 --- a/jetty-io/src/test/java/org/eclipse/jetty/io/ArrayByteBufferPoolTest.java +++ b/jetty-io/src/test/java/org/eclipse/jetty/io/ArrayByteBufferPoolTest.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.io; diff --git a/jetty-io/src/test/java/org/eclipse/jetty/io/ByteArrayEndPointTest.java b/jetty-io/src/test/java/org/eclipse/jetty/io/ByteArrayEndPointTest.java index 01dc31af16f..0df2d34c233 100644 --- a/jetty-io/src/test/java/org/eclipse/jetty/io/ByteArrayEndPointTest.java +++ b/jetty-io/src/test/java/org/eclipse/jetty/io/ByteArrayEndPointTest.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.io; diff --git a/jetty-io/src/test/java/org/eclipse/jetty/io/CyclicTimeoutTest.java b/jetty-io/src/test/java/org/eclipse/jetty/io/CyclicTimeoutTest.java index e9438fd43d8..fc002a72b6e 100644 --- a/jetty-io/src/test/java/org/eclipse/jetty/io/CyclicTimeoutTest.java +++ b/jetty-io/src/test/java/org/eclipse/jetty/io/CyclicTimeoutTest.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.io; @@ -146,10 +146,10 @@ public class CyclicTimeoutTest QueuedThreadPool pool = new QueuedThreadPool(200); pool.start(); - long test_until = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(1500); + long testUntil = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(1500); assertTrue(_timeout.schedule(100, TimeUnit.MILLISECONDS)); - while (System.nanoTime() < test_until) + while (System.nanoTime() < testUntil) { CountDownLatch latch = new CountDownLatch(1); pool.execute(() -> diff --git a/jetty-io/src/test/java/org/eclipse/jetty/io/IOTest.java b/jetty-io/src/test/java/org/eclipse/jetty/io/IOTest.java index a9b198eaced..493eea69f9b 100644 --- a/jetty-io/src/test/java/org/eclipse/jetty/io/IOTest.java +++ b/jetty-io/src/test/java/org/eclipse/jetty/io/IOTest.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.io; @@ -43,6 +43,7 @@ import java.util.concurrent.TimeUnit; import org.eclipse.jetty.toolchain.test.MavenTestingUtils; import org.eclipse.jetty.util.BufferUtil; import org.eclipse.jetty.util.IO; +import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.OS; @@ -53,7 +54,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; public class IOTest { @@ -93,14 +93,8 @@ public class IOTest assertEquals(-1, server.getInputStream().read()); // but cannot write - try - { - client.getOutputStream().write(1); - fail("exception expected"); - } - catch (SocketException expected) - { - } + Assertions.assertThrows(SocketException.class, () -> client.getOutputStream().write(1)); + // but can still write in opposite direction. server.getOutputStream().write(1); @@ -110,14 +104,7 @@ public class IOTest server.shutdownInput(); // now we EOF instead of reading -1 - try - { - server.getInputStream().read(); - fail("exception expected"); - } - catch (SocketException expected) - { - } + Assertions.assertThrows(SocketException.class, () -> server.getInputStream().read()); // but can still write in opposite direction. server.getOutputStream().write(1); @@ -127,14 +114,7 @@ public class IOTest client.shutdownInput(); // now we EOF instead of reading -1 - try - { - client.getInputStream().read(); - fail("exception expected"); - } - catch (SocketException expected) - { - } + Assertions.assertThrows(SocketException.class, () -> client.getInputStream().read()); // But we can still write at the server (data which will never be read) server.getOutputStream().write(1); @@ -146,14 +126,7 @@ public class IOTest server.shutdownOutput(); // and now we can't write - try - { - server.getOutputStream().write(1); - fail("exception expected"); - } - catch (SocketException expected) - { - } + Assertions.assertThrows(SocketException.class, () -> server.getOutputStream().write(1)); // but the sockets are still open assertFalse(client.isClosed()); diff --git a/jetty-io/src/test/java/org/eclipse/jetty/io/IdleTimeoutTest.java b/jetty-io/src/test/java/org/eclipse/jetty/io/IdleTimeoutTest.java index 31881fa559d..0ce738e637c 100644 --- a/jetty-io/src/test/java/org/eclipse/jetty/io/IdleTimeoutTest.java +++ b/jetty-io/src/test/java/org/eclipse/jetty/io/IdleTimeoutTest.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.io; diff --git a/jetty-io/src/test/java/org/eclipse/jetty/io/MappedByteBufferPoolTest.java b/jetty-io/src/test/java/org/eclipse/jetty/io/MappedByteBufferPoolTest.java index 5bd536b48cf..16e20928e78 100644 --- a/jetty-io/src/test/java/org/eclipse/jetty/io/MappedByteBufferPoolTest.java +++ b/jetty-io/src/test/java/org/eclipse/jetty/io/MappedByteBufferPoolTest.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.io; diff --git a/jetty-io/src/test/java/org/eclipse/jetty/io/NIOTest.java b/jetty-io/src/test/java/org/eclipse/jetty/io/NIOTest.java index 3dd1a65f5b1..1540ae9818f 100644 --- a/jetty-io/src/test/java/org/eclipse/jetty/io/NIOTest.java +++ b/jetty-io/src/test/java/org/eclipse/jetty/io/NIOTest.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.io; diff --git a/jetty-io/src/test/java/org/eclipse/jetty/io/SelectorManagerTest.java b/jetty-io/src/test/java/org/eclipse/jetty/io/SelectorManagerTest.java index 0c3845616fd..5d3ca7e2772 100644 --- a/jetty-io/src/test/java/org/eclipse/jetty/io/SelectorManagerTest.java +++ b/jetty-io/src/test/java/org/eclipse/jetty/io/SelectorManagerTest.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.io; diff --git a/jetty-io/src/test/java/org/eclipse/jetty/io/SocketChannelEndPointInterestsTest.java b/jetty-io/src/test/java/org/eclipse/jetty/io/SocketChannelEndPointInterestsTest.java index cebf4594434..3ee35a3f160 100644 --- a/jetty-io/src/test/java/org/eclipse/jetty/io/SocketChannelEndPointInterestsTest.java +++ b/jetty-io/src/test/java/org/eclipse/jetty/io/SocketChannelEndPointInterestsTest.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.io; diff --git a/jetty-io/src/test/java/org/eclipse/jetty/io/SocketChannelEndPointOpenCloseTest.java b/jetty-io/src/test/java/org/eclipse/jetty/io/SocketChannelEndPointOpenCloseTest.java index b3fa6288093..5d6feb44f63 100644 --- a/jetty-io/src/test/java/org/eclipse/jetty/io/SocketChannelEndPointOpenCloseTest.java +++ b/jetty-io/src/test/java/org/eclipse/jetty/io/SocketChannelEndPointOpenCloseTest.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.io; diff --git a/jetty-io/src/test/java/org/eclipse/jetty/io/SocketChannelEndPointTest.java b/jetty-io/src/test/java/org/eclipse/jetty/io/SocketChannelEndPointTest.java index 7970e1e0e8c..537174b8625 100644 --- a/jetty-io/src/test/java/org/eclipse/jetty/io/SocketChannelEndPointTest.java +++ b/jetty-io/src/test/java/org/eclipse/jetty/io/SocketChannelEndPointTest.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.io; @@ -48,8 +48,6 @@ import org.eclipse.jetty.toolchain.test.MavenTestingUtils; import org.eclipse.jetty.util.BufferUtil; import org.eclipse.jetty.util.Callback; import org.eclipse.jetty.util.FutureCallback; -import org.eclipse.jetty.util.log.Log; -import org.eclipse.jetty.util.log.Logger; import org.eclipse.jetty.util.ssl.SslContextFactory; import org.eclipse.jetty.util.thread.QueuedThreadPool; import org.eclipse.jetty.util.thread.Scheduler; @@ -62,6 +60,8 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.greaterThan; @@ -75,7 +75,7 @@ import static org.junit.jupiter.api.Assertions.fail; @SuppressWarnings("Duplicates") public class SocketChannelEndPointTest { - private static final Logger LOG = Log.getLogger(SocketChannelEndPoint.class); + private static final Logger LOG = LoggerFactory.getLogger(SocketChannelEndPoint.class); public interface Scenario { @@ -630,10 +630,9 @@ public class SocketChannelEndPointTest public SslScenario(NormalScenario normalScenario) throws Exception { _normalScenario = normalScenario; - File keystore = MavenTestingUtils.getTestResourceFile("keystore"); + File keystore = MavenTestingUtils.getTestResourceFile("keystore.p12"); _sslCtxFactory.setKeyStorePath(keystore.getAbsolutePath()); _sslCtxFactory.setKeyStorePassword("storepwd"); - _sslCtxFactory.setKeyManagerPassword("keypwd"); _sslCtxFactory.start(); } @@ -674,7 +673,7 @@ public class SocketChannelEndPointTest @SuppressWarnings("Duplicates") public static class TestConnection extends AbstractConnection { - private static final Logger LOG = Log.getLogger(TestConnection.class); + private static final Logger LOG = LoggerFactory.getLogger(TestConnection.class); volatile FutureCallback _blockingRead; final AtomicInteger _blockAt; @@ -744,7 +743,7 @@ public class SocketChannelEndPointTest return; } - EndPoint _endp = getEndPoint(); + EndPoint endp = getEndPoint(); try { _last = TimeUnit.NANOSECONDS.toMillis(System.nanoTime()); @@ -757,17 +756,17 @@ public class SocketChannelEndPointTest BufferUtil.compact(_in); if (BufferUtil.isFull(_in)) throw new IllegalStateException("FULL " + BufferUtil.toDetailString(_in)); - int filled = _endp.fill(_in); + int filled = endp.fill(_in); if (filled > 0) progress = true; // If the tests wants to block, then block - while (_blockAt.get() > 0 && _endp.isOpen() && _in.remaining() < _blockAt.get()) + while (_blockAt.get() > 0 && endp.isOpen() && _in.remaining() < _blockAt.get()) { FutureCallback future = _blockingRead = new FutureCallback(); fillInterested(); future.get(); - filled = _endp.fill(_in); + filled = endp.fill(_in); progress |= filled > 0; } @@ -783,18 +782,18 @@ public class SocketChannelEndPointTest for (int i = 0; i < _writeCount.get(); i++) { FutureCallback blockingWrite = new FutureCallback(); - _endp.write(blockingWrite, out.asReadOnlyBuffer()); + endp.write(blockingWrite, out.asReadOnlyBuffer()); blockingWrite.get(); } progress = true; } // are we done? - if (_endp.isInputShutdown()) - _endp.shutdownOutput(); + if (endp.isInputShutdown()) + endp.shutdownOutput(); } - if (_endp.isOpen()) + if (endp.isOpen()) fillInterested(); } catch (ExecutionException e) @@ -803,9 +802,9 @@ public class SocketChannelEndPointTest try { FutureCallback blockingWrite = new FutureCallback(); - _endp.write(blockingWrite, BufferUtil.toBuffer("EE: " + BufferUtil.toString(_in))); + endp.write(blockingWrite, BufferUtil.toBuffer("EE: " + BufferUtil.toString(_in))); blockingWrite.get(); - _endp.shutdownOutput(); + endp.shutdownOutput(); } catch (Exception e2) { @@ -815,13 +814,13 @@ public class SocketChannelEndPointTest catch (InterruptedException | EofException e) { if (LOG.isDebugEnabled()) - LOG.debug(e); + LOG.debug("Fill interrupted", e); else LOG.info(e.getClass().getName()); } catch (Exception e) { - LOG.warn(e); + LOG.warn("Unable to fill from endpoint", e); } } } diff --git a/jetty-io/src/test/java/org/eclipse/jetty/io/SslConnectionTest.java b/jetty-io/src/test/java/org/eclipse/jetty/io/SslConnectionTest.java index 92395418ceb..3ad5bdd737e 100644 --- a/jetty-io/src/test/java/org/eclipse/jetty/io/SslConnectionTest.java +++ b/jetty-io/src/test/java/org/eclipse/jetty/io/SslConnectionTest.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.io; @@ -42,7 +42,6 @@ import org.eclipse.jetty.io.ssl.SslConnection; import org.eclipse.jetty.toolchain.test.MavenTestingUtils; import org.eclipse.jetty.util.BufferUtil; import org.eclipse.jetty.util.FutureCallback; -import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.ssl.SslContextFactory; import org.eclipse.jetty.util.thread.QueuedThreadPool; import org.eclipse.jetty.util.thread.Scheduler; @@ -50,6 +49,8 @@ import org.eclipse.jetty.util.thread.TimerScheduler; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; @@ -60,6 +61,8 @@ import static org.junit.jupiter.api.Assertions.assertTrue; public class SslConnectionTest { + private static final Logger LOG = LoggerFactory.getLogger(SslConnectionTest.class); + private static final int TIMEOUT = 1000000; private static ByteBufferPool __byteBufferPool = new LeakTrackingByteBufferPool(new MappedByteBufferPool.Tagged()); @@ -141,10 +144,9 @@ public class SslConnectionTest @BeforeEach public void initSSL() throws Exception { - File keystore = MavenTestingUtils.getTestResourceFile("keystore"); + File keystore = MavenTestingUtils.getTestResourceFile("keystore.p12"); _sslCtxFactory.setKeyStorePath(keystore.getAbsolutePath()); _sslCtxFactory.setKeyStorePassword("storepwd"); - _sslCtxFactory.setKeyManagerPassword("keypwd"); _sslCtxFactory.setRenegotiationAllowed(true); _sslCtxFactory.setRenegotiationLimit(-1); startManager(); @@ -251,11 +253,11 @@ public class SslConnectionTest } catch (InterruptedException | EofException e) { - Log.getRootLogger().ignore(e); + LOG.trace("IGNORED", e); } catch (Exception e) { - Log.getRootLogger().warn(e); + LOG.warn("During onFillable", e); } finally { @@ -460,6 +462,7 @@ public class SslConnectionTest } catch (SocketTimeoutException e) { + // no op } assertTrue(__onIncompleteFlush.get()); @@ -483,9 +486,6 @@ public class SslConnectionTest server.configureBlocking(false); _manager.accept(server); - //__startBlocking.set(5); - //__blockFor.set(3); - client.getOutputStream().write("Short".getBytes(StandardCharsets.UTF_8)); byte[] buffer = new byte[1024]; int len = client.getInputStream().read(buffer); @@ -506,13 +506,14 @@ public class SslConnectionTest } catch (SocketTimeoutException e) { + // no op } __blockFor.set(0); assertTrue(__onIncompleteFlush.get()); ((TestEP)_lastEndp).getWriteFlusher().completeWrite(); len = client.getInputStream().read(buffer); - assertThat(len, is(len)); + assertThat(len, is(-1)); } } } diff --git a/jetty-io/src/test/java/org/eclipse/jetty/io/SslEngineBehaviorTest.java b/jetty-io/src/test/java/org/eclipse/jetty/io/SslEngineBehaviorTest.java index d4b475b2969..24742f85de2 100644 --- a/jetty-io/src/test/java/org/eclipse/jetty/io/SslEngineBehaviorTest.java +++ b/jetty-io/src/test/java/org/eclipse/jetty/io/SslEngineBehaviorTest.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.io; @@ -44,10 +44,9 @@ public class SslEngineBehaviorTest public static void startSsl() throws Exception { sslCtxFactory = new SslContextFactory.Server(); - File keystore = MavenTestingUtils.getTestResourceFile("keystore"); + File keystore = MavenTestingUtils.getTestResourceFile("keystore.p12"); sslCtxFactory.setKeyStorePath(keystore.getAbsolutePath()); sslCtxFactory.setKeyStorePassword("storepwd"); - sslCtxFactory.setKeyManagerPassword("keypwd"); sslCtxFactory.start(); } diff --git a/jetty-io/src/test/java/org/eclipse/jetty/io/WriteFlusherTest.java b/jetty-io/src/test/java/org/eclipse/jetty/io/WriteFlusherTest.java index 7a062d9b72a..c2fbc7f91ee 100644 --- a/jetty-io/src/test/java/org/eclipse/jetty/io/WriteFlusherTest.java +++ b/jetty-io/src/test/java/org/eclipse/jetty/io/WriteFlusherTest.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.io; @@ -32,10 +32,10 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; +import org.eclipse.jetty.logging.StacklessLogging; import org.eclipse.jetty.util.BufferUtil; import org.eclipse.jetty.util.Callback; import org.eclipse.jetty.util.FutureCallback; -import org.eclipse.jetty.util.log.StacklessLogging; import org.hamcrest.Matchers; import org.junit.jupiter.api.Test; diff --git a/jetty-io/src/test/resources/jetty-logging.properties b/jetty-io/src/test/resources/jetty-logging.properties index 257743ed54b..a83221a9354 100644 --- a/jetty-io/src/test/resources/jetty-logging.properties +++ b/jetty-io/src/test/resources/jetty-logging.properties @@ -1,5 +1,5 @@ -org.eclipse.jetty.util.log.class=org.eclipse.jetty.util.log.StdErrLog -org.eclipse.jetty.LEVEL=INFO +# Jetty Logging using jetty-slf4j-impl +#org.eclipse.jetty.LEVEL=DEBUG #org.eclipse.jetty.io.AbstractConnection.LEVEL=DEBUG #org.eclipse.jetty.io.ManagedSelector.LEVEL=DEBUG #org.eclipse.jetty.io.ssl.SslConnection.LEVEL=DEBUG diff --git a/jetty-io/src/test/resources/keystore b/jetty-io/src/test/resources/keystore deleted file mode 100644 index b727bd0fb77..00000000000 Binary files a/jetty-io/src/test/resources/keystore and /dev/null differ diff --git a/jetty-io/src/test/resources/keystore.p12 b/jetty-io/src/test/resources/keystore.p12 new file mode 100644 index 00000000000..db99d3d2734 Binary files /dev/null and b/jetty-io/src/test/resources/keystore.p12 differ diff --git a/jetty-jaas/pom.xml b/jetty-jaas/pom.xml index 6662377bb20..0645ecf6288 100644 --- a/jetty-jaas/pom.xml +++ b/jetty-jaas/pom.xml @@ -42,13 +42,17 @@LifeCycle wrapper for JMXConnectorServer.
@@ -61,7 +61,7 @@ import org.eclipse.jetty.util.thread.ShutdownThread; public class ConnectorServer extends AbstractLifeCycle { public static final String RMI_REGISTRY_CLIENT_SOCKET_FACTORY_ATTRIBUTE = "com.sun.jndi.rmi.factory.socket"; - private static final Logger LOG = Log.getLogger(ConnectorServer.class); + private static final Logger LOG = LoggerFactory.getLogger(ConnectorServer.class); private JMXServiceURL _jmxURL; private final MapA dynamic MBean that can wrap an arbitrary Object instance.
@@ -44,7 +44,7 @@ import org.eclipse.jetty.util.log.Logger; */ public class ObjectMBean implements DynamicMBean { - private static final Logger LOG = Log.getLogger(ObjectMBean.class); + private static final Logger LOG = LoggerFactory.getLogger(ObjectMBean.class); protected final Object _managed; private MetaData _metaData; @@ -154,7 +154,7 @@ public class ObjectMBean implements DynamicMBean catch (Throwable x) { if (LOG.isDebugEnabled()) - LOG.debug(x); + LOG.debug("Unable to get attribute {}", name, x); } } return results; @@ -188,7 +188,7 @@ public class ObjectMBean implements DynamicMBean catch (Throwable x) { if (LOG.isDebugEnabled()) - LOG.debug(x); + LOG.debug("Unable to get Attribute {}", attribute, x); } } return results; diff --git a/jetty-jmx/src/main/java/org/eclipse/jetty/jmx/package-info.java b/jetty-jmx/src/main/java/org/eclipse/jetty/jmx/package-info.java index 4a14bafe9b5..76703787e01 100644 --- a/jetty-jmx/src/main/java/org/eclipse/jetty/jmx/package-info.java +++ b/jetty-jmx/src/main/java/org/eclipse/jetty/jmx/package-info.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // /** diff --git a/jetty-jmx/src/main/java/org/eclipse/jetty/util/log/jmx/LogMBean.java b/jetty-jmx/src/main/java/org/eclipse/jetty/util/log/jmx/LogMBean.java deleted file mode 100644 index d3f447bad6c..00000000000 --- a/jetty-jmx/src/main/java/org/eclipse/jetty/util/log/jmx/LogMBean.java +++ /dev/null @@ -1,60 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. -// -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html -// -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php -// -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== -// - -package org.eclipse.jetty.util.log.jmx; - -import java.util.ArrayList; -import java.util.List; - -import org.eclipse.jetty.jmx.ObjectMBean; -import org.eclipse.jetty.util.annotation.ManagedAttribute; -import org.eclipse.jetty.util.annotation.ManagedObject; -import org.eclipse.jetty.util.annotation.ManagedOperation; -import org.eclipse.jetty.util.annotation.Name; -import org.eclipse.jetty.util.log.Log; - -/** - * - */ -@ManagedObject("Jetty Logging") -public class LogMBean extends ObjectMBean -{ - public LogMBean(Object managedObject) - { - super(managedObject); - } - - @ManagedAttribute(value = "list of instantiated loggers") - public ListGreetingService
.
+ */
+public interface GreetingServiceAsync
+{
+ void greetServer(String input, AsyncCallbackGreetingService
.
- */
-public interface GreetingServiceAsync
-{
- void greetServer(String input, AsyncCallback- * Determines whether or not the server blocks when started. The default - * behavior (false) will cause the server to pause other processes - * while it continues to handle web requests. This is useful when starting the - * server with the intent to work with it interactively. This is the - * behaviour of the jetty:run, jetty:run-war, jetty:run-war-exploded goals. - *
- * If true, the server will not block the execution of subsequent code. This - * is the behaviour of the jetty:start and default behaviour of the jetty:deploy goals. - *
- */ - @Parameter(defaultValue = "false") - protected boolean nonBlocking = false; - - /** - * Per default this goal support onlywar
packaging.
- * If your project use an other type please configure it here.
- */
- @Parameter
- protected Listwar
packaging.
+ */
+ @Parameter
+ protected List- * This goal is used to run Jetty with a pre-assembled war. - *
- *- * It accepts exactly the same options as the run-war goal. - * However, it doesn't assume that the current artifact is a - * webapp and doesn't try to assemble it into a war before its execution. - * So using it makes sense only when used in conjunction with the - * war configuration parameter pointing to a pre-built WAR. - *
- *- * This goal is useful e.g. for launching a web app in Jetty as a target for unit-tested - * HTTP client components. - *
- * Deploy a pre-assembled war - */ -@Mojo(name = "deploy-war", requiresDependencyResolution = ResolutionScope.RUNTIME) -@Execute(phase = LifecyclePhase.VALIDATE) -public class JettyDeployWar extends JettyRunWarMojo -{ - /** - * If true, the plugin should continue and not block. Otherwise the - * plugin will block further execution and you will need to use - * cntrl-c to stop it. - */ - @Parameter(property = "jetty.daemon", defaultValue = "true") - protected boolean daemon = true; - - @Override - public void execute() throws MojoExecutionException, MojoFailureException - { - nonBlocking = daemon; - super.execute(); - } - - @Override - public void finishConfigurationBeforeStart() throws Exception - { - super.finishConfigurationBeforeStart(); - //only stop the server at shutdown if we are blocking - server.setStopAtShutdown(!nonBlocking); - } -} diff --git a/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/JettyDistroForker.java b/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/JettyDistroForker.java new file mode 100644 index 00000000000..641662cc9b4 --- /dev/null +++ b/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/JettyDistroForker.java @@ -0,0 +1,409 @@ +// +// ======================================================================== +// 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.maven.plugin; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.URI; +import java.nio.file.FileAlreadyExistsException; +import java.nio.file.FileSystems; +import java.nio.file.FileVisitOption; +import java.nio.file.FileVisitResult; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.SimpleFileVisitor; +import java.nio.file.attribute.BasicFileAttributes; +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.List; +import java.util.Map; + +import org.eclipse.jetty.util.IO; +import org.eclipse.jetty.util.StringUtil; +import org.eclipse.jetty.util.TypeUtil; +import org.eclipse.jetty.util.resource.JarResource; +import org.eclipse.jetty.util.resource.Resource; + +/** + * JettyDistroForker + * + * Unpacks a jetty distribution and configures it with a base that allows it + * to run an unassembled webapp. + */ +public class JettyDistroForker extends AbstractForker +{ + protected MavenWebAppContext webApp; + + protected String contextXml; + + /** + * Location of existing jetty home directory + */ + protected File jettyHome; + + /** + * Zip of jetty distro + */ + protected File jettyDistro; + + /** + * Location of existing jetty base directory + */ + protected File jettyBase; + + protected File baseDir; + + /** + * Optional list of other modules to + * activate. + */ + protected String[] modules; + + protected List- * You need to define a jetty.xml file to configure connectors etc. You can use the normal setters of o.e.j.webapp.WebAppContext on the webApp - * configuration element for this plugin. You may also need context xml file for any particularly complex webapp setup. - * - *
- * Unlike the other jetty goals, this does NOT support the scanIntervalSeconds parameter: the webapp will be deployed only once. - *
- * The stopKey, stopPort configuration elements can be used to control the stopping of the forked process. By default, this plugin will launch - * the forked jetty instance and wait for it to complete (in which case it acts much like the jetty:run goal, and you will need to Cntrl-C to stop). - * By setting the configuration element waitForChild to false, the plugin will terminate after having forked the jetty process. In this case - * you can use the jetty:stop goal to terminate the process. - *
- * See http://www.eclipse.org/jetty/documentation for more information on this and other jetty plugins.
- *
- * Runs Jetty in forked JVM on an unassembled webapp
- */
-@Mojo(name = "run-forked", requiresDependencyResolution = ResolutionScope.TEST)
-@Execute(phase = LifecyclePhase.TEST_COMPILE)
-public class JettyRunForkedMojo extends JettyRunMojo
-{
- /**
- * The target directory
- */
- @Parameter(defaultValue = "${project.build.directory}", readonly = true, required = true)
- protected File target;
-
- /**
- * The file into which to generate the quickstart web xml for the forked process to use
- */
- @Parameter(defaultValue = "${project.build.directory}/fork-web.xml")
- protected File forkWebXml;
-
- /**
- * Arbitrary jvm args to pass to the forked process
- */
- @Parameter(property = "jetty.jvmArgs")
- private String jvmArgs;
-
- /**
- * Optional list of jetty properties to put on the command line
- */
- @Parameter
- private String[] jettyProperties;
-
- @Parameter(defaultValue = "${plugin.artifacts}", readonly = true)
- private List
- * The plugin forks a parallel lifecycle to ensure that the "compile" phase has been completed before invoking Jetty. This means
- * that you do not need to explicitly execute a "mvn compile" first. It also means that a "mvn clean jetty:run" will ensure that
- * a full fresh compile is done before invoking Jetty.
- *
- * Once invoked, the plugin can be configured to run continuously, scanning for changes in the project and automatically performing a
- * hot redeploy when necessary. This allows the developer to concentrate on coding changes to the project using their IDE of choice and have those changes
- * immediately and transparently reflected in the running web container, eliminating development time that is wasted on rebuilding, reassembling and redeploying.
- *
- * You may also specify the location of a jetty.xml file whose contents will be applied before any plugin configuration.
- * This can be used, for example, to deploy a static webapp that is not part of your maven build.
- *
- * There is a reference guide to the configuration parameters for this plugin.
- *
- * Runs jetty directly from a maven project
+ * This goal is used in-situ on a Maven project without first requiring that the project
+ * is assembled into a war, saving time during the development cycle.
+ *
+ * The plugin runs a parallel lifecycle to ensure that the "test-compile" phase has been completed before invoking Jetty. This means
+ * that you do not need to explicity execute a "mvn compile" first. It also means that a "mvn clean jetty:run" will ensure that
+ * a full fresh compile is done before invoking Jetty.
+ *
+ * Once invoked, the plugin can be configured to run continuously, scanning for changes in the project and automatically performing a
+ * hot redeploy when necessary. This allows the developer to concentrate on coding changes to the project using their IDE of choice and have those changes
+ * immediately and transparently reflected in the running web container, eliminating development time that is wasted on rebuilding, reassembling and redeploying.
+ * Alternatively, you can configure the plugin to wait for an <enter> at the command line to manually control redeployment.
+ *
+ * You can configure this goal to run your unassembled webapp either in-process with maven, or forked into a new process, or deployed into a
+ * jetty distribution.
*/
-@Mojo(name = "run", requiresDependencyResolution = ResolutionScope.TEST)
-@Execute(phase = LifecyclePhase.TEST_COMPILE)
-public class JettyRunMojo extends AbstractJettyMojo
+@Mojo (name = "run", requiresDependencyResolution = ResolutionScope.TEST)
+@Execute (phase = LifecyclePhase.TEST_COMPILE)
+public class JettyRunMojo extends AbstractUnassembledWebAppMojo
{
- public static final String DEFAULT_WEBAPP_SRC = "src" + File.separator + "main" + File.separator + "webapp";
- public static final String FAKE_WEBAPP = "webapp-tmp";
-
+ //Start of parameters only valid for runType=inprocess
/**
- * If true, the <testOutputDirectory>
- * and the dependencies of <scope>test<scope>
- * will be put first on the runtime classpath.
+ * The interval in seconds to pause before checking if changes
+ * have occurred and re-deploying as necessary. A value
+ * of 0 indicates no re-deployment will be done. In that case, you
+ * can force redeployment by typing a linefeed character at the command line.
*/
- @Parameter(alias = "useTestClasspath", defaultValue = "false")
- protected boolean useTestScope;
-
+ @Parameter(defaultValue = "0", property = "jetty.scan", required = true)
+ protected int scan;
+
/**
- * The default location of the web.xml file. Will be used
- * if <webApp><descriptor> is not set.
+ * Scanner to check for files changes to cause redeploy
*/
- @Parameter(defaultValue = "${maven.war.webxml}", readonly = true)
- protected String webXml;
-
+ protected Scanner scanner;
+
/**
- * The directory containing generated classes.
+ * Only one of the following will be used, depending the mode
+ * the mojo is started in: EMBED, FORK, DISTRO
*/
- @Parameter(defaultValue = "${project.build.outputDirectory}", required = true)
- protected File classesDirectory;
+ protected JettyEmbedder embedder;
+ protected JettyForker forker;
+ protected JettyDistroForker distroForker;
- /**
- * An optional pattern for includes/excludes of classes in the classesDirectory
- */
- @Parameter
- protected ScanPattern scanClassesPattern;
-
- /**
- * The directory containing generated test classes.
- */
- @Parameter(defaultValue = "${project.build.testOutputDirectory}", required = true)
- protected File testClassesDirectory;
-
- /**
- * An optional pattern for includes/excludes of classes in the testClassesDirectory
- */
- @Parameter
- protected ScanPattern scanTestClassesPattern;
-
- /**
- * Root directory for all html/jsp etc files
- */
- @Parameter(defaultValue = "${maven.war.src}")
- protected File webAppSourceDirectory;
-
- /**
- * List of files or directories to additionally periodically scan for changes. Optional.
- */
- @Parameter
- protected File[] scanTargets;
-
- /**
- * List of directories with ant-style <include> and <exclude> patterns
- * for extra targets to periodically scan for changes. Can be used instead of,
- * or in conjunction with <scanTargets>.Optional.
- */
- @Parameter
- protected ScanTargetPattern[] scanTargetPatterns;
-
- /**
- * maven-war-plugin reference
- */
- protected WarPluginInfo warPluginInfo;
-
- /**
- * List of deps that are wars
- */
- protected List
- * This goal is used to assemble your webapp into an exploded war and automatically deploy it to Jetty.
- *
- * Once invoked, the plugin runs continuously, and can be configured to scan for changes in the pom.xml and
- * to WEB-INF/web.xml, WEB-INF/classes or WEB-INF/lib and hot redeploy when a change is detected.
- *
- * You may also specify the location of a jetty.xml file whose contents will be applied before any plugin configuration.
- * This can be used, for example, to deploy a static webapp that is not part of your maven build.
- *
- * This goal is used to assemble your webapp into a war and automatically deploy it to Jetty.
- *
- * Once invoked, the plugin runs continuously and can be configured to scan for changes in the project and to the
- * war file and automatically perform a hot redeploy when necessary.
- *
- * You may also specify the location of a jetty.xml file whose contents will be applied before any plugin configuration.
- * This can be used, for example, to deploy a static webapp that is not part of your maven build.
- *
+* This goal is used to assemble your webapp into a war and automatically deploy it to Jetty.
+*
+* Once invoked, the plugin runs continuously and can be configured to scan for changes in the project and to the
+* war file and automatically perform a hot redeploy when necessary.
+*
+* You may also specify the location of a jetty.xml file whose contents will be applied before any plugin configuration.
+*
+* You can configure this goal to run your webapp either in-process with maven, or forked into a new process, or deployed into a
+* jetty distribution.
+*
+ * This goal is similar to the jetty:run goal in that it it starts jetty on an unassembled webapp,
+ * EXCEPT that it is designed to be bound to an execution inside your pom. Thus, this goal does NOT
+ * run a parallel build cycle, so you must be careful to ensure that you bind it to a phase in
+ * which all necessary generated files and classes for the webapp have been created.
+ *
- * This goal is similar to the jetty:run goal, EXCEPT that it is designed to be bound to an execution inside your pom, rather
- * than being run from the command line.
+ * This goal will NOT scan for changes in either the webapp project or any scanTargets or scanTargetPatterns.
*
- * When using it, be careful to ensure that you bind it to a phase in which all necessary generated files and classes for the webapp
- * will have been created. If you run it from the command line, then also ensure that all necessary generated files and classes for
- * the webapp already exist.
- *
+ * This goal is used to run Jetty with any pre-assembled war. This goal does not have
+ * to be used with a project of packaging type "war".
+ *
+ * You can configure the "webApp" element with the location of either a war file or
+ * an unpacked war that you wish to deploy - in either case, the webapp must be
+ * fully compiled and assembled as this goal does not do anything other than start
+ * jetty with the given webapp. If you do not configure the "webApp" element, then
+ * the goal will default to using the war of the webapp project.
+ *
+ * This goal is designed to be bound to a build phase, and NOT to be run at the
+ * command line. It will not block waiting for jetty to execute, but rather continue
+ * execution.
+ *
+ * This goal is useful e.g. for launching a web app in Jetty as a target for unit-tested
+ * HTTP client components via binding to the test-integration build phase.
+ *
+ * You can configure this goal to run the webapp either in-process with maven, or
+ * forked into a new process, or deployed into a jetty distribution.
+ *
+ *
* Information about the maven-war-plugin contained in the pom
*/
public class WarPluginInfo
@@ -40,10 +43,50 @@ public class WarPluginInfo
private List Implements authentication using OpenId Connect on top of OAuth 2.0.
+ *
+ * The OpenIdAuthenticator redirects unauthenticated requests to the OpenID Connect Provider. The End-User is
+ * eventually redirected back with an Authorization Code to the /j_security_check URI within the context.
+ * The Authorization Code is then used to authenticate the user through the {@link OpenIdCredentials} and {@link OpenIdLoginService}.
+ *
+ * Once a user is authenticated the OpenID Claims can be retrieved through an attribute on the session with the key {@link #CLAIMS}.
+ * The full response containing the OAuth 2.0 Access Token can be obtained with the session attribute {@link #RESPONSE}.
+ * {@link SessionAuthentication} is then used to wrap Authentication results so that they are associated with the session. The credentials of an user to be authenticated with OpenID Connect. This will contain
+ * the OpenID ID Token and the OAuth 2.0 Access Token.
+ * This is constructed with an authorization code from the authentication request. This authorization code
+ * is then exchanged using {@link #redeemAuthCode(HttpClient)} for a response containing the ID Token and Access Token.
+ * The response is then validated against the {@link OpenIdConfiguration}.
+ *
+ * Can contain an optional wrapped {@link LoginService} which is used to store role information about users.
+ *
+ * If set to true, any users not found by the wrapped {@link LoginService} will still
+ * be authenticated but with no roles, if set to false users will not be
+ * authenticated unless they are discovered by the wrapped {@link LoginService}.
+ * ROOT
\ No newline at end of file
diff --git a/jetty-maven-plugin/src/test/resources/selective-jar-test.jar b/jetty-maven-plugin/src/test/resources/selective-jar-test.jar
new file mode 100644
index 00000000000..dc7dc4b596c
Binary files /dev/null and b/jetty-maven-plugin/src/test/resources/selective-jar-test.jar differ
diff --git a/jetty-memcached/jetty-memcached-sessions/src/main/config/modules/sessions/session-data-cache/xmemcached.mod b/jetty-memcached/jetty-memcached-sessions/src/main/config/modules/sessions/session-data-cache/xmemcached.mod
index 77a21ea759f..017c004f4b9 100644
--- a/jetty-memcached/jetty-memcached-sessions/src/main/config/modules/sessions/session-data-cache/xmemcached.mod
+++ b/jetty-memcached/jetty-memcached-sessions/src/main/config/modules/sessions/session-data-cache/xmemcached.mod
@@ -8,7 +8,7 @@ session
[depends]
session-store
-slf4j-api
+logging/slf4j
[files]
maven://com.googlecode.xmemcached/xmemcached/2.4.5|lib/xmemcached/xmemcached-2.4.5.jar
diff --git a/jetty-memcached/jetty-memcached-sessions/src/main/java/org/eclipse/jetty/memcached/session/MemcachedSessionDataMap.java b/jetty-memcached/jetty-memcached-sessions/src/main/java/org/eclipse/jetty/memcached/session/MemcachedSessionDataMap.java
index 2198a822934..1c7900462f3 100644
--- a/jetty-memcached/jetty-memcached-sessions/src/main/java/org/eclipse/jetty/memcached/session/MemcachedSessionDataMap.java
+++ b/jetty-memcached/jetty-memcached-sessions/src/main/java/org/eclipse/jetty/memcached/session/MemcachedSessionDataMap.java
@@ -1,19 +1,19 @@
//
-// ========================================================================
-// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd.
-// ------------------------------------------------------------------------
-// All rights reserved. This program and the accompanying materials
-// are made available under the terms of the Eclipse Public License v1.0
-// and Apache License v2.0 which accompanies this distribution.
+// ========================================================================
+// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others.
//
-// The Eclipse Public License is available at
-// http://www.eclipse.org/legal/epl-v10.html
+// 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
//
-// The Apache License v2.0 is available at
-// http://www.opensource.org/licenses/apache2.0.php
+// 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
//
-// You may elect to redistribute this code under either of these licenses.
-// ========================================================================
+// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
+// ========================================================================
//
package org.eclipse.jetty.memcached.session;
diff --git a/jetty-memcached/jetty-memcached-sessions/src/main/java/org/eclipse/jetty/memcached/session/MemcachedSessionDataMapFactory.java b/jetty-memcached/jetty-memcached-sessions/src/main/java/org/eclipse/jetty/memcached/session/MemcachedSessionDataMapFactory.java
index c1714bd7e87..e04ca05a327 100644
--- a/jetty-memcached/jetty-memcached-sessions/src/main/java/org/eclipse/jetty/memcached/session/MemcachedSessionDataMapFactory.java
+++ b/jetty-memcached/jetty-memcached-sessions/src/main/java/org/eclipse/jetty/memcached/session/MemcachedSessionDataMapFactory.java
@@ -1,19 +1,19 @@
//
-// ========================================================================
-// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd.
-// ------------------------------------------------------------------------
-// All rights reserved. This program and the accompanying materials
-// are made available under the terms of the Eclipse Public License v1.0
-// and Apache License v2.0 which accompanies this distribution.
+// ========================================================================
+// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others.
//
-// The Eclipse Public License is available at
-// http://www.eclipse.org/legal/epl-v10.html
+// 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
//
-// The Apache License v2.0 is available at
-// http://www.opensource.org/licenses/apache2.0.php
+// 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
//
-// You may elect to redistribute this code under either of these licenses.
-// ========================================================================
+// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
+// ========================================================================
//
package org.eclipse.jetty.memcached.session;
@@ -83,9 +83,6 @@ public class MemcachedSessionDataMapFactory implements SessionDataMapFactory
_heartbeats = heartbeats;
}
- /**
- * @see org.eclipse.jetty.server.session.SessionDataMapFactory#getSessionDataMap()
- */
@Override
public SessionDataMap getSessionDataMap()
{
diff --git a/jetty-memcached/jetty-memcached-sessions/src/test/java/org/eclipse/jetty/memcached/session/TestMemcachedSessions.java b/jetty-memcached/jetty-memcached-sessions/src/test/java/org/eclipse/jetty/memcached/session/TestMemcachedSessions.java
index ffc3d8d68f8..9debffeb235 100644
--- a/jetty-memcached/jetty-memcached-sessions/src/test/java/org/eclipse/jetty/memcached/session/TestMemcachedSessions.java
+++ b/jetty-memcached/jetty-memcached-sessions/src/test/java/org/eclipse/jetty/memcached/session/TestMemcachedSessions.java
@@ -1,19 +1,19 @@
//
-// ========================================================================
-// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd.
-// ------------------------------------------------------------------------
-// All rights reserved. This program and the accompanying materials
-// are made available under the terms of the Eclipse Public License v1.0
-// and Apache License v2.0 which accompanies this distribution.
+// ========================================================================
+// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others.
//
-// The Eclipse Public License is available at
-// http://www.eclipse.org/legal/epl-v10.html
+// 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
//
-// The Apache License v2.0 is available at
-// http://www.opensource.org/licenses/apache2.0.php
+// 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
//
-// You may elect to redistribute this code under either of these licenses.
-// ========================================================================
+// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
+// ========================================================================
//
package org.eclipse.jetty.memcached.session;
@@ -31,12 +31,9 @@ import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.client.api.Request;
import org.eclipse.jetty.server.NetworkConnector;
import org.eclipse.jetty.server.Server;
-import org.eclipse.jetty.server.session.AbstractSessionCache;
import org.eclipse.jetty.server.session.CachingSessionDataStore;
+import org.eclipse.jetty.server.session.NullSessionCache;
import org.eclipse.jetty.server.session.NullSessionDataStore;
-import org.eclipse.jetty.server.session.Session;
-import org.eclipse.jetty.server.session.SessionData;
-import org.eclipse.jetty.server.session.SessionHandler;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.junit.jupiter.api.Test;
@@ -88,56 +85,6 @@ public class TestMemcachedSessions
}
}
- public static class NullSessionCache extends AbstractSessionCache
- {
-
- public NullSessionCache(SessionHandler handler)
- {
- super(handler);
- }
-
- @Override
- public void shutdown()
- {
- }
-
- @Override
- public Session newSession(SessionData data)
- {
- return new Session(_handler, data);
- }
-
- @Override
- public Session newSession(HttpServletRequest request, SessionData data)
- {
- return new Session(_handler, request, data);
- }
-
- @Override
- public Session doGet(String id)
- {
- return null;
- }
-
- @Override
- public Session doPutIfAbsent(String id, Session session)
- {
- return null;
- }
-
- @Override
- public boolean doReplace(String id, Session oldValue, Session newValue)
- {
- return true;
- }
-
- @Override
- public Session doDelete(String id)
- {
- return null;
- }
- }
-
@Test
public void testMemcached() throws Exception
{
diff --git a/jetty-nosql/pom.xml b/jetty-nosql/pom.xml
index 1d3f099c606..af03a0f479c 100644
--- a/jetty-nosql/pom.xml
+++ b/jetty-nosql/pom.xml
@@ -21,11 +21,6 @@
Abstract base class for proxy servlets.
@@ -150,7 +151,7 @@ public abstract class AbstractProxyServlet extends HttpServlet catch (Exception x) { if (_log.isDebugEnabled()) - _log.debug(x); + _log.debug("Failed to stop client", x); } } @@ -207,7 +208,7 @@ public abstract class AbstractProxyServlet extends HttpServlet { servletName = getClass().getName() + "." + servletName; } - return Log.getLogger(servletName); + return LoggerFactory.getLogger(servletName); } /** @@ -350,11 +351,23 @@ public abstract class AbstractProxyServlet extends HttpServlet */ protected HttpClient newHttpClient() { - int selectors = Math.max(1, ProcessorUtils.availableProcessors() / 2); + int selectors = 1; String value = getServletConfig().getInitParameter("selectors"); if (value != null) selectors = Integer.parseInt(value); - return new HttpClient(new HttpClientTransportOverHTTP(selectors)); + ClientConnector clientConnector = newClientConnector(); + clientConnector.setSelectors(selectors); + return newHttpClient(clientConnector); + } + + protected HttpClient newHttpClient(ClientConnector clientConnector) + { + return new HttpClient(new HttpClientTransportDynamic(clientConnector)); + } + + protected ClientConnector newClientConnector() + { + return new ClientConnector(); } protected HttpClient getHttpClient() @@ -411,8 +424,14 @@ public abstract class AbstractProxyServlet extends HttpServlet { if (!validateDestination(clientRequest.getServerName(), clientRequest.getServerPort())) return null; - + // If the proxy is secure, we will likely get a proxied URI + // with the "https" scheme, but the upstream server needs + // to be called with the "http" scheme (the ConnectHandler + // is used to call upstream servers with the "https" scheme). StringBuffer target = clientRequest.getRequestURL(); + // Change "https" to "http". + if (HttpScheme.HTTPS.is(target.substring(0, 5))) + target.replace(4, 5, ""); String query = clientRequest.getQueryString(); if (query != null) target.append("?").append(query); @@ -673,7 +692,15 @@ public abstract class AbstractProxyServlet extends HttpServlet } catch (Exception e) { - _log.ignore(e); + _log.trace("IGNORED", e); + try + { + proxyResponse.sendError(-1); + } + catch (Exception e2) + { + _log.trace("IGNORED", e2); + } } finally { diff --git a/jetty-proxy/src/main/java/org/eclipse/jetty/proxy/AfterContentTransformer.java b/jetty-proxy/src/main/java/org/eclipse/jetty/proxy/AfterContentTransformer.java index be757347d57..9169004064a 100644 --- a/jetty-proxy/src/main/java/org/eclipse/jetty/proxy/AfterContentTransformer.java +++ b/jetty-proxy/src/main/java/org/eclipse/jetty/proxy/AfterContentTransformer.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.proxy; @@ -35,8 +35,8 @@ import java.util.List; import org.eclipse.jetty.util.IO; import org.eclipse.jetty.util.component.Destroyable; -import org.eclipse.jetty.util.log.Log; -import org.eclipse.jetty.util.log.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** *A specialized transformer for {@link AsyncMiddleManServlet} that performs
@@ -58,7 +58,7 @@ import org.eclipse.jetty.util.log.Logger;
*/
public abstract class AfterContentTransformer implements AsyncMiddleManServlet.ContentTransformer, Destroyable
{
- private static final Logger LOG = Log.getLogger(AfterContentTransformer.class);
+ private static final Logger LOG = LoggerFactory.getLogger(AfterContentTransformer.class);
private final List Servlet 3.1 asynchronous proxy servlet with capability
@@ -757,7 +757,7 @@ public class AsyncMiddleManServlet extends AbstractProxyServlet
public static class GZIPContentTransformer implements ContentTransformer
{
- private static final Logger logger = Log.getLogger(GZIPContentTransformer.class);
+ private static final Logger logger = LoggerFactory.getLogger(GZIPContentTransformer.class);
private final List Implementation of a {@link Handler} that supports HTTP CONNECT.
- * Re-inflate a deployable webapp from a saved effective-web.xml
- * which combines all pre-parsed web xml descriptors and annotations.
+ * Prepare for quickstart generation, or usage.
*/
public class QuickStartConfiguration extends AbstractConfiguration
{
- private static final Logger LOG = Log.getLogger(QuickStartConfiguration.class);
+ private static final Logger LOG = LoggerFactory.getLogger(QuickStartConfiguration.class);
public static final Set In practise this means calling
* Generate an effective web.xml from a WebAppContext, including all components
* from web.xml, web-fragment.xmls annotations etc.
@@ -75,16 +77,15 @@ import org.eclipse.jetty.xml.XmlAppendable;
*/
public class QuickStartGeneratorConfiguration extends AbstractConfiguration
{
- private static final Logger LOG = Log.getLogger(QuickStartGeneratorConfiguration.class);
+ static final Logger LOG = LoggerFactory.getLogger(QuickStartGeneratorConfiguration.class);
public static final String ORIGIN = "org.eclipse.jetty.originAttribute";
public static final String DEFAULT_ORIGIN_ATTRIBUTE_NAME = "origin";
protected final boolean _abort;
protected String _originAttribute;
- protected boolean _generateOrigin;
protected int _count;
protected Resource _quickStartWebXml;
-
+
public QuickStartGeneratorConfiguration()
{
this(false);
@@ -92,7 +93,7 @@ public class QuickStartGeneratorConfiguration extends AbstractConfiguration
public QuickStartGeneratorConfiguration(boolean abort)
{
- super(true);
+ super(false);
_count = 0;
_abort = abort;
}
@@ -116,22 +117,6 @@ public class QuickStartGeneratorConfiguration extends AbstractConfiguration
return _originAttribute;
}
- /**
- * @return the generateOrigin
- */
- public boolean isGenerateOrigin()
- {
- return _generateOrigin;
- }
-
- /**
- * @param generateOrigin the generateOrigin to set
- */
- public void setGenerateOrigin(boolean generateOrigin)
- {
- _generateOrigin = generateOrigin;
- }
-
public Resource getQuickStartWebXml()
{
return _quickStartWebXml;
@@ -163,8 +148,6 @@ public class QuickStartGeneratorConfiguration extends AbstractConfiguration
if (context.getBaseResource() == null)
throw new IllegalArgumentException("No base resource for " + this);
- LOG.info("Quickstart generating");
-
MetaData md = context.getMetaData();
Mapserver.setDryRun(true)
for GENERATE mode
A configurable (as opposed to using system properties) SPNEGO LoginService.
@@ -51,14 +51,14 @@ import org.ietf.jgss.Oid; * of the {@link #getServiceName() service name} and the {@link #getHostName() host name}, * for example {@code HTTP/wonder.com}, using a {@code keyTab} file as the service principal * credentials. - *Upon receiving a HTTP request, the server tries to authenticate the client + *
Upon receiving an HTTP request, the server tries to authenticate the client * calling {@link #login(String, Object, ServletRequest)} where the GSS APIs are used to * verify client tokens and (perhaps after a few round-trips) a {@code GSSContext} is * established.
*/ public class ConfigurableSpnegoLoginService extends ContainerLifeCycle implements LoginService { - private static final Logger LOG = Log.getLogger(ConfigurableSpnegoLoginService.class); + private static final Logger LOG = LoggerFactory.getLogger(ConfigurableSpnegoLoginService.class); private final GSSManager _gssManager = GSSManager.getInstance(); private final String _realm; diff --git a/jetty-security/src/main/java/org/eclipse/jetty/security/ConstraintAware.java b/jetty-security/src/main/java/org/eclipse/jetty/security/ConstraintAware.java index 09d4112fc20..0f2a41cb9fe 100644 --- a/jetty-security/src/main/java/org/eclipse/jetty/security/ConstraintAware.java +++ b/jetty-security/src/main/java/org/eclipse/jetty/security/ConstraintAware.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.security; diff --git a/jetty-security/src/main/java/org/eclipse/jetty/security/ConstraintMapping.java b/jetty-security/src/main/java/org/eclipse/jetty/security/ConstraintMapping.java index 20ed69c66df..9752749a203 100644 --- a/jetty-security/src/main/java/org/eclipse/jetty/security/ConstraintMapping.java +++ b/jetty-security/src/main/java/org/eclipse/jetty/security/ConstraintMapping.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.security; diff --git a/jetty-security/src/main/java/org/eclipse/jetty/security/ConstraintSecurityHandler.java b/jetty-security/src/main/java/org/eclipse/jetty/security/ConstraintSecurityHandler.java index 26aede1f640..fae59423c75 100644 --- a/jetty-security/src/main/java/org/eclipse/jetty/security/ConstraintSecurityHandler.java +++ b/jetty-security/src/main/java/org/eclipse/jetty/security/ConstraintSecurityHandler.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.security; @@ -47,9 +47,9 @@ import org.eclipse.jetty.server.UserIdentity; import org.eclipse.jetty.server.handler.ContextHandler; import org.eclipse.jetty.util.URIUtil; import org.eclipse.jetty.util.component.DumpableCollection; -import org.eclipse.jetty.util.log.Log; -import org.eclipse.jetty.util.log.Logger; import org.eclipse.jetty.util.security.Constraint; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * ConstraintSecurityHandler @@ -60,7 +60,7 @@ import org.eclipse.jetty.util.security.Constraint; */ public class ConstraintSecurityHandler extends SecurityHandler implements ConstraintAware { - private static final Logger LOG = Log.getLogger(SecurityHandler.class); //use same as SecurityHandler + private static final Logger LOG = LoggerFactory.getLogger(SecurityHandler.class); //use same as SecurityHandler private static final String OMISSION_SUFFIX = ".omission"; private static final String ALL_METHODS = "*"; @@ -352,9 +352,6 @@ public class ConstraintSecurityHandler extends SecurityHandler implements Constr _roles.addAll(roles); } - /** - * @see org.eclipse.jetty.security.ConstraintAware#addConstraintMapping(org.eclipse.jetty.security.ConstraintMapping) - */ @Override public void addConstraintMapping(ConstraintMapping mapping) { @@ -377,9 +374,6 @@ public class ConstraintSecurityHandler extends SecurityHandler implements Constr } } - /** - * @see org.eclipse.jetty.security.ConstraintAware#addRole(java.lang.String) - */ @Override public void addRole(String role) { @@ -399,9 +393,6 @@ public class ConstraintSecurityHandler extends SecurityHandler implements Constr } } - /** - * @see org.eclipse.jetty.security.SecurityHandler#doStart() - */ @Override protected void doStart() throws Exception { @@ -677,9 +668,6 @@ public class ConstraintSecurityHandler extends SecurityHandler implements Constr return constraintInfo != null && ((RoleInfo)constraintInfo).isChecked(); } - /** - * @see org.eclipse.jetty.security.SecurityHandler#checkWebResourcePermissions(java.lang.String, org.eclipse.jetty.server.Request, org.eclipse.jetty.server.Response, java.lang.Object, org.eclipse.jetty.server.UserIdentity) - */ @Override protected boolean checkWebResourcePermissions(String pathInContext, Request request, Response response, Object constraintInfo, UserIdentity userIdentity) throws IOException @@ -735,9 +723,6 @@ public class ConstraintSecurityHandler extends SecurityHandler implements Constr DumpableCollection.from("constraints", _constraintMappings)); } - /** - * @see org.eclipse.jetty.security.ConstraintAware#setDenyUncoveredHttpMethods(boolean) - */ @Override public void setDenyUncoveredHttpMethods(boolean deny) { @@ -759,12 +744,14 @@ public class ConstraintSecurityHandler extends SecurityHandler implements Constr SetThis class monitors a property file of the format mentioned below
@@ -59,7 +59,7 @@ import org.eclipse.jetty.util.security.Credential;
*/
public class PropertyUserStore extends UserStore implements PathWatcher.Listener
{
- private static final Logger LOG = Log.getLogger(PropertyUserStore.class);
+ private static final Logger LOG = LoggerFactory.getLogger(PropertyUserStore.class);
protected Path _configPath;
protected PathWatcher _pathWatcher;
@@ -305,7 +305,7 @@ public class PropertyUserStore extends UserStore implements PathWatcher.Listener
}
catch (IOException e)
{
- LOG.warn(e);
+ LOG.warn("Unable to load users", e);
}
}
diff --git a/jetty-security/src/main/java/org/eclipse/jetty/security/RoleInfo.java b/jetty-security/src/main/java/org/eclipse/jetty/security/RoleInfo.java
index a2699188b22..ccb8f7af891 100644
--- a/jetty-security/src/main/java/org/eclipse/jetty/security/RoleInfo.java
+++ b/jetty-security/src/main/java/org/eclipse/jetty/security/RoleInfo.java
@@ -1,19 +1,19 @@
//
-// ========================================================================
-// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd.
-// ------------------------------------------------------------------------
-// All rights reserved. This program and the accompanying materials
-// are made available under the terms of the Eclipse Public License v1.0
-// and Apache License v2.0 which accompanies this distribution.
+// ========================================================================
+// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others.
//
-// The Eclipse Public License is available at
-// http://www.eclipse.org/legal/epl-v10.html
+// 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
//
-// The Apache License v2.0 is available at
-// http://www.opensource.org/licenses/apache2.0.php
+// 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
//
-// You may elect to redistribute this code under either of these licenses.
-// ========================================================================
+// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
+// ========================================================================
//
package org.eclipse.jetty.security;
diff --git a/jetty-security/src/main/java/org/eclipse/jetty/security/RoleRunAsToken.java b/jetty-security/src/main/java/org/eclipse/jetty/security/RoleRunAsToken.java
index 6309c64365a..7b382792b95 100644
--- a/jetty-security/src/main/java/org/eclipse/jetty/security/RoleRunAsToken.java
+++ b/jetty-security/src/main/java/org/eclipse/jetty/security/RoleRunAsToken.java
@@ -1,19 +1,19 @@
//
-// ========================================================================
-// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd.
-// ------------------------------------------------------------------------
-// All rights reserved. This program and the accompanying materials
-// are made available under the terms of the Eclipse Public License v1.0
-// and Apache License v2.0 which accompanies this distribution.
+// ========================================================================
+// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others.
//
-// The Eclipse Public License is available at
-// http://www.eclipse.org/legal/epl-v10.html
+// 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
//
-// The Apache License v2.0 is available at
-// http://www.opensource.org/licenses/apache2.0.php
+// 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
//
-// You may elect to redistribute this code under either of these licenses.
-// ========================================================================
+// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
+// ========================================================================
//
package org.eclipse.jetty.security;
diff --git a/jetty-security/src/main/java/org/eclipse/jetty/security/RunAsToken.java b/jetty-security/src/main/java/org/eclipse/jetty/security/RunAsToken.java
index 3750ee0d105..ee0aafe2b11 100644
--- a/jetty-security/src/main/java/org/eclipse/jetty/security/RunAsToken.java
+++ b/jetty-security/src/main/java/org/eclipse/jetty/security/RunAsToken.java
@@ -1,19 +1,19 @@
//
-// ========================================================================
-// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd.
-// ------------------------------------------------------------------------
-// All rights reserved. This program and the accompanying materials
-// are made available under the terms of the Eclipse Public License v1.0
-// and Apache License v2.0 which accompanies this distribution.
+// ========================================================================
+// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others.
//
-// The Eclipse Public License is available at
-// http://www.eclipse.org/legal/epl-v10.html
+// 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
//
-// The Apache License v2.0 is available at
-// http://www.opensource.org/licenses/apache2.0.php
+// 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
//
-// You may elect to redistribute this code under either of these licenses.
-// ========================================================================
+// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
+// ========================================================================
//
package org.eclipse.jetty.security;
diff --git a/jetty-security/src/main/java/org/eclipse/jetty/security/SecurityHandler.java b/jetty-security/src/main/java/org/eclipse/jetty/security/SecurityHandler.java
index 62df3199fd7..020c12b0005 100644
--- a/jetty-security/src/main/java/org/eclipse/jetty/security/SecurityHandler.java
+++ b/jetty-security/src/main/java/org/eclipse/jetty/security/SecurityHandler.java
@@ -1,29 +1,32 @@
//
-// ========================================================================
-// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd.
-// ------------------------------------------------------------------------
-// All rights reserved. This program and the accompanying materials
-// are made available under the terms of the Eclipse Public License v1.0
-// and Apache License v2.0 which accompanies this distribution.
+// ========================================================================
+// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others.
//
-// The Eclipse Public License is available at
-// http://www.eclipse.org/legal/epl-v10.html
+// 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
//
-// The Apache License v2.0 is available at
-// http://www.opensource.org/licenses/apache2.0.php
+// 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
//
-// You may elect to redistribute this code under either of these licenses.
-// ========================================================================
+// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
+// ========================================================================
//
package org.eclipse.jetty.security;
import java.io.IOException;
import java.security.Principal;
+import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashMap;
+import java.util.List;
import java.util.Map;
+import java.util.ServiceLoader;
import java.util.Set;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
@@ -38,8 +41,10 @@ import org.eclipse.jetty.server.UserIdentity;
import org.eclipse.jetty.server.handler.ContextHandler;
import org.eclipse.jetty.server.handler.ContextHandler.Context;
import org.eclipse.jetty.server.handler.HandlerWrapper;
-import org.eclipse.jetty.util.log.Log;
-import org.eclipse.jetty.util.log.Logger;
+import org.eclipse.jetty.util.TypeUtil;
+import org.eclipse.jetty.util.component.DumpableCollection;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* Abstract SecurityHandler.
@@ -57,21 +62,29 @@ import org.eclipse.jetty.util.log.Logger;
*/
public abstract class SecurityHandler extends HandlerWrapper implements Authenticator.AuthConfiguration
{
- private static final Logger LOG = Log.getLogger(SecurityHandler.class);
+ private static final Logger LOG = LoggerFactory.getLogger(SecurityHandler.class);
+ private static final List A LoginAuthenticator that uses SPNEGO and the GSS API to authenticate requests.
Provides the common handling for {@link ConnectionFactory} implementations including:
- *Provides the common handling for {@link ConnectionFactory} implementations.
*/ @ManagedObject public abstract class AbstractConnectionFactory extends ContainerLifeCycle implements ConnectionFactory @@ -87,24 +77,35 @@ public abstract class AbstractConnectionFactory extends ContainerLifeCycle imple _inputbufferSize = size; } + protected String findNextProtocol(Connector connector) + { + return findNextProtocol(connector, getProtocol()); + } + + protected static String findNextProtocol(Connector connector, String currentProtocol) + { + String nextProtocol = null; + for (IteratorAn abstract implementation of {@link Connector} that provides a {@link ConnectionFactory} mechanism
@@ -115,7 +115,7 @@ import org.eclipse.jetty.util.thread.ThreadPoolBudget;
* {@link ConnectionFactory}s may also create temporary {@link org.eclipse.jetty.io.Connection} instances that will exchange bytes
* over the connection to determine what is the next protocol to use. For example the ALPN protocol is an extension
* of SSL to allow a protocol to be specified during the SSL handshake. ALPN is used by the HTTP/2 protocol to
- * negotiate the protocol that the client and server will speak. Thus to accept a HTTP/2 connection, the
+ * negotiate the protocol that the client and server will speak. Thus to accept an HTTP/2 connection, the
* connector will be configured with {@link ConnectionFactory}s for "SSL-ALPN", "h2", "http/1.1"
* with the default protocol being "SSL-ALPN". Thus a newly accepted connection uses "SSL-ALPN", which specifies a
* SSLConnectionFactory with "ALPN" as the next protocol. Thus an SSL connection instance is created chained to an ALPN
@@ -141,10 +141,10 @@ import org.eclipse.jetty.util.thread.ThreadPoolBudget;
@ManagedObject("Abstract implementation of the Connector Interface")
public abstract class AbstractConnector extends ContainerLifeCycle implements Connector, Dumpable
{
- protected static final Logger LOG = Log.getLogger(AbstractConnector.class);
+ protected static final Logger LOG = LoggerFactory.getLogger(AbstractConnector.class);
- private final Locker _locker = new Locker();
- private final Condition _setAccepting = _locker.newCondition();
+ private final AutoLock _lock = new AutoLock();
+ private final Condition _setAccepting = _lock.newCondition();
private final Map A Listener that limits the rate at which new connections are accepted Connections created by this factory MUST implement {@link Connection.UpgradeTo}. Check the bytes in the given {@code buffer} to figure out if this {@link Detecting} instance
+ * can work with them or not. The {@code buffer} MUST be left untouched by this method: bytes MUST NOT be consumed and MUST NOT be modified. A Listener that limits the number of Connections. When the first bytes are not recognized by the {@code detectingConnectionFactories}, the default behavior is to
+ * upgrade to the protocol returned by {@link #findNextProtocol(Connector)}. Callback method called when detection was unsuccessful.
+ * This implementation upgrades to the protocol returned by {@link #findNextProtocol(Connector)}. Listeners added by this method will only be notified
+ * if the HttpChannel has been constructed with an instance of
+ * {@link TransientListeners} as an {@link AbstractConnector}
+ * provided listener Transient listeners are removed after every request cycle Checks whether the processing of the request resulted in an upgrade,
+ * and if so performs upgrade preparation steps before the upgrade
+ * response is sent back to the client. This avoids a race where the server is unprepared if the client sends
+ * data immediately after having received the upgrade response. Listener for {@link HttpChannel} events. HttpChannel will emit events for the various phases it goes through while
- * processing a HTTP request and response.
+ *
+ * @see #getBeans(Class)
+ * @return An unmodifiable list of EventListener beans
+ */
+ public HttpChannel.Listener getHttpChannelListeners()
+ {
+ return _httpChannelListeners;
+ }
+
@Override
public Server getServer()
{
@@ -249,6 +283,20 @@ public abstract class AbstractConnector extends ContainerLifeCycle implements Co
public void setIdleTimeout(long idleTimeout)
{
_idleTimeout = idleTimeout;
+ if (_idleTimeout == 0)
+ _shutdownIdleTimeout = 0;
+ else if (_idleTimeout < _shutdownIdleTimeout)
+ _shutdownIdleTimeout = Math.min(1000L, _idleTimeout);
+ }
+
+ public void setShutdownIdleTimeout(long idle)
+ {
+ _shutdownIdleTimeout = idle;
+ }
+
+ public long getShutdownIdleTimeout()
+ {
+ return _shutdownIdleTimeout;
}
/**
@@ -263,7 +311,21 @@ public abstract class AbstractConnector extends ContainerLifeCycle implements Co
@Override
protected void doStart() throws Exception
{
- _shutdown.cancel();
+ _shutdown = new Graceful.Shutdown(this)
+ {
+ @Override
+ public boolean isShutdownDone()
+ {
+ if (!_endpoints.isEmpty())
+ return false;
+
+ for (Thread a : _acceptors)
+ if (a != null)
+ return false;
+
+ return true;
+ }
+ };
if (_defaultProtocol == null)
throw new IllegalStateException("No default protocol for " + this);
@@ -282,7 +344,6 @@ public abstract class AbstractConnector extends ContainerLifeCycle implements Co
_lease = ThreadPoolBudget.leaseFrom(getExecutor(), this, _acceptors.length);
super.doStart();
- _stopping = new CountDownLatch(_acceptors.length);
for (int i = 0; i < _acceptors.length; i++)
{
Acceptor a = new Acceptor(i);
@@ -295,7 +356,7 @@ public abstract class AbstractConnector extends ContainerLifeCycle implements Co
protected void interruptAcceptors()
{
- try (Locker.Lock lock = _locker.lock())
+ try (AutoLock lock = _lock.lock())
{
for (Thread thread : _acceptors)
{
@@ -306,15 +367,29 @@ public abstract class AbstractConnector extends ContainerLifeCycle implements Co
}
@Override
- public Future
- *
@@ -85,4 +86,43 @@ public interface ConnectionFactory
*/
public Connection upgradeConnection(Connector connector, EndPoint endPoint, MetaData.Request upgradeRequest, HttpFields responseFields) throws BadMessageException;
}
+
+ /**
+ *
+ *
+ */
+ Detection detect(ByteBuffer buffer);
+ }
}
diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/ConnectionLimit.java b/jetty-server/src/main/java/org/eclipse/jetty/server/ConnectionLimit.java
index cc57b2d654f..054923a2862 100644
--- a/jetty-server/src/main/java/org/eclipse/jetty/server/ConnectionLimit.java
+++ b/jetty-server/src/main/java/org/eclipse/jetty/server/ConnectionLimit.java
@@ -1,19 +1,19 @@
//
-// ========================================================================
-// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd.
-// ------------------------------------------------------------------------
-// All rights reserved. This program and the accompanying materials
-// are made available under the terms of the Eclipse Public License v1.0
-// and Apache License v2.0 which accompanies this distribution.
+// ========================================================================
+// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others.
//
-// The Eclipse Public License is available at
-// http://www.eclipse.org/legal/epl-v10.html
+// 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
//
-// The Apache License v2.0 is available at
-// http://www.opensource.org/licenses/apache2.0.php
+// 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
//
-// You may elect to redistribute this code under either of these licenses.
-// ========================================================================
+// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
+// ========================================================================
//
package org.eclipse.jetty.server;
@@ -33,8 +33,8 @@ import org.eclipse.jetty.util.annotation.ManagedObject;
import org.eclipse.jetty.util.annotation.Name;
import org.eclipse.jetty.util.component.AbstractLifeCycle;
import org.eclipse.jetty.util.component.Container;
-import org.eclipse.jetty.util.log.Log;
-import org.eclipse.jetty.util.log.Logger;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
*
*
*
@@ -268,12 +271,12 @@ import static java.lang.invoke.MethodType.methodType;
@ManagedObject("Custom format request log")
public class CustomRequestLog extends ContainerLifeCycle implements RequestLog
{
- protected static final Logger LOG = Log.getLogger(CustomRequestLog.class);
+ protected static final Logger LOG = LoggerFactory.getLogger(CustomRequestLog.class);
public static final String DEFAULT_DATE_FORMAT = "dd/MMM/yyyy:HH:mm:ss ZZZ";
public static final String NCSA_FORMAT = "%{client}a - %u %t \"%r\" %s %O";
- public static final String EXTENDED_NCSA_FORMAT = "%{client}a - %u %t \"%r\" %s %O \"%{Referer}i\" \"%{User-Agent}i\"";
+ public static final String EXTENDED_NCSA_FORMAT = NCSA_FORMAT + " \"%{Referer}i\" \"%{User-Agent}i\"";
private static ThreadLocal%{d}u
*
- * Remote user if the request was authenticated. May be bogus if return status (%s) is 401 (unauthorized).
- * Optional parameter d, with this parameter deferred authentication will also be checked.
+ * Remote user if the request was authenticated with servlet authentication. May be bogus if return status (%s) is 401 (unauthorized).
+ * Optional parameter d, with this parameter deferred authentication will also be checked,
+ * this is equivalent to {@link HttpServletRequest#getRemoteUser()}.
*
*
Implementations of this interface may listen to those events to track * timing and/or other values such as request URI, etc.
*The events parameters, especially the {@link Request} object, may be @@ -1113,15 +1055,20 @@ public class HttpChannel implements Runnable, HttpOutput.Interceptor *
Listener methods are invoked synchronously from the thread that is * performing the request processing, and they should not call blocking code * (otherwise the request processing will be blocked as well).
+ *Listener instances that are set as a bean on the {@link Connector} are + * efficiently added to {@link HttpChannel}. If additional listeners are added + * using the deprecated {@link HttpChannel#addListener(Listener)}
method, + * then an instance of {@link TransientListeners} must be added to the connector + * in order for them to be invoked. */ - public interface Listener + public interface Listener extends EventListener { /** * Invoked just after the HTTP request line and headers have been parsed. * * @param request the request object */ - public default void onRequestBegin(Request request) + default void onRequestBegin(Request request) { } @@ -1130,7 +1077,7 @@ public class HttpChannel implements Runnable, HttpOutput.Interceptor * * @param request the request object */ - public default void onBeforeDispatch(Request request) + default void onBeforeDispatch(Request request) { } @@ -1140,7 +1087,7 @@ public class HttpChannel implements Runnable, HttpOutput.Interceptor * @param request the request object * @param failure the exception thrown by the application */ - public default void onDispatchFailure(Request request, Throwable failure) + default void onDispatchFailure(Request request, Throwable failure) { } @@ -1149,7 +1096,7 @@ public class HttpChannel implements Runnable, HttpOutput.Interceptor * * @param request the request object */ - public default void onAfterDispatch(Request request) + default void onAfterDispatch(Request request) { } @@ -1160,7 +1107,7 @@ public class HttpChannel implements Runnable, HttpOutput.Interceptor * @param request the request object * @param content a {@link ByteBuffer#slice() slice} of the request content chunk */ - public default void onRequestContent(Request request, ByteBuffer content) + default void onRequestContent(Request request, ByteBuffer content) { } @@ -1169,7 +1116,7 @@ public class HttpChannel implements Runnable, HttpOutput.Interceptor * * @param request the request object */ - public default void onRequestContentEnd(Request request) + default void onRequestContentEnd(Request request) { } @@ -1178,7 +1125,7 @@ public class HttpChannel implements Runnable, HttpOutput.Interceptor * * @param request the request object */ - public default void onRequestTrailers(Request request) + default void onRequestTrailers(Request request) { } @@ -1187,7 +1134,7 @@ public class HttpChannel implements Runnable, HttpOutput.Interceptor * * @param request the request object */ - public default void onRequestEnd(Request request) + default void onRequestEnd(Request request) { } @@ -1197,7 +1144,7 @@ public class HttpChannel implements Runnable, HttpOutput.Interceptor * @param request the request object * @param failure the request failure */ - public default void onRequestFailure(Request request, Throwable failure) + default void onRequestFailure(Request request, Throwable failure) { } @@ -1206,7 +1153,7 @@ public class HttpChannel implements Runnable, HttpOutput.Interceptor * * @param request the request object */ - public default void onResponseBegin(Request request) + default void onResponseBegin(Request request) { } @@ -1217,7 +1164,7 @@ public class HttpChannel implements Runnable, HttpOutput.Interceptor * * @param request the request object */ - public default void onResponseCommit(Request request) + default void onResponseCommit(Request request) { } @@ -1227,7 +1174,7 @@ public class HttpChannel implements Runnable, HttpOutput.Interceptor * @param request the request object * @param content a {@link ByteBuffer#slice() slice} of the response content chunk */ - public default void onResponseContent(Request request, ByteBuffer content) + default void onResponseContent(Request request, ByteBuffer content) { } @@ -1236,7 +1183,7 @@ public class HttpChannel implements Runnable, HttpOutput.Interceptor * * @param request the request object */ - public default void onResponseEnd(Request request) + default void onResponseEnd(Request request) { } @@ -1246,7 +1193,7 @@ public class HttpChannel implements Runnable, HttpOutput.Interceptor * @param request the request object * @param failure the response failure */ - public default void onResponseFailure(Request request, Throwable failure) + default void onResponseFailure(Request request, Throwable failure) { } @@ -1255,7 +1202,7 @@ public class HttpChannel implements Runnable, HttpOutput.Interceptor * * @param request the request object */ - public default void onComplete(Request request) + default void onComplete(Request request) { } } @@ -1280,16 +1227,13 @@ public class HttpChannel implements Runnable, HttpOutput.Interceptor public void succeeded() { _written += _length; - super.succeeded(); if (_commit) - notifyResponseCommit(_request); + _combinedListener.onResponseCommit(_request); if (_length > 0) - notifyResponseContent(_request, _content); - if (_complete) - { - _responseCompleted.set(true); - notifyResponseEnd(_request); - } + _combinedListener.onResponseContent(_request, _content); + if (_complete && _state.completeResponse()) + _combinedListener.onResponseEnd(_request); + super.succeeded(); } @Override @@ -1300,13 +1244,13 @@ public class HttpChannel implements Runnable, HttpOutput.Interceptor if (x instanceof BadMessageException) { - _transport.send(HttpGenerator.RESPONSE_500_INFO, false, null, true, new Callback.Nested(this) + _transport.send(_request.getMetaData(), HttpGenerator.RESPONSE_500_INFO, null, true, new Callback.Nested(this) { @Override public void succeeded() { + _response.getHttpOutput().completed(); super.failed(x); - _response.getHttpOutput().closed(); } @Override @@ -1335,10 +1279,108 @@ public class HttpChannel implements Runnable, HttpOutput.Interceptor @Override public void succeeded() { - if (_committed.compareAndSet(true, false)) + if (_state.partialResponse()) super.succeeded(); else super.failed(new IllegalStateException()); } } + + /** + * A Listener instance that can be added as a bean to {@link AbstractConnector} so that + * the listeners obtained from HttpChannel{@link #getTransientListeners()} + */ + @Deprecated + public static class TransientListeners implements Listener + { + @Override + public void onRequestBegin(Request request) + { + request.getHttpChannel().notifyEvent1(listener -> listener::onRequestBegin, request); + } + + @Override + public void onBeforeDispatch(Request request) + { + request.getHttpChannel().notifyEvent1(listener -> listener::onBeforeDispatch, request); + } + + @Override + public void onDispatchFailure(Request request, Throwable failure) + { + request.getHttpChannel().notifyEvent2(listener -> listener::onDispatchFailure, request, failure); + } + + @Override + public void onAfterDispatch(Request request) + { + request.getHttpChannel().notifyEvent1(listener -> listener::onAfterDispatch, request); + } + + @Override + public void onRequestContent(Request request, ByteBuffer content) + { + request.getHttpChannel().notifyEvent2(listener -> listener::onRequestContent, request, content); + } + + @Override + public void onRequestContentEnd(Request request) + { + request.getHttpChannel().notifyEvent1(listener -> listener::onRequestContentEnd, request); + } + + @Override + public void onRequestTrailers(Request request) + { + request.getHttpChannel().notifyEvent1(listener -> listener::onRequestTrailers, request); + } + + @Override + public void onRequestEnd(Request request) + { + request.getHttpChannel().notifyEvent1(listener -> listener::onRequestEnd, request); + } + + @Override + public void onRequestFailure(Request request, Throwable failure) + { + request.getHttpChannel().notifyEvent2(listener -> listener::onRequestFailure, request, failure); + } + + @Override + public void onResponseBegin(Request request) + { + request.getHttpChannel().notifyEvent1(listener -> listener::onResponseBegin, request); + } + + @Override + public void onResponseCommit(Request request) + { + request.getHttpChannel().notifyEvent1(listener -> listener::onResponseCommit, request); + } + + @Override + public void onResponseContent(Request request, ByteBuffer content) + { + request.getHttpChannel().notifyEvent2(listener -> listener::onResponseContent, request, content); + } + + @Override + public void onResponseEnd(Request request) + { + request.getHttpChannel().notifyEvent1(listener -> listener::onResponseEnd, request); + } + + @Override + public void onResponseFailure(Request request, Throwable failure) + { + request.getHttpChannel().notifyEvent2(listener -> listener::onResponseFailure, request, failure); + } + + @Override + public void onComplete(Request request) + { + request.getHttpChannel().notifyEvent1(listener -> listener::onComplete, request); + } + } } diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/HttpChannelListeners.java b/jetty-server/src/main/java/org/eclipse/jetty/server/HttpChannelListeners.java new file mode 100644 index 00000000000..f380ab54e56 --- /dev/null +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/HttpChannelListeners.java @@ -0,0 +1,286 @@ +// +// ======================================================================== +// 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.server; + +import java.nio.ByteBuffer; +import java.util.Collection; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * A {@link HttpChannel.Listener} that holds a collection of + * other {@link HttpChannel.Listener} instances that are efficiently + * invoked without iteration. + * @see AbstractConnector + */ +public class HttpChannelListeners implements HttpChannel.Listener +{ + static final Logger LOG = LoggerFactory.getLogger(HttpChannel.class); + public static HttpChannel.Listener NOOP = new HttpChannel.Listener() {}; + + private final NotifyRequest onRequestBegin; + private final NotifyRequest onBeforeDispatch; + private final NotifyFailure onDispatchFailure; + private final NotifyRequest onAfterDispatch; + private final NotifyContent onRequestContent; + private final NotifyRequest onRequestContentEnd; + private final NotifyRequest onRequestTrailers; + private final NotifyRequest onRequestEnd; + private final NotifyFailure onRequestFailure; + private final NotifyRequest onResponseBegin; + private final NotifyRequest onResponseCommit; + private final NotifyContent onResponseContent; + private final NotifyRequest onResponseEnd; + private final NotifyFailure onResponseFailure; + private final NotifyRequest onComplete; + + public HttpChannelListeners(CollectionAttempts to perform a HTTP/1.1 upgrade.
+ *Attempts to perform an HTTP/1.1 upgrade.
*The upgrade looks up a {@link ConnectionFactory.Upgrading} from the connector * matching the protocol specified in the {@code Upgrade} header.
*The upgrade may succeed, be ignored (which can allow a later handler to implement) @@ -429,18 +441,12 @@ public class HttpChannelOverHttp extends HttpChannel implements HttpParser.Reque throw new BadMessageException(HttpStatus.BAD_REQUEST_400); // Find the upgrade factory - ConnectionFactory.Upgrading factory = null; - for (ConnectionFactory f : getConnector().getConnectionFactories()) - { - if (f instanceof ConnectionFactory.Upgrading) - { - if (f.getProtocols().contains(_upgrade.getValue())) - { - factory = (ConnectionFactory.Upgrading)f; - break; - } - } - } + ConnectionFactory.Upgrading factory = getConnector().getConnectionFactories().stream() + .filter(f -> f instanceof ConnectionFactory.Upgrading) + .map(ConnectionFactory.Upgrading.class::cast) + .filter(f -> f.getProtocols().contains(_upgrade.getValue())) + .findAny() + .orElse(null); if (factory == null) { @@ -472,8 +478,7 @@ public class HttpChannelOverHttp extends HttpChannel implements HttpParser.Reque if (LOG.isDebugEnabled()) LOG.debug("Upgrade from {} to {}", getEndPoint().getConnection(), upgradeConnection); - getRequest().setAttribute(HttpConnection.UPGRADE_CONNECTION_ATTRIBUTE, upgradeConnection); - getResponse().setStatus(101); + getRequest().setAttribute(HttpTransport.UPGRADE_CONNECTION_ATTRIBUTE, upgradeConnection); getHttpTransport().onCompleted(); return true; } @@ -508,18 +513,6 @@ public class HttpChannelOverHttp extends HttpChannel implements HttpParser.Reque return onRequestComplete(); } - @Override - public int getHeaderCacheSize() - { - return getHttpConfiguration().getHeaderCacheSize(); - } - - @Override - public boolean isHeaderCacheCaseSensitive() - { - return getHttpConfiguration().isHeaderCacheCaseSensitive(); - } - @Override public void onComplianceViolation(ComplianceViolation.Mode mode, ComplianceViolation violation, String details) { @@ -530,10 +523,22 @@ public class HttpChannelOverHttp extends HttpChannel implements HttpParser.Reque _complianceViolations = new ArrayList<>(); } String record = String.format("%s (see %s) in mode %s for %s in %s", - violation.getDescription(), violation.getURL(), mode, details, getHttpTransport()); + violation.getDescription(), violation.getURL(), mode, details, getHttpTransport()); _complianceViolations.add(record); if (LOG.isDebugEnabled()) LOG.debug(record); } } + + @Override + public boolean isTunnellingSupported() + { + return true; + } + + @Override + public EndPoint getTunnellingEndPoint() + { + return getEndPoint(); + } } diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/HttpChannelState.java b/jetty-server/src/main/java/org/eclipse/jetty/server/HttpChannelState.java index 75e37a8763a..0871e53b14b 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/HttpChannelState.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/HttpChannelState.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// 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 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// 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 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.server; @@ -21,25 +21,26 @@ package org.eclipse.jetty.server; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicReference; import javax.servlet.AsyncListener; -import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.servlet.ServletResponse; import javax.servlet.UnavailableException; import org.eclipse.jetty.http.BadMessageException; import org.eclipse.jetty.http.HttpStatus; +import org.eclipse.jetty.io.QuietException; import org.eclipse.jetty.server.handler.ContextHandler; import org.eclipse.jetty.server.handler.ContextHandler.Context; -import org.eclipse.jetty.util.log.Log; -import org.eclipse.jetty.util.log.Logger; -import org.eclipse.jetty.util.thread.Locker; +import org.eclipse.jetty.server.handler.ErrorHandler; import org.eclipse.jetty.util.thread.Scheduler; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import static javax.servlet.RequestDispatcher.ERROR_EXCEPTION; import static javax.servlet.RequestDispatcher.ERROR_EXCEPTION_TYPE; import static javax.servlet.RequestDispatcher.ERROR_MESSAGE; +import static javax.servlet.RequestDispatcher.ERROR_REQUEST_URI; +import static javax.servlet.RequestDispatcher.ERROR_SERVLET_NAME; import static javax.servlet.RequestDispatcher.ERROR_STATUS_CODE; /** @@ -47,25 +48,81 @@ import static javax.servlet.RequestDispatcher.ERROR_STATUS_CODE; */ public class HttpChannelState { - private static final Logger LOG = Log.getLogger(HttpChannelState.class); + private static final Logger LOG = LoggerFactory.getLogger(HttpChannelState.class); private static final long DEFAULT_TIMEOUT = Long.getLong("org.eclipse.jetty.server.HttpChannelState.DEFAULT_TIMEOUT", 30000L); - /** + /* * The state of the HttpChannel,used to control the overall lifecycle. + *
+ * IDLE <-----> HANDLING ----> WAITING + * | ^ / + * | \ / + * v \ v + * UPGRADED WOKEN + **/ public enum State { - IDLE, // Idle request - DISPATCHED, // Request dispatched to filter/servlet - THROWN, // Exception thrown while DISPATCHED - ASYNC_WAIT, // Suspended and waiting - ASYNC_WOKEN, // Dispatch to handle from ASYNC_WAIT - ASYNC_IO, // Dispatched for async IO - ASYNC_ERROR, // Async error from ASYNC_WAIT - COMPLETING, // Response is completable - COMPLETED, // Response is completed - UPGRADED // Request upgraded the connection + IDLE, // Idle request + HANDLING, // Request dispatched to filter/servlet or Async IO callback + WAITING, // Suspended and waiting + WOKEN, // Dispatch to handle from ASYNC_WAIT + UPGRADED // Request upgraded the connection + } + + /* + * The state of the request processing lifecycle. + *
+ * BLOCKING <----> COMPLETING ---> COMPLETED + * ^ | ^ ^ + * / | \ | + * | | DISPATCH | + * | | ^ ^ | + * | v / | | + * | ASYNC -------> COMPLETE + * | | | ^ + * | v | | + * | EXPIRE | | + * \ | / | + * \ v / | + * EXPIRING ----------+ + *+ */ + private enum RequestState + { + BLOCKING, // Blocking request dispatched + ASYNC, // AsyncContext.startAsync() has been called + DISPATCH, // AsyncContext.dispatch() has been called + EXPIRE, // AsyncContext timeout has happened + EXPIRING, // AsyncListeners are being called + COMPLETE, // AsyncContext.complete() has been called + COMPLETING, // Request is being closed (maybe asynchronously) + COMPLETED // Response is completed + } + + /* + * The input readiness state, which works together with {@link HttpInput.State} + */ + private enum InputState + { + IDLE, // No isReady; No data + REGISTER, // isReady()==false handling; No data + REGISTERED, // isReady()==false !handling; No data + POSSIBLE, // isReady()==false async read callback called (http/1 only) + PRODUCING, // isReady()==false READ_PRODUCE action is being handled (http/1 only) + READY // isReady() was false, onContentAdded has been called + } + + /* + * The output committed state, which works together with {@link HttpOutput.State} + */ + private enum OutputState + { + OPEN, + COMMITTED, + COMPLETED, + ABORTED, } /** @@ -73,51 +130,28 @@ public class HttpChannelState */ public enum Action { - NOOP, // No action DISPATCH, // handle a normal request dispatch ASYNC_DISPATCH, // handle an async request dispatch - ERROR_DISPATCH, // handle a normal error + SEND_ERROR, // Generate an error page or error dispatch ASYNC_ERROR, // handle an async error + ASYNC_TIMEOUT, // call asyncContext onTimeout WRITE_CALLBACK, // handle an IO write callback + READ_REGISTER, // Register for fill interest READ_PRODUCE, // Check is a read is possible by parsing/filling READ_CALLBACK, // handle an IO read callback - COMPLETE, // Complete the response + COMPLETE, // Complete the response by closing output TERMINATED, // No further actions WAIT, // Wait for further events } - /** - * The state of the servlet async API. - */ - private enum Async - { - NOT_ASYNC, - STARTED, // AsyncContext.startAsync() has been called - DISPATCH, // AsyncContext.dispatch() has been called - COMPLETE, // AsyncContext.complete() has been called - EXPIRING, // AsyncContext timeout just happened - EXPIRED, // AsyncContext timeout has been processed - ERRORING, // An error just happened - ERRORED // The error has been processed - } - - private enum AsyncRead - { - IDLE, // No isReady; No data - REGISTER, // isReady()==false handling; No data - REGISTERED, // isReady()==false !handling; No data - POSSIBLE, // isReady()==false async read callback called (http/1 only) - PRODUCING, // isReady()==false READ_PRODUCE action is being handled (http/1 only) - READY // isReady() was false, onContentAdded has been called - } - - private final Locker _locker = new Locker(); private final HttpChannel _channel; private List
true
if more content may be available
+ * @return {@code true} if more content may be available
*/
public boolean onReadPossible()
{
boolean woken = false;
- try (Locker.Lock lock = _locker.lock())
+ synchronized (this)
{
if (LOG.isDebugEnabled())
LOG.debug("onReadPossible {}", toStringLocked());
- switch (_asyncRead)
+ switch (_inputState)
{
case REGISTERED:
- _asyncRead = AsyncRead.POSSIBLE;
- if (_state == State.ASYNC_WAIT)
+ _inputState = InputState.POSSIBLE;
+ if (_state == State.WAITING)
{
woken = true;
- _state = State.ASYNC_WOKEN;
+ _state = State.WOKEN;
}
break;
@@ -1310,22 +1386,22 @@ public class HttpChannelState
* Called to signal that a read has read -1.
* Will wake if the read was called while in ASYNC_WAIT state
*
- * @return true
if woken
+ * @return {@code true} if woken
*/
public boolean onReadEof()
{
boolean woken = false;
- try (Locker.Lock lock = _locker.lock())
+ synchronized (this)
{
if (LOG.isDebugEnabled())
LOG.debug("onEof {}", toStringLocked());
// Force read ready so onAllDataRead can be called
- _asyncRead = AsyncRead.READY;
- if (_state == State.ASYNC_WAIT)
+ _inputState = InputState.READY;
+ if (_state == State.WAITING)
{
woken = true;
- _state = State.ASYNC_WOKEN;
+ _state = State.WOKEN;
}
}
return woken;
@@ -1335,15 +1411,15 @@ public class HttpChannelState
{
boolean wake = false;
- try (Locker.Lock lock = _locker.lock())
+ synchronized (this)
{
if (LOG.isDebugEnabled())
LOG.debug("onWritePossible {}", toStringLocked());
_asyncWritePossible = true;
- if (_state == State.ASYNC_WAIT)
+ if (_state == State.WAITING)
{
- _state = State.ASYNC_WOKEN;
+ _state = State.WOKEN;
wake = true;
}
}
diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/HttpConfiguration.java b/jetty-server/src/main/java/org/eclipse/jetty/server/HttpConfiguration.java
index 26276476b4c..997364544a9 100644
--- a/jetty-server/src/main/java/org/eclipse/jetty/server/HttpConfiguration.java
+++ b/jetty-server/src/main/java/org/eclipse/jetty/server/HttpConfiguration.java
@@ -1,19 +1,19 @@
//
-// ========================================================================
-// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd.
-// ------------------------------------------------------------------------
-// All rights reserved. This program and the accompanying materials
-// are made available under the terms of the Eclipse Public License v1.0
-// and Apache License v2.0 which accompanies this distribution.
+// ========================================================================
+// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others.
//
-// The Eclipse Public License is available at
-// http://www.eclipse.org/legal/epl-v10.html
+// 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
//
-// The Apache License v2.0 is available at
-// http://www.opensource.org/licenses/apache2.0.php
+// 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
//
-// You may elect to redistribute this code under either of these licenses.
-// ========================================================================
+// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
+// ========================================================================
//
package org.eclipse.jetty.server;
@@ -34,13 +34,11 @@ import org.eclipse.jetty.util.annotation.ManagedAttribute;
import org.eclipse.jetty.util.annotation.ManagedObject;
import org.eclipse.jetty.util.component.Dumpable;
import org.eclipse.jetty.util.component.DumpableCollection;
-import org.eclipse.jetty.util.log.Log;
-import org.eclipse.jetty.util.log.Logger;
/**
* HTTP Configuration.
* This class is a holder of HTTP configuration for use by the - * {@link HttpChannel} class. Typically a HTTPConfiguration instance + * {@link HttpChannel} class. Typically an HTTPConfiguration instance * is instantiated and passed to a {@link ConnectionFactory} that can * create HTTP channels (e.g. HTTP, AJP or FCGI).
*The configuration held by this class is not for the wire protocol,
@@ -51,8 +49,6 @@ import org.eclipse.jetty.util.log.Logger;
@ManagedObject("HTTP Configuration")
public class HttpConfiguration implements Dumpable
{
- private static final Logger LOG = Log.getLogger(HttpConfiguration.class);
-
public static final String SERVER_VERSION = "Jetty(" + Jetty.VERSION + ")";
private final List The max idle time is applied to a HTTP request for IO operations and
+ * The max idle time is applied to an HTTP request for IO operations and
* delayed dispatch. The max idle time is applied to a HTTP request for IO operations and
+ * The max idle time is applied to an HTTP request for IO operations and
* delayed dispatch. A {@link Connection} that handles the HTTP protocol. {@link HttpOutput} implements {@link ServletOutputStream}
@@ -61,8 +58,67 @@ import org.eclipse.jetty.util.log.Logger;
*/
public class HttpOutput extends ServletOutputStream implements Runnable
{
- private static final String LSTRING_FILE = "javax.servlet.LocalStrings";
- private static ResourceBundle lStrings = ResourceBundle.getBundle(LSTRING_FILE);
+ /**
+ * The output state
+ */
+ enum State
+ {
+ OPEN, // Open
+ CLOSE, // Close needed from onWriteCompletion
+ CLOSING, // Close in progress after close API called
+ CLOSED // Closed
+ }
+
+ /**
+ * The API State which combines with the output State:
+ * If the Interceptor contains buffers then reset them.
@@ -126,11 +174,15 @@ public class HttpOutput extends ServletOutputStream implements Runnable
}
}
- private static Logger LOG = Log.getLogger(HttpOutput.class);
+ private static Logger LOG = LoggerFactory.getLogger(HttpOutput.class);
private static final ThreadLocal
@@ -71,11 +73,4 @@ public interface HttpTransport
* @param failure the failure that caused the abort.
*/
void abort(Throwable failure);
-
- /**
- * Is the underlying transport optimized for DirectBuffer usage
- *
- * @return True if direct buffers can be used optimally.
- */
- boolean isOptimizedForDirectBuffers();
}
diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/HttpWriter.java b/jetty-server/src/main/java/org/eclipse/jetty/server/HttpWriter.java
index 20b42e20760..ee89d1e1eea 100644
--- a/jetty-server/src/main/java/org/eclipse/jetty/server/HttpWriter.java
+++ b/jetty-server/src/main/java/org/eclipse/jetty/server/HttpWriter.java
@@ -1,19 +1,19 @@
//
-// ========================================================================
-// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd.
-// ------------------------------------------------------------------------
-// All rights reserved. This program and the accompanying materials
-// are made available under the terms of the Eclipse Public License v1.0
-// and Apache License v2.0 which accompanies this distribution.
+// ========================================================================
+// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others.
//
-// The Eclipse Public License is available at
-// http://www.eclipse.org/legal/epl-v10.html
+// 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
//
-// The Apache License v2.0 is available at
-// http://www.opensource.org/licenses/apache2.0.php
+// 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
//
-// You may elect to redistribute this code under either of these licenses.
-// ========================================================================
+// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
+// ========================================================================
//
package org.eclipse.jetty.server;
@@ -22,13 +22,14 @@ import java.io.IOException;
import java.io.Writer;
import org.eclipse.jetty.util.ByteArrayOutputStream2;
+import org.eclipse.jetty.util.Callback;
/**
*
*/
public abstract class HttpWriter extends Writer
{
- public static final int MAX_OUTPUT_CHARS = 512;
+ public static final int MAX_OUTPUT_CHARS = 512; // TODO should this be configurable? super size is 1024
final HttpOutput _out;
final ByteArrayOutputStream2 _bytes;
@@ -38,7 +39,7 @@ public abstract class HttpWriter extends Writer
{
_out = out;
_chars = new char[MAX_OUTPUT_CHARS];
- _bytes = new ByteArrayOutputStream2(MAX_OUTPUT_CHARS);
+ _bytes = new ByteArrayOutputStream2(MAX_OUTPUT_CHARS); // TODO should this be pooled - or do we just recycle the writer?
}
@Override
@@ -47,6 +48,11 @@ public abstract class HttpWriter extends Writer
_out.close();
}
+ public void complete(Callback callback)
+ {
+ _out.complete(callback);
+ }
+
@Override
public void flush() throws IOException
{
diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/InclusiveByteRange.java b/jetty-server/src/main/java/org/eclipse/jetty/server/InclusiveByteRange.java
index ac2e362f089..931538af2d1 100644
--- a/jetty-server/src/main/java/org/eclipse/jetty/server/InclusiveByteRange.java
+++ b/jetty-server/src/main/java/org/eclipse/jetty/server/InclusiveByteRange.java
@@ -1,19 +1,19 @@
//
-// ========================================================================
-// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd.
-// ------------------------------------------------------------------------
-// All rights reserved. This program and the accompanying materials
-// are made available under the terms of the Eclipse Public License v1.0
-// and Apache License v2.0 which accompanies this distribution.
+// ========================================================================
+// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others.
//
-// The Eclipse Public License is available at
-// http://www.eclipse.org/legal/epl-v10.html
+// 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
//
-// The Apache License v2.0 is available at
-// http://www.opensource.org/licenses/apache2.0.php
+// 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
//
-// You may elect to redistribute this code under either of these licenses.
-// ========================================================================
+// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
+// ========================================================================
//
package org.eclipse.jetty.server;
@@ -24,8 +24,8 @@ import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;
-import org.eclipse.jetty.util.log.Log;
-import org.eclipse.jetty.util.log.Logger;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* Byte range inclusive of end points.
@@ -52,7 +52,7 @@ import org.eclipse.jetty.util.log.Logger;
*/
public class InclusiveByteRange
{
- private static final Logger LOG = Log.getLogger(InclusiveByteRange.class);
+ private static final Logger LOG = LoggerFactory.getLogger(InclusiveByteRange.class);
private long first;
private long last;
@@ -237,14 +237,14 @@ public class InclusiveByteRange
catch (NumberFormatException e)
{
LOG.warn("Bad range format: {}", t);
- LOG.ignore(e);
+ LOG.trace("IGNORED", e);
}
}
}
catch (Exception e)
{
LOG.warn("Bad range format: {}", t);
- LOG.ignore(e);
+ LOG.trace("IGNORED", e);
}
}
diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/Iso88591HttpWriter.java b/jetty-server/src/main/java/org/eclipse/jetty/server/Iso88591HttpWriter.java
index 1c8c9b444df..db284303706 100644
--- a/jetty-server/src/main/java/org/eclipse/jetty/server/Iso88591HttpWriter.java
+++ b/jetty-server/src/main/java/org/eclipse/jetty/server/Iso88591HttpWriter.java
@@ -1,19 +1,19 @@
//
-// ========================================================================
-// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd.
-// ------------------------------------------------------------------------
-// All rights reserved. This program and the accompanying materials
-// are made available under the terms of the Eclipse Public License v1.0
-// and Apache License v2.0 which accompanies this distribution.
+// ========================================================================
+// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others.
//
-// The Eclipse Public License is available at
-// http://www.eclipse.org/legal/epl-v10.html
+// 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
//
-// The Apache License v2.0 is available at
-// http://www.opensource.org/licenses/apache2.0.php
+// 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
//
-// You may elect to redistribute this code under either of these licenses.
-// ========================================================================
+// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
+// ========================================================================
//
package org.eclipse.jetty.server;
@@ -35,11 +35,6 @@ public class Iso88591HttpWriter extends HttpWriter
public void write(char[] s, int offset, int length) throws IOException
{
HttpOutput out = _out;
- if (length == 0 && out.isAllContentWritten())
- {
- close();
- return;
- }
if (length == 1)
{
@@ -51,7 +46,7 @@ public class Iso88591HttpWriter extends HttpWriter
while (length > 0)
{
_bytes.reset();
- int chars = length > MAX_OUTPUT_CHARS ? MAX_OUTPUT_CHARS : length;
+ int chars = Math.min(length, MAX_OUTPUT_CHARS);
byte[] buffer = _bytes.getBuf();
int bytes = _bytes.getCount();
diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/LocalConnector.java b/jetty-server/src/main/java/org/eclipse/jetty/server/LocalConnector.java
index d1c353cfd97..93de8472028 100644
--- a/jetty-server/src/main/java/org/eclipse/jetty/server/LocalConnector.java
+++ b/jetty-server/src/main/java/org/eclipse/jetty/server/LocalConnector.java
@@ -1,19 +1,19 @@
//
-// ========================================================================
-// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd.
-// ------------------------------------------------------------------------
-// All rights reserved. This program and the accompanying materials
-// are made available under the terms of the Eclipse Public License v1.0
-// and Apache License v2.0 which accompanies this distribution.
+// ========================================================================
+// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others.
//
-// The Eclipse Public License is available at
-// http://www.eclipse.org/legal/epl-v10.html
+// 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
//
-// The Apache License v2.0 is available at
-// http://www.opensource.org/licenses/apache2.0.php
+// 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
//
-// You may elect to redistribute this code under either of these licenses.
-// ========================================================================
+// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
+// ========================================================================
//
package org.eclipse.jetty.server;
@@ -98,6 +98,8 @@ public class LocalConnector extends AbstractConnector
{
if (!isStarted())
throw new IllegalStateException("!STARTED");
+ if (isShutdown())
+ throw new IllegalStateException("Shutdown");
LocalEndPoint endp = new LocalEndPoint();
endp.addInput(rawRequest);
_connects.add(endp);
@@ -276,7 +278,7 @@ public class LocalConnector extends AbstractConnector
}
catch (Exception e)
{
- LOG.warn(e);
+ LOG.warn("Close wait failed", e);
}
}
}
@@ -302,7 +304,7 @@ public class LocalConnector extends AbstractConnector
}
catch (Exception e)
{
- LOG.warn(e);
+ LOG.warn("Close wait failed", e);
}
}
}
@@ -381,18 +383,6 @@ public class LocalConnector extends AbstractConnector
return false;
}
- @Override
- public int getHeaderCacheSize()
- {
- return 0;
- }
-
- @Override
- public boolean isHeaderCacheCaseSensitive()
- {
- return false;
- }
-
@Override
public void earlyEOF()
{
@@ -405,9 +395,8 @@ public class LocalConnector extends AbstractConnector
}
@Override
- public boolean startResponse(HttpVersion version, int status, String reason)
+ public void startResponse(HttpVersion version, int status, String reason)
{
- return false;
}
};
@@ -425,7 +414,7 @@ public class LocalConnector extends AbstractConnector
else
{
chunk = waitForOutput(time, unit);
- if (BufferUtil.isEmpty(chunk) && (!isOpen() || isOutputShutdown()))
+ if (BufferUtil.isEmpty(chunk) && (!isOpen() || isOutputShutdown() || isShutdown()))
{
parser.atEOF();
parser.parseNext(BufferUtil.EMPTY_BUFFER);
diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/LowResourceMonitor.java b/jetty-server/src/main/java/org/eclipse/jetty/server/LowResourceMonitor.java
index 7d888082d2e..aea31be30a6 100644
--- a/jetty-server/src/main/java/org/eclipse/jetty/server/LowResourceMonitor.java
+++ b/jetty-server/src/main/java/org/eclipse/jetty/server/LowResourceMonitor.java
@@ -1,19 +1,19 @@
//
-// ========================================================================
-// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd.
-// ------------------------------------------------------------------------
-// All rights reserved. This program and the accompanying materials
-// are made available under the terms of the Eclipse Public License v1.0
-// and Apache License v2.0 which accompanies this distribution.
+// ========================================================================
+// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others.
//
-// The Eclipse Public License is available at
-// http://www.eclipse.org/legal/epl-v10.html
+// 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
//
-// The Apache License v2.0 is available at
-// http://www.opensource.org/licenses/apache2.0.php
+// 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
//
-// You may elect to redistribute this code under either of these licenses.
-// ========================================================================
+// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
+// ========================================================================
//
package org.eclipse.jetty.server;
@@ -32,11 +32,11 @@ import org.eclipse.jetty.util.annotation.ManagedAttribute;
import org.eclipse.jetty.util.annotation.ManagedObject;
import org.eclipse.jetty.util.annotation.Name;
import org.eclipse.jetty.util.component.ContainerLifeCycle;
-import org.eclipse.jetty.util.log.Log;
-import org.eclipse.jetty.util.log.Logger;
import org.eclipse.jetty.util.thread.ScheduledExecutorScheduler;
import org.eclipse.jetty.util.thread.Scheduler;
import org.eclipse.jetty.util.thread.ThreadPool;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* A monitor for low resources, low resources can be detected by:
@@ -51,7 +51,7 @@ import org.eclipse.jetty.util.thread.ThreadPool;
@ManagedObject("Monitor for low resource conditions and activate a low resource mode if detected")
public class LowResourceMonitor extends ContainerLifeCycle
{
- private static final Logger LOG = Log.getLogger(LowResourceMonitor.class);
+ private static final Logger LOG = LoggerFactory.getLogger(LowResourceMonitor.class);
protected final Server _server;
private Scheduler _scheduler;
diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/MultiPartCleanerListener.java b/jetty-server/src/main/java/org/eclipse/jetty/server/MultiPartCleanerListener.java
deleted file mode 100644
index 4340ffbc842..00000000000
--- a/jetty-server/src/main/java/org/eclipse/jetty/server/MultiPartCleanerListener.java
+++ /dev/null
@@ -1,63 +0,0 @@
-//
-// ========================================================================
-// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd.
-// ------------------------------------------------------------------------
-// All rights reserved. This program and the accompanying materials
-// are made available under the terms of the Eclipse Public License v1.0
-// and Apache License v2.0 which accompanies this distribution.
-//
-// The Eclipse Public License is available at
-// http://www.eclipse.org/legal/epl-v10.html
-//
-// The Apache License v2.0 is available at
-// http://www.opensource.org/licenses/apache2.0.php
-//
-// You may elect to redistribute this code under either of these licenses.
-// ========================================================================
-//
-
-package org.eclipse.jetty.server;
-
-import javax.servlet.ServletRequestEvent;
-import javax.servlet.ServletRequestListener;
-
-import org.eclipse.jetty.server.handler.ContextHandler;
-
-public class MultiPartCleanerListener implements ServletRequestListener
-{
- public static final MultiPartCleanerListener INSTANCE = new MultiPartCleanerListener();
-
- protected MultiPartCleanerListener()
- {
- }
-
- @Override
- public void requestDestroyed(ServletRequestEvent sre)
- {
- //Clean up any tmp files created by MultiPartInputStream
- MultiParts parts = (MultiParts)sre.getServletRequest().getAttribute(Request.__MULTIPARTS);
- if (parts != null)
- {
- ContextHandler.Context context = parts.getContext();
-
- //Only do the cleanup if we are exiting from the context in which a servlet parsed the multipart files
- if (context == sre.getServletContext())
- {
- try
- {
- parts.close();
- }
- catch (Throwable e)
- {
- sre.getServletContext().log("Errors deleting multipart tmp files", e);
- }
- }
- }
- }
-
- @Override
- public void requestInitialized(ServletRequestEvent sre)
- {
- //nothing to do, multipart config set up by ServletHolder.handle()
- }
-}
diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/MultiPartFormInputStream.java b/jetty-server/src/main/java/org/eclipse/jetty/server/MultiPartFormInputStream.java
similarity index 79%
rename from jetty-http/src/main/java/org/eclipse/jetty/http/MultiPartFormInputStream.java
rename to jetty-server/src/main/java/org/eclipse/jetty/server/MultiPartFormInputStream.java
index 2494522e190..12b9555fbad 100644
--- a/jetty-http/src/main/java/org/eclipse/jetty/http/MultiPartFormInputStream.java
+++ b/jetty-server/src/main/java/org/eclipse/jetty/server/MultiPartFormInputStream.java
@@ -1,22 +1,22 @@
//
-// ========================================================================
-// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd.
-// ------------------------------------------------------------------------
-// All rights reserved. This program and the accompanying materials
-// are made available under the terms of the Eclipse Public License v1.0
-// and Apache License v2.0 which accompanies this distribution.
+// ========================================================================
+// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others.
//
-// The Eclipse Public License is available at
-// http://www.eclipse.org/legal/epl-v10.html
+// 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
//
-// The Apache License v2.0 is available at
-// http://www.opensource.org/licenses/apache2.0.php
+// 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
//
-// You may elect to redistribute this code under either of these licenses.
-// ========================================================================
+// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
+// ========================================================================
//
-package org.eclipse.jetty.http;
+package org.eclipse.jetty.server;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
@@ -31,46 +31,76 @@ import java.nio.ByteBuffer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
-import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
+import java.util.stream.Collectors;
import javax.servlet.MultipartConfigElement;
import javax.servlet.ServletInputStream;
import javax.servlet.http.Part;
import org.eclipse.jetty.util.BufferUtil;
import org.eclipse.jetty.util.ByteArrayOutputStream2;
-import org.eclipse.jetty.util.LazyList;
import org.eclipse.jetty.util.MultiException;
import org.eclipse.jetty.util.MultiMap;
import org.eclipse.jetty.util.QuotedStringTokenizer;
import org.eclipse.jetty.util.StringUtil;
-import org.eclipse.jetty.util.log.Log;
-import org.eclipse.jetty.util.log.Logger;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* MultiPartInputStream
*
* Handle a MultiPart Mime input stream, breaking it up on the boundary into files and strings.
+ *
+ * Deleting the parts can be done from a different thread if the parts are parsed asynchronously.
+ * Because of this we use the state to fail the parsing and coordinate which thread will delete any remaining parts.
+ * The deletion of parts is done by the cleanup thread in all cases except the transition from DELETING->DELETED which
+ * is done by the parsing thread.
+ * A ConnectionFactory whose connections detect whether the first bytes are
* TLS bytes and upgrades to either a TLS connection or to another configurable
* connection. Creates a new ConnectionFactory whose connections can upgrade to TLS or another protocol. If {@code otherProtocol} is {@code null}, and the first bytes are not TLS, then
- * {@link #otherProtocol(ByteBuffer, EndPoint)} is called. Callback method invoked when {@code otherProtocol} is {@code null}
- * and the first bytes are not TLS. Callback method invoked when the detected bytes are not TLS. This typically happens when a client is trying to connect to a TLS
* port using the {@code http} scheme (and not the {@code https} scheme). Legacy callback method invoked when {@code nextProtocol} is {@code null}
+ * and the first bytes are not TLS. This typically happens when a client is trying to connect to a TLS
+ * port using the {@code http} scheme (and not the {@code https} scheme). This method is kept around for backward compatibility. ConnectionFactory for the PROXY Protocol. Sets a TLV vector, see section 2.2.7 of the PROXY protocol specification. Gets a TLV vector, see section 2.2.7 of the PROXY protocol specification. {@link Response} provides the implementation for {@link HttpServletResponse}. In addition to the servlet standard handling, this method supports some additional codes:
+ * The Java {@link Files#isSameFile(Path, Path)} method is used to determine
+ * if the requested file is the same as the alias file.
+ *
+ * For File Systems that are case insensitive (eg: Microsoft Windows FAT32 and NTFS),
+ * the access to the file can be in any combination or style of upper and lowercase.
+ *
+ * For File Systems that normalize UTF-8 access (eg: Mac OSX on HFS+ or APFS,
+ * or Linux on XFS) the the actual file could be stored using UTF-16,
+ * but be accessed using NFD UTF-8 or NFC UTF-8 for the same file.
+ * Customizer that extracts the attribute from an {@link SSLContext}
@@ -48,7 +48,7 @@ import org.eclipse.jetty.util.ssl.X509;
*/
public class SecureRequestCustomizer implements HttpConfiguration.Customizer
{
- private static final Logger LOG = Log.getLogger(SecureRequestCustomizer.class);
+ private static final Logger LOG = LoggerFactory.getLogger(SecureRequestCustomizer.class);
/**
* The name of the SSLSession attribute that will contain any cached information.
@@ -57,6 +57,7 @@ public class SecureRequestCustomizer implements HttpConfiguration.Customizer
private String sslSessionAttribute = "org.eclipse.jetty.servlet.request.ssl_session";
+ private boolean _sniRequired;
private boolean _sniHostCheck;
private long _stsMaxAge = -1;
private boolean _stsIncludeSubDomains;
@@ -82,6 +83,22 @@ public class SecureRequestCustomizer implements HttpConfiguration.Customizer
@Name("stsMaxAgeSeconds") long stsMaxAgeSeconds,
@Name("stsIncludeSubdomains") boolean stsIncludeSubdomains)
{
+ this(false, sniHostCheck, stsMaxAgeSeconds, stsIncludeSubdomains);
+ }
+
+ /**
+ * @param sniRequired True if a SNI certificate is required.
+ * @param sniHostCheck True if the SNI Host name must match.
+ * @param stsMaxAgeSeconds The max age in seconds for a Strict-Transport-Security response header. If set less than zero then no header is sent.
+ * @param stsIncludeSubdomains If true, a include subdomain property is sent with any Strict-Transport-Security header
+ */
+ public SecureRequestCustomizer(
+ @Name("sniRequired") boolean sniRequired,
+ @Name("sniHostCheck") boolean sniHostCheck,
+ @Name("stsMaxAgeSeconds") long stsMaxAgeSeconds,
+ @Name("stsIncludeSubdomains") boolean stsIncludeSubdomains)
+ {
+ _sniRequired = sniRequired;
_sniHostCheck = sniHostCheck;
_stsMaxAge = stsMaxAgeSeconds;
_stsIncludeSubDomains = stsIncludeSubdomains;
@@ -89,7 +106,7 @@ public class SecureRequestCustomizer implements HttpConfiguration.Customizer
}
/**
- * @return True if the SNI Host name must match.
+ * @return True if the SNI Host name must match when there is an SNI certificate.
*/
public boolean isSniHostCheck()
{
@@ -97,13 +114,31 @@ public class SecureRequestCustomizer implements HttpConfiguration.Customizer
}
/**
- * @param sniHostCheck True if the SNI Host name must match.
+ * @param sniHostCheck True if the SNI Host name must match when there is an SNI certificate.
*/
public void setSniHostCheck(boolean sniHostCheck)
{
_sniHostCheck = sniHostCheck;
}
+ /**
+ * @return True if SNI is required, else requests will be rejected with 400 response.
+ * @see SslContextFactory.Server#isSniRequired()
+ */
+ public boolean isSniRequired()
+ {
+ return _sniRequired;
+ }
+
+ /**
+ * @param sniRequired True if SNI is required, else requests will be rejected with 400 response.
+ * @see SslContextFactory.Server#setSniRequired(boolean)
+ */
+ public void setSniRequired(boolean sniRequired)
+ {
+ _sniRequired = sniRequired;
+ }
+
/**
* @return The max age in seconds for a Strict-Transport-Security response header. If set less than zero then no header is sent.
*/
@@ -208,19 +243,23 @@ public class SecureRequestCustomizer implements HttpConfiguration.Customizer
{
SSLSession sslSession = sslEngine.getSession();
- if (_sniHostCheck)
+ if (_sniHostCheck || _sniRequired)
{
String name = request.getServerName();
X509 x509 = (X509)sslSession.getValue(SniX509ExtendedKeyManager.SNI_X509);
- if (x509 != null && !x509.matches(name))
+ if (LOG.isDebugEnabled())
+ LOG.debug("Host {} with SNI {}", name, x509);
+
+ if (x509 == null)
+ {
+ if (_sniRequired)
+ throw new BadMessageException(400, "SNI required");
+ }
+ else if (_sniHostCheck && !x509.matches(name))
{
- LOG.warn("Host {} does not match SNI {}", name, x509);
throw new BadMessageException(400, "Host does not match SNI");
}
-
- if (LOG.isDebugEnabled())
- LOG.debug("Host {} matched SNI {}", name, x509);
}
try
@@ -259,7 +298,7 @@ public class SecureRequestCustomizer implements HttpConfiguration.Customizer
}
catch (Exception e)
{
- LOG.warn(Log.EXCEPTION, e);
+ LOG.warn("Unable to customize request with encryption details", e);
}
}
diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/Server.java b/jetty-server/src/main/java/org/eclipse/jetty/server/Server.java
index d2ffc2f564e..d9ade6e27d4 100644
--- a/jetty-server/src/main/java/org/eclipse/jetty/server/Server.java
+++ b/jetty-server/src/main/java/org/eclipse/jetty/server/Server.java
@@ -1,19 +1,19 @@
//
-// ========================================================================
-// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd.
-// ------------------------------------------------------------------------
-// All rights reserved. This program and the accompanying materials
-// are made available under the terms of the Eclipse Public License v1.0
-// and Apache License v2.0 which accompanies this distribution.
+// ========================================================================
+// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others.
//
-// The Eclipse Public License is available at
-// http://www.eclipse.org/legal/epl-v10.html
+// 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
//
-// The Apache License v2.0 is available at
-// http://www.opensource.org/licenses/apache2.0.php
+// 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
//
-// You may elect to redistribute this code under either of these licenses.
-// ========================================================================
+// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
+// ========================================================================
//
package org.eclipse.jetty.server;
@@ -27,7 +27,7 @@ import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
-import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
@@ -44,7 +44,6 @@ import org.eclipse.jetty.http.PreEncodedHttpField;
import org.eclipse.jetty.server.handler.ContextHandler;
import org.eclipse.jetty.server.handler.ErrorHandler;
import org.eclipse.jetty.server.handler.HandlerWrapper;
-import org.eclipse.jetty.server.handler.StatisticsHandler;
import org.eclipse.jetty.util.Attributes;
import org.eclipse.jetty.util.Jetty;
import org.eclipse.jetty.util.MultiException;
@@ -54,13 +53,14 @@ import org.eclipse.jetty.util.annotation.ManagedAttribute;
import org.eclipse.jetty.util.annotation.ManagedObject;
import org.eclipse.jetty.util.annotation.Name;
import org.eclipse.jetty.util.component.AttributeContainerMap;
+import org.eclipse.jetty.util.component.Graceful;
import org.eclipse.jetty.util.component.LifeCycle;
-import org.eclipse.jetty.util.log.Log;
-import org.eclipse.jetty.util.log.Logger;
-import org.eclipse.jetty.util.thread.Locker;
+import org.eclipse.jetty.util.thread.AutoLock;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.eclipse.jetty.util.thread.ShutdownThread;
import org.eclipse.jetty.util.thread.ThreadPool;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* Jetty HTTP Servlet Server.
@@ -72,20 +72,21 @@ import org.eclipse.jetty.util.thread.ThreadPool;
@ManagedObject(value = "Jetty HTTP Servlet server")
public class Server extends HandlerWrapper implements Attributes
{
- private static final Logger LOG = Log.getLogger(Server.class);
+ private static final Logger LOG = LoggerFactory.getLogger(Server.class);
private final AttributeContainerMap _attributes = new AttributeContainerMap();
private final ThreadPool _threadPool;
private final List This method can be called from {@link #handle(String, Request, HttpServletRequest, HttpServletResponse)} when an {@link DispatcherType#ERROR} dispatch
- * is detected and an error page needs to be generated by calling {@link HttpServletResponse#sendError(int, String)} with the appropriate code and reason,
- * which are taken from {@link HttpServletRequest#getAttribute(String)} for {@link RequestDispatcher#ERROR_STATUS_CODE} and {@link RequestDispatcher#ERROR_MESSAGE}
- *
+ * Deprecated error page generation
* @param target The target of the request - either a URI or a name.
* @param baseRequest The original unwrapped request object.
* @param request The request either as the {@link Request} object or a wrapper of that request. The
@@ -81,21 +74,16 @@ public abstract class AbstractHandler extends ContainerLifeCycle implements Hand
* method can be used access the Response object if required.
* @throws IOException if unable to handle the request or response processing
* @throws ServletException if unable to handle the request or response due to underlying servlet issue
- * @see ErrorDispatchHandler for a convenience class that calls this method.
*/
+ @Deprecated
protected void doError(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
Object o = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
int code = (o instanceof Integer) ? ((Integer)o).intValue() : (o != null ? Integer.parseInt(o.toString()) : 500);
- o = request.getAttribute(RequestDispatcher.ERROR_MESSAGE);
- String reason = o != null ? o.toString() : null;
-
- response.sendError(code, reason);
+ response.setStatus(code);
+ baseRequest.setHandled(true);
}
- /*
- * @see org.eclipse.thread.LifeCycle#start()
- */
@Override
protected void doStart() throws Exception
{
@@ -106,9 +94,6 @@ public abstract class AbstractHandler extends ContainerLifeCycle implements Hand
super.doStart();
}
- /*
- * @see org.eclipse.thread.LifeCycle#stop()
- */
@Override
protected void doStop() throws Exception
{
@@ -123,7 +108,7 @@ public abstract class AbstractHandler extends ContainerLifeCycle implements Hand
if (_server == server)
return;
if (isStarted())
- throw new IllegalStateException(STARTED);
+ throw new IllegalStateException(getState());
_server = server;
}
@@ -147,7 +132,9 @@ public abstract class AbstractHandler extends ContainerLifeCycle implements Hand
* {@link DispatcherType#ERROR} dispatches are handled by calling the {@link #doError(String, Request, HttpServletRequest, HttpServletResponse)}
* method. All other dispatches are passed to the abstract {@link #doNonErrorHandle(String, Request, HttpServletRequest, HttpServletResponse)}
* method, which should be implemented with specific handler behavior
+ * @deprecated This class is no longer required as ERROR dispatch is only done if there is an error page target.
*/
+ @Deprecated
public abstract static class ErrorDispatchHandler extends AbstractHandler
{
@Override
@@ -174,6 +161,7 @@ public abstract class AbstractHandler extends ContainerLifeCycle implements Hand
* @throws IOException if unable to handle the request or response processing
* @throws ServletException if unable to handle the request or response due to underlying servlet issue
*/
+ @Deprecated
protected abstract void doNonErrorHandle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException;
}
}
diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/handler/AbstractHandlerContainer.java b/jetty-server/src/main/java/org/eclipse/jetty/server/handler/AbstractHandlerContainer.java
index e56645f5dcf..474f6107240 100644
--- a/jetty-server/src/main/java/org/eclipse/jetty/server/handler/AbstractHandlerContainer.java
+++ b/jetty-server/src/main/java/org/eclipse/jetty/server/handler/AbstractHandlerContainer.java
@@ -1,38 +1,32 @@
//
-// ========================================================================
-// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd.
-// ------------------------------------------------------------------------
-// All rights reserved. This program and the accompanying materials
-// are made available under the terms of the Eclipse Public License v1.0
-// and Apache License v2.0 which accompanies this distribution.
+// ========================================================================
+// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others.
//
-// The Eclipse Public License is available at
-// http://www.eclipse.org/legal/epl-v10.html
+// 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
//
-// The Apache License v2.0 is available at
-// http://www.opensource.org/licenses/apache2.0.php
+// 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
//
-// You may elect to redistribute this code under either of these licenses.
-// ========================================================================
+// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
+// ========================================================================
//
package org.eclipse.jetty.server.handler;
import java.util.ArrayList;
import java.util.Arrays;
-import java.util.Date;
import java.util.List;
-import java.util.concurrent.Future;
-import java.util.concurrent.TimeUnit;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.HandlerContainer;
import org.eclipse.jetty.server.Server;
-import org.eclipse.jetty.util.Callback;
-import org.eclipse.jetty.util.MultiException;
-import org.eclipse.jetty.util.component.Graceful;
-import org.eclipse.jetty.util.log.Log;
-import org.eclipse.jetty.util.log.Logger;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* Abstract Handler Container.
@@ -40,7 +34,7 @@ import org.eclipse.jetty.util.log.Logger;
*/
public abstract class AbstractHandlerContainer extends AbstractHandler implements HandlerContainer
{
- private static final Logger LOG = Log.getLogger(AbstractHandlerContainer.class);
+ private static final Logger LOG = LoggerFactory.getLogger(AbstractHandlerContainer.class);
public AbstractHandlerContainer()
{
@@ -128,7 +122,7 @@ public abstract class AbstractHandlerContainer extends AbstractHandler implement
return;
if (isStarted())
- throw new IllegalStateException(STARTED);
+ throw new IllegalStateException(getState());
super.setServer(server);
Handler[] handlers = getHandlers();
@@ -138,62 +132,4 @@ public abstract class AbstractHandlerContainer extends AbstractHandler implement
h.setServer(server);
}
}
-
- /**
- * Shutdown nested Gracefule handlers
- *
- * @param futures A list of Futures which must also be waited on for the shutdown (or null)
- * returns A MultiException to which any failures are added or null
- */
- protected void doShutdown(List
- * A partial implementation of {@link javax.servlet.ServletContext}. A complete implementation is provided by the derived {@link ContextHandler}.
+ * A partial implementation of {@link javax.servlet.ServletContext}. A complete implementation is provided by the
+ * derived {@link ContextHandler} implementations.
* This method is called for each mime type in the users agent's
- * This method is called for each mime type in the users agent's
+ * The default implementation handles "text/html", "text/*" and "*/*".
+ * The method can be overridden to handle other types. Implementations must
+ * immediate produce a response and may not be async.
+ * Problem accessing ");
- write(writer, uri);
- writer.write(". Reason:\n Generate a error response body to be sent for a bad message.
+ * Generate an error response body to be sent for a bad message.
* In this case there is something wrong with the request, so either
* a request cannot be built, or it is not safe to build a request.
* This method allows for a simple error page body to be returned
@@ -382,6 +546,22 @@ public class ErrorHandler extends AbstractHandler
_cacheControl = cacheControl;
}
+ /**
+ * @return True if the error page will show the Servlet that generated the error
+ */
+ public boolean isShowServlet()
+ {
+ return _showServlet;
+ }
+
+ /**
+ * @param showServlet True if the error page will show the Servlet that generated the error
+ */
+ public void setShowServlet(boolean showServlet)
+ {
+ _showServlet = showServlet;
+ }
+
/**
* @return True if stack traces are shown in the error pages
*/
diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/handler/HandlerCollection.java b/jetty-server/src/main/java/org/eclipse/jetty/server/handler/HandlerCollection.java
index dfea9fc93b7..f677a9cccbb 100644
--- a/jetty-server/src/main/java/org/eclipse/jetty/server/handler/HandlerCollection.java
+++ b/jetty-server/src/main/java/org/eclipse/jetty/server/handler/HandlerCollection.java
@@ -1,19 +1,19 @@
//
-// ========================================================================
-// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd.
-// ------------------------------------------------------------------------
-// All rights reserved. This program and the accompanying materials
-// are made available under the terms of the Eclipse Public License v1.0
-// and Apache License v2.0 which accompanies this distribution.
+// ========================================================================
+// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others.
//
-// The Eclipse Public License is available at
-// http://www.eclipse.org/legal/epl-v10.html
+// 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
//
-// The Apache License v2.0 is available at
-// http://www.opensource.org/licenses/apache2.0.php
+// 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
//
-// You may elect to redistribute this code under either of these licenses.
-// ========================================================================
+// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
+// ========================================================================
//
package org.eclipse.jetty.server.handler;
@@ -82,7 +82,7 @@ public class HandlerCollection extends AbstractHandlerContainer
public void setHandlers(Handler[] handlers)
{
if (!_mutableWhenRunning && isStarted())
- throw new IllegalStateException(STARTED);
+ throw new IllegalStateException(getState());
while (true)
{
diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/handler/HandlerList.java b/jetty-server/src/main/java/org/eclipse/jetty/server/handler/HandlerList.java
index 82c142e899e..2507ea9322e 100644
--- a/jetty-server/src/main/java/org/eclipse/jetty/server/handler/HandlerList.java
+++ b/jetty-server/src/main/java/org/eclipse/jetty/server/handler/HandlerList.java
@@ -1,19 +1,19 @@
//
-// ========================================================================
-// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd.
-// ------------------------------------------------------------------------
-// All rights reserved. This program and the accompanying materials
-// are made available under the terms of the Eclipse Public License v1.0
-// and Apache License v2.0 which accompanies this distribution.
+// ========================================================================
+// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others.
//
-// The Eclipse Public License is available at
-// http://www.eclipse.org/legal/epl-v10.html
+// 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
//
-// The Apache License v2.0 is available at
-// http://www.opensource.org/licenses/apache2.0.php
+// 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
//
-// You may elect to redistribute this code under either of these licenses.
-// ========================================================================
+// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
+// ========================================================================
//
package org.eclipse.jetty.server.handler;
@@ -43,9 +43,6 @@ public class HandlerList extends HandlerCollection
super(handlers);
}
- /**
- * @see Handler#handle(String, Request, HttpServletRequest, HttpServletResponse)
- */
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/handler/HandlerWrapper.java b/jetty-server/src/main/java/org/eclipse/jetty/server/handler/HandlerWrapper.java
index 27a53fecf98..86d58347660 100644
--- a/jetty-server/src/main/java/org/eclipse/jetty/server/handler/HandlerWrapper.java
+++ b/jetty-server/src/main/java/org/eclipse/jetty/server/handler/HandlerWrapper.java
@@ -1,19 +1,19 @@
//
-// ========================================================================
-// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd.
-// ------------------------------------------------------------------------
-// All rights reserved. This program and the accompanying materials
-// are made available under the terms of the Eclipse Public License v1.0
-// and Apache License v2.0 which accompanies this distribution.
+// ========================================================================
+// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others.
//
-// The Eclipse Public License is available at
-// http://www.eclipse.org/legal/epl-v10.html
+// 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
//
-// The Apache License v2.0 is available at
-// http://www.opensource.org/licenses/apache2.0.php
+// 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
//
-// You may elect to redistribute this code under either of these licenses.
-// ========================================================================
+// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
+// ========================================================================
//
package org.eclipse.jetty.server.handler;
@@ -74,7 +74,7 @@ public class HandlerWrapper extends AbstractHandlerContainer
public void setHandler(Handler handler)
{
if (isStarted())
- throw new IllegalStateException(STARTED);
+ throw new IllegalStateException(getState());
// check for loops
if (handler == this || (handler instanceof HandlerContainer &&
diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/handler/HotSwapHandler.java b/jetty-server/src/main/java/org/eclipse/jetty/server/handler/HotSwapHandler.java
index b78146f8505..162d1ce3f89 100644
--- a/jetty-server/src/main/java/org/eclipse/jetty/server/handler/HotSwapHandler.java
+++ b/jetty-server/src/main/java/org/eclipse/jetty/server/handler/HotSwapHandler.java
@@ -1,19 +1,19 @@
//
-// ========================================================================
-// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd.
-// ------------------------------------------------------------------------
-// All rights reserved. This program and the accompanying materials
-// are made available under the terms of the Eclipse Public License v1.0
-// and Apache License v2.0 which accompanies this distribution.
+// ========================================================================
+// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others.
//
-// The Eclipse Public License is available at
-// http://www.eclipse.org/legal/epl-v10.html
+// 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
//
-// The Apache License v2.0 is available at
-// http://www.opensource.org/licenses/apache2.0.php
+// 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
//
-// You may elect to redistribute this code under either of these licenses.
-// ========================================================================
+// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
+// ========================================================================
//
package org.eclipse.jetty.server.handler;
@@ -81,27 +81,18 @@ public class HotSwapHandler extends AbstractHandlerContainer
}
}
- /*
- * @see org.eclipse.thread.AbstractLifeCycle#doStart()
- */
@Override
protected void doStart() throws Exception
{
super.doStart();
}
- /*
- * @see org.eclipse.thread.AbstractLifeCycle#doStop()
- */
@Override
protected void doStop() throws Exception
{
super.doStop();
}
- /*
- * @see org.eclipse.jetty.server.server.EventHandler#handle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
- */
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/handler/IdleTimeoutHandler.java b/jetty-server/src/main/java/org/eclipse/jetty/server/handler/IdleTimeoutHandler.java
index c6d260eb74a..e1a96242b7d 100644
--- a/jetty-server/src/main/java/org/eclipse/jetty/server/handler/IdleTimeoutHandler.java
+++ b/jetty-server/src/main/java/org/eclipse/jetty/server/handler/IdleTimeoutHandler.java
@@ -1,19 +1,19 @@
//
-// ========================================================================
-// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd.
-// ------------------------------------------------------------------------
-// All rights reserved. This program and the accompanying materials
-// are made available under the terms of the Eclipse Public License v1.0
-// and Apache License v2.0 which accompanies this distribution.
+// ========================================================================
+// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others.
//
-// The Eclipse Public License is available at
-// http://www.eclipse.org/legal/epl-v10.html
+// 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
//
-// The Apache License v2.0 is available at
-// http://www.opensource.org/licenses/apache2.0.php
+// 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
//
-// You may elect to redistribute this code under either of these licenses.
-// ========================================================================
+// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
+// ========================================================================
//
package org.eclipse.jetty.server.handler;
diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/handler/InetAccessHandler.java b/jetty-server/src/main/java/org/eclipse/jetty/server/handler/InetAccessHandler.java
index bf2a96cffe6..e35b6bce96d 100644
--- a/jetty-server/src/main/java/org/eclipse/jetty/server/handler/InetAccessHandler.java
+++ b/jetty-server/src/main/java/org/eclipse/jetty/server/handler/InetAccessHandler.java
@@ -1,19 +1,19 @@
//
-// ========================================================================
-// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd.
-// ------------------------------------------------------------------------
-// All rights reserved. This program and the accompanying materials
-// are made available under the terms of the Eclipse Public License v1.0
-// and Apache License v2.0 which accompanies this distribution.
+// ========================================================================
+// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others.
//
-// The Eclipse Public License is available at
-// http://www.eclipse.org/legal/epl-v10.html
+// 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
//
-// The Apache License v2.0 is available at
-// http://www.opensource.org/licenses/apache2.0.php
+// 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
//
-// You may elect to redistribute this code under either of these licenses.
-// ========================================================================
+// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
+// ========================================================================
//
package org.eclipse.jetty.server.handler;
@@ -26,15 +26,19 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.http.HttpStatus;
+import org.eclipse.jetty.http.pathmap.PathSpec;
import org.eclipse.jetty.io.EndPoint;
import org.eclipse.jetty.server.HttpChannel;
import org.eclipse.jetty.server.Request;
-import org.eclipse.jetty.util.IncludeExclude;
import org.eclipse.jetty.util.IncludeExcludeSet;
+import org.eclipse.jetty.util.InetAddressPattern;
import org.eclipse.jetty.util.InetAddressSet;
import org.eclipse.jetty.util.component.DumpableCollection;
-import org.eclipse.jetty.util.log.Log;
-import org.eclipse.jetty.util.log.Logger;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import static org.eclipse.jetty.server.handler.InetAccessSet.AccessTuple;
+import static org.eclipse.jetty.server.handler.InetAccessSet.PatternTuple;
/**
* InetAddress Access Handler
@@ -43,18 +47,13 @@ import org.eclipse.jetty.util.log.Logger;
* provided by and {@link IncludeExcludeSet} over a {@link InetAddressSet}. This
* handler uses the real internet address of the connection, not one reported in
* the forwarded for headers, as this cannot be as easily forged.
- *
- * Additionally, there may be times when you want to only apply this handler to
- * a subset of your connectors. In this situation you can use
- * connectorNames to specify the connector names that you want this IP
- * access filter to apply to.
+ * The connector name is separated from the InetAddress pattern with an '@' character,
+ * and the InetAddress pattern is separated from the URI pattern using the "|" (pipe)
+ * character. URI patterns follow the servlet specification for simple * prefix and
+ * suffix wild cards (e.g. /, /foo, /foo/bar, /foo/bar/*, *.baz). The connector name is separated from the InetAddress pattern with an '@' character,
+ * and the InetAddress pattern is separated from the URI pattern using the "|" (pipe)
+ * character. URI patterns follow the servlet specification for simple * prefix and
+ * suffix wild cards (e.g. /, /foo, /foo/bar, /foo/bar/*, *.baz). Handler to limit the threads per IP address for DOS protection
+ * Sizes below {@link #BREAK_EVEN_GZIP_SIZE} will result a compressed response that is larger than the
+ * original data.
+ *
- * Should always see WARN level messages, regardless of set level.
- *
- * @throws UnsupportedEncodingException failed test
- */
- @Test
- public void testWarnFiltering() throws UnsupportedEncodingException
- {
- StdErrLog log = new StdErrLog(StdErrLogTest.class.getName(), new Properties());
- try (StacklessLogging stackless = new StacklessLogging(log))
- {
- StdErrCapture output = new StdErrCapture(log);
-
- // Start with default level
- log.warn("See Me");
-
- // Set to debug level
- log.setLevel(StdErrLog.LEVEL_DEBUG);
- log.warn("Hear Me");
-
- // Set to warn level
- log.setLevel(StdErrLog.LEVEL_WARN);
- log.warn("Cheer Me");
-
- log.warn("
- * Should only see INFO level messages when level is set to {@link StdErrLog#LEVEL_INFO} and below.
- *
- * @throws Exception failed test
- */
- @Test
- public void testInfoFiltering() throws Exception
- {
- StdErrLog log = new StdErrLog(StdErrLogTest.class.getName(), new Properties());
- try (StacklessLogging stackless = new StacklessLogging(log))
- {
- StdErrCapture output = new StdErrCapture(log);
-
- // Normal/Default behavior
- log.info("I will not buy");
-
- // Level Debug
- log.setLevel(StdErrLog.LEVEL_DEBUG);
- log.info("this record");
-
- // Level All
- log.setLevel(StdErrLog.LEVEL_ALL);
- log.info("it is scratched.");
-
- log.info("
- * Should only see DEBUG level messages when level is set to {@link StdErrLog#LEVEL_DEBUG} and below.
- *
- * @throws Exception failed test
- */
- @Test
- public void testDebugFiltering() throws Exception
- {
- StdErrLog log = new StdErrLog(StdErrLogTest.class.getName(), new Properties());
- try (StacklessLogging stackless = new StacklessLogging(log))
- {
- StdErrCapture output = new StdErrCapture(log);
-
- // Normal/Default behavior
- log.debug("Tobacconist");
- log.debug("
- * Should only see IGNORED level messages when level is set to {@link StdErrLog#LEVEL_ALL}.
- *
- * @throws Exception failed test
- */
- @Test
- public void testIgnores() throws Exception
- {
- StdErrLog log = new StdErrLog(StdErrLogTest.class.getName(), new Properties());
- try (StacklessLogging stackless = new StacklessLogging(log))
- {
- StdErrCapture output = new StdErrCapture(log);
-
- // Normal/Default behavior
- log.ignore(new Throwable("IGNORE ME"));
-
- // Show Ignored
- log.setLevel(StdErrLog.LEVEL_ALL);
- log.ignore(new Throwable("Don't ignore me"));
-
- // Set to Debug level
- log.setLevel(StdErrLog.LEVEL_DEBUG);
- log.ignore(new Throwable("Debug me"));
-
- // Validate Output
- // System.err.print(output);
- output.assertNotContains("IGNORE ME");
- output.assertContains("Don't ignore me");
- output.assertNotContains("Debug me");
- }
- }
-
- @Test
- public void testIsDebugEnabled() throws Exception
- {
- StdErrLog log = new StdErrLog(StdErrLogTest.class.getName(), new Properties());
- try (StacklessLogging stackless = new StacklessLogging(log))
- {
- log.setLevel(StdErrLog.LEVEL_ALL);
- assertThat("log.level(all).isDebugEnabled", log.isDebugEnabled(), is(true));
-
- log.setLevel(StdErrLog.LEVEL_DEBUG);
- assertThat("log.level(debug).isDebugEnabled", log.isDebugEnabled(), is(true));
-
- log.setLevel(StdErrLog.LEVEL_INFO);
- assertThat("log.level(info).isDebugEnabled", log.isDebugEnabled(), is(false));
-
- log.setLevel(StdErrLog.LEVEL_WARN);
- assertThat("log.level(warn).isDebugEnabled", log.isDebugEnabled(), is(false));
-
- log.setLevel(StdErrLog.LEVEL_OFF);
- assertThat("log.level(off).isDebugEnabled", log.isDebugEnabled(), is(false));
- }
- }
-
- @Test
- public void testSetGetLevel()
- {
- StdErrLog log = new StdErrLog(StdErrLogTest.class.getName(), new Properties());
- try (StacklessLogging stackless = new StacklessLogging(log))
- {
- log.setLevel(StdErrLog.LEVEL_ALL);
- assertThat("log.level(all).getLevel()", log.getLevel(), is(StdErrLog.LEVEL_ALL));
-
- log.setLevel(StdErrLog.LEVEL_DEBUG);
- assertThat("log.level(debug).getLevel()", log.getLevel(), is(StdErrLog.LEVEL_DEBUG));
-
- log.setLevel(StdErrLog.LEVEL_INFO);
- assertThat("log.level(info).getLevel()", log.getLevel(), is(StdErrLog.LEVEL_INFO));
-
- log.setLevel(StdErrLog.LEVEL_WARN);
- assertThat("log.level(warn).getLevel()", log.getLevel(), is(StdErrLog.LEVEL_WARN));
-
- log.setLevel(StdErrLog.LEVEL_OFF);
- assertThat("log.level(off).getLevel()", log.getLevel(), is(StdErrLog.LEVEL_OFF));
- }
- }
-
- @Test
- public void testGetChildLogger_Simple()
- {
- String baseName = "jetty";
- StdErrLog log = new StdErrLog(baseName, new Properties());
- try (StacklessLogging stackless = new StacklessLogging(log))
- {
- assertThat("Logger.name", log.getName(), is("jetty"));
-
- Logger log2 = log.getLogger("child");
- assertThat("Logger.child.name", log2.getName(), is("jetty.child"));
- }
- }
-
- @Test
- public void testGetChildLogger_Deep()
- {
- String baseName = "jetty";
- StdErrLog log = new StdErrLog(baseName, new Properties());
- try (StacklessLogging stackless = new StacklessLogging(log))
- {
- assertThat("Logger.name", log.getName(), is("jetty"));
-
- Logger log2 = log.getLogger("child.of.the.sixties");
- assertThat("Logger.child.name", log2.getName(), is("jetty.child.of.the.sixties"));
- }
- }
-
- @Test
- public void testGetChildLogger_Null()
- {
- String baseName = "jetty";
- StdErrLog log = new StdErrLog(baseName, new Properties());
- try (StacklessLogging stackless = new StacklessLogging(log))
- {
- assertThat("Logger.name", log.getName(), is("jetty"));
-
- // Pass null as child reference, should return parent logger
- Logger log2 = log.getLogger((String)null);
- assertThat("Logger.child.name", log2.getName(), is("jetty"));
- assertSame(log2, log, "Should have returned same logger");
- }
- }
-
- @Test
- public void testGetChildLogger_EmptyName()
- {
- String baseName = "jetty";
- StdErrLog log = new StdErrLog(baseName, new Properties());
- try (StacklessLogging stackless = new StacklessLogging(log))
- {
- assertThat("Logger.name", log.getName(), is("jetty"));
-
- // Pass empty name as child reference, should return parent logger
- Logger log2 = log.getLogger("");
- assertThat("Logger.child.name", log2.getName(), is("jetty"));
- assertSame(log2, log, "Should have returned same logger");
- }
- }
-
- @Test
- public void testGetChildLogger_EmptyNameSpaces()
- {
- String baseName = "jetty";
- StdErrLog log = new StdErrLog(baseName, new Properties());
- try (StacklessLogging stackless = new StacklessLogging(log))
- {
- assertThat("Logger.name", log.getName(), is("jetty"));
-
- // Pass empty name as child reference, should return parent logger
- Logger log2 = log.getLogger(" ");
- assertThat("Logger.child.name", log2.getName(), is("jetty"));
- assertSame(log2, log, "Should have returned same logger");
- }
- }
-
- @Test
- public void testGetChildLogger_NullParent()
- {
- AbstractLogger log = new StdErrLog(null, new Properties());
-
- assertThat("Logger.name", log.getName(), is(""));
-
- Logger log2 = log.getLogger("jetty");
- assertThat("Logger.child.name", log2.getName(), is("jetty"));
- assertNotSame(log2, log, "Should have returned same logger");
- }
-
- @Test
- public void testToString()
- {
- StdErrLog log = new StdErrLog("jetty", new Properties());
-
- log.setLevel(StdErrLog.LEVEL_ALL);
- assertThat("Logger.toString", log.toString(), is("StdErrLog:jetty:LEVEL=ALL"));
-
- log.setLevel(StdErrLog.LEVEL_DEBUG);
- assertThat("Logger.toString", log.toString(), is("StdErrLog:jetty:LEVEL=DEBUG"));
-
- log.setLevel(StdErrLog.LEVEL_INFO);
- assertThat("Logger.toString", log.toString(), is("StdErrLog:jetty:LEVEL=INFO"));
-
- log.setLevel(StdErrLog.LEVEL_WARN);
- assertThat("Logger.toString", log.toString(), is("StdErrLog:jetty:LEVEL=WARN"));
-
- log.setLevel(99); // intentionally bogus level
- assertThat("Logger.toString", log.toString(), is("StdErrLog:jetty:LEVEL=?"));
- }
-
- @Test
- public void testPrintSource() throws UnsupportedEncodingException
- {
- Properties props = new Properties();
- props.put("test.SOURCE", "true");
- StdErrLog log = new StdErrLog("test", props);
- log.setLevel(StdErrLog.LEVEL_DEBUG);
-
- ByteArrayOutputStream test = new ByteArrayOutputStream();
- PrintStream err = new PrintStream(test);
- log.setStdErrStream(err);
-
- log.debug("Show me the source!");
-
- String output = new String(test.toByteArray(), StandardCharsets.UTF_8);
- // System.err.print(output);
-
- assertThat(output, containsString(".StdErrLogTest#testPrintSource(StdErrLogTest.java:"));
-
- props.put("test.SOURCE", "false");
- log = new StdErrLog("other", props);
- }
-
- @Test
- public void testConfiguredAndSetDebugEnabled()
- {
- Properties props = new Properties();
- props.setProperty("org.eclipse.jetty.util.LEVEL", "WARN");
- props.setProperty("org.eclipse.jetty.io.LEVEL", "WARN");
-
- StdErrLog root = new StdErrLog("", props);
- assertLevel(root, StdErrLog.LEVEL_INFO); // default
-
- StdErrLog log = (StdErrLog)root.getLogger(StdErrLogTest.class.getName());
- assertThat("Log.isDebugEnabled()", log.isDebugEnabled(), is(false));
- assertLevel(log, StdErrLog.LEVEL_WARN); // as configured
-
- // Boot stomp it all to debug
- root.setDebugEnabled(true);
- assertThat("Log.isDebugEnabled()", log.isDebugEnabled(), is(true));
- assertLevel(log, StdErrLog.LEVEL_DEBUG); // as stomped
-
- // Restore configured
- root.setDebugEnabled(false);
- assertThat("Log.isDebugEnabled()", log.isDebugEnabled(), is(false));
- assertLevel(log, StdErrLog.LEVEL_WARN); // as configured
- }
-
- @Test
- public void testSuppressed()
- {
- StdErrLog log = new StdErrLog("xxx", new Properties());
- StdErrCapture output = new StdErrCapture(log);
-
- Exception inner = new Exception("inner");
- inner.addSuppressed(new IllegalStateException()
- {{
- addSuppressed(new Exception("branch0"));
- }});
- IOException outer = new IOException("outer", inner);
-
- outer.addSuppressed(new IllegalStateException()
- {{
- addSuppressed(new Exception("branch1"));
- }});
- outer.addSuppressed(new IllegalArgumentException()
- {{
- addSuppressed(new Exception("branch2"));
- }});
-
- log.warn("problem", outer);
-
- output.assertContains("\t|\t|java.lang.Exception: branch2");
- output.assertContains("\t|\t|java.lang.Exception: branch1");
- output.assertContains("\t|\t|java.lang.Exception: branch0");
- }
-
- private void assertLevel(StdErrLog log, int expectedLevel)
- {
- assertThat("Log[" + log.getName() + "].level", levelToString(log.getLevel()), is(levelToString(expectedLevel)));
- }
-
- private String levelToString(int level)
- {
- switch (level)
- {
- case StdErrLog.LEVEL_ALL:
- return "ALL";
- case StdErrLog.LEVEL_DEBUG:
- return "DEBUG";
- case StdErrLog.LEVEL_INFO:
- return "INFO";
- case StdErrLog.LEVEL_WARN:
- return "WARN";
- default:
- return Integer.toString(level);
- }
- }
-}
diff --git a/jetty-util/src/test/java/org/eclipse/jetty/util/resource/ClassPathResourceTest.java b/jetty-util/src/test/java/org/eclipse/jetty/util/resource/ClassPathResourceTest.java
index 83404b2d0f7..5c21361b16c 100644
--- a/jetty-util/src/test/java/org/eclipse/jetty/util/resource/ClassPathResourceTest.java
+++ b/jetty-util/src/test/java/org/eclipse/jetty/util/resource/ClassPathResourceTest.java
@@ -1,19 +1,19 @@
//
-// ========================================================================
-// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd.
-// ------------------------------------------------------------------------
-// All rights reserved. This program and the accompanying materials
-// are made available under the terms of the Eclipse Public License v1.0
-// and Apache License v2.0 which accompanies this distribution.
+// ========================================================================
+// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others.
//
-// The Eclipse Public License is available at
-// http://www.eclipse.org/legal/epl-v10.html
+// 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
//
-// The Apache License v2.0 is available at
-// http://www.opensource.org/licenses/apache2.0.php
+// 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
//
-// You may elect to redistribute this code under either of these licenses.
-// ========================================================================
+// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
+// ========================================================================
//
package org.eclipse.jetty.util.resource;
diff --git a/jetty-util/src/test/java/org/eclipse/jetty/util/resource/FileSystemResourceTest.java b/jetty-util/src/test/java/org/eclipse/jetty/util/resource/FileSystemResourceTest.java
index 8e4fd128bae..03f876dd25f 100644
--- a/jetty-util/src/test/java/org/eclipse/jetty/util/resource/FileSystemResourceTest.java
+++ b/jetty-util/src/test/java/org/eclipse/jetty/util/resource/FileSystemResourceTest.java
@@ -1,25 +1,27 @@
//
-// ========================================================================
-// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd.
-// ------------------------------------------------------------------------
-// All rights reserved. This program and the accompanying materials
-// are made available under the terms of the Eclipse Public License v1.0
-// and Apache License v2.0 which accompanies this distribution.
+// ========================================================================
+// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others.
//
-// The Eclipse Public License is available at
-// http://www.eclipse.org/legal/epl-v10.html
+// 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
//
-// The Apache License v2.0 is available at
-// http://www.opensource.org/licenses/apache2.0.php
+// 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
//
-// You may elect to redistribute this code under either of these licenses.
-// ========================================================================
+// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
+// ========================================================================
//
package org.eclipse.jetty.util.resource;
import java.io.BufferedWriter;
+import java.io.ByteArrayOutputStream;
import java.io.File;
+import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
@@ -228,7 +230,7 @@ public class FileSystemResourceTest
@ParameterizedTest
@EnabledOnOs(WINDOWS)
@MethodSource("fsResourceProvider")
- public void testBogusFilename_Windows(Class Configuration instances are discovered by the {@link Configurations} class using either the
* {@link ServiceLoader} mechanism or by an explicit call to {@link Configurations#setKnown(String...)}.
- * By default, all Configurations that do not implement the {@link #isDisabledByDefault()} interface
+ * By default, all Configurations that do not return false from {@link #isEnabledByDefault()}
* are applied to all {@link WebAppContext}s within the JVM. However a Server wide default {@link Configurations}
* collection may also be defined with {@link Configurations#setServerDefault(org.eclipse.jetty.server.Server)}.
* Furthermore, each individual Context may have its Configurations list explicitly set and/or amended with
* {@link WebAppContext#setConfigurations(Configuration[])}, {@link WebAppContext#addConfiguration(Configuration...)}
- * or {@link WebAppContext#getWebAppConfigurations()}.
+ * or {@link WebAppContext#getConfigurations()}.
* Since Jetty-9.4, Configurations are self ordering using the {@link #getDependencies()} and
* {@link #getDependents()} methods for a {@link TopologicalSort} initiated by {@link Configurations#sort()}
@@ -171,12 +171,12 @@ public interface Configuration
void destroy(WebAppContext context) throws Exception;
/**
- * @return true if configuration is disabled by default
+ * @return true if configuration is enabled by default
*/
- boolean isDisabledByDefault();
+ boolean isEnabledByDefault();
/**
* @return true if configuration should be aborted
*/
boolean abort(WebAppContext context);
-}
\ No newline at end of file
+}
diff --git a/jetty-webapp/src/main/java/org/eclipse/jetty/webapp/Configurations.java b/jetty-webapp/src/main/java/org/eclipse/jetty/webapp/Configurations.java
index 9868d7f570a..c43eac366bd 100644
--- a/jetty-webapp/src/main/java/org/eclipse/jetty/webapp/Configurations.java
+++ b/jetty-webapp/src/main/java/org/eclipse/jetty/webapp/Configurations.java
@@ -1,19 +1,19 @@
//
-// ========================================================================
-// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd.
-// ------------------------------------------------------------------------
-// All rights reserved. This program and the accompanying materials
-// are made available under the terms of the Eclipse Public License v1.0
-// and Apache License v2.0 which accompanies this distribution.
+// ========================================================================
+// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others.
//
-// The Eclipse Public License is available at
-// http://www.eclipse.org/legal/epl-v10.html
+// 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
//
-// The Apache License v2.0 is available at
-// http://www.opensource.org/licenses/apache2.0.php
+// 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
//
-// You may elect to redistribute this code under either of these licenses.
-// ========================================================================
+// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
+// ========================================================================
//
package org.eclipse.jetty.webapp;
@@ -37,11 +37,12 @@ import java.util.stream.Collectors;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.util.Loader;
import org.eclipse.jetty.util.TopologicalSort;
+import org.eclipse.jetty.util.TypeUtil;
import org.eclipse.jetty.util.annotation.Name;
import org.eclipse.jetty.util.component.Dumpable;
import org.eclipse.jetty.util.component.DumpableCollection;
-import org.eclipse.jetty.util.log.Log;
-import org.eclipse.jetty.util.log.Logger;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* An ordered list of {@link Configuration} instances.
@@ -64,7 +65,7 @@ import org.eclipse.jetty.util.log.Logger;
*/
public class Configurations extends AbstractList JAAS Configuration JMX Configuration JNDI Configuration JSP ConfigurationCookie
headers.
+ * @return The CookieCompliance used for parsing request {@code Cookie} headers.
* @see #getResponseCookieCompliance()
*/
public CookieCompliance getRequestCookieCompliance()
@@ -566,7 +580,7 @@ public class HttpConfiguration implements Dumpable
}
/**
- * @return The CookieCompliance used for generating response Set-Cookie
headers
+ * @return The CookieCompliance used for generating response {@code Set-Cookie} headers
* @see #getRequestCookieCompliance()
*/
public CookieCompliance getResponseCookieCompliance()
@@ -575,8 +589,7 @@ public class HttpConfiguration implements Dumpable
}
/**
- * @param cookieCompliance The CookieCompliance to use for parsing request Cookie
headers.
- * @see #setRequestCookieCompliance(CookieCompliance)
+ * @param cookieCompliance The CookieCompliance to use for parsing request {@code Cookie} headers.
*/
public void setRequestCookieCompliance(CookieCompliance cookieCompliance)
{
@@ -584,8 +597,7 @@ public class HttpConfiguration implements Dumpable
}
/**
- * @param cookieCompliance The CookieCompliance to use for generating response Set-Cookie
headers
- * @see #setResponseCookieCompliance(CookieCompliance)
+ * @param cookieCompliance The CookieCompliance to use for generating response {@code Set-Cookie} headers
*/
public void setResponseCookieCompliance(CookieCompliance cookieCompliance)
{
diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/HttpConnection.java b/jetty-server/src/main/java/org/eclipse/jetty/server/HttpConnection.java
index 3d717ca4497..d54aeaf2d47 100644
--- a/jetty-server/src/main/java/org/eclipse/jetty/server/HttpConnection.java
+++ b/jetty-server/src/main/java/org/eclipse/jetty/server/HttpConnection.java
@@ -1,19 +1,19 @@
//
-// ========================================================================
-// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd.
-// ------------------------------------------------------------------------
-// All rights reserved. This program and the accompanying materials
-// are made available under the terms of the Eclipse Public License v1.0
-// and Apache License v2.0 which accompanies this distribution.
+// ========================================================================
+// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others.
//
-// The Eclipse Public License is available at
-// http://www.eclipse.org/legal/epl-v10.html
+// 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
//
-// The Apache License v2.0 is available at
-// http://www.opensource.org/licenses/apache2.0.php
+// 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
//
-// You may elect to redistribute this code under either of these licenses.
-// ========================================================================
+// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
+// ========================================================================
//
package org.eclipse.jetty.server;
@@ -25,11 +25,13 @@ import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.LongAdder;
+import org.eclipse.jetty.http.BadMessageException;
import org.eclipse.jetty.http.HttpCompliance;
import org.eclipse.jetty.http.HttpField;
import org.eclipse.jetty.http.HttpGenerator;
import org.eclipse.jetty.http.HttpHeader;
import org.eclipse.jetty.http.HttpHeaderValue;
+import org.eclipse.jetty.http.HttpMethod;
import org.eclipse.jetty.http.HttpParser;
import org.eclipse.jetty.http.HttpParser.RequestHandler;
import org.eclipse.jetty.http.HttpStatus;
@@ -44,17 +46,16 @@ import org.eclipse.jetty.io.WriteFlusher;
import org.eclipse.jetty.util.BufferUtil;
import org.eclipse.jetty.util.Callback;
import org.eclipse.jetty.util.IteratingCallback;
-import org.eclipse.jetty.util.log.Log;
-import org.eclipse.jetty.util.log.Logger;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
*
+ OPEN/BLOCKING---last----------------------------+ CLOSED/BLOCKING
+ / | ^ \ ^ ^
+ / w | \ / |
+ / | owc +--owcL------------------->--owcL-----\---------------------+ |
+ | v | / / V |
+ swl OPEN/BLOCKED----last---->CLOSE/BLOCKED----owc----->CLOSING/BLOCKED--owcL------+
+ |
+ \
+ \
+ V
+ +-->OPEN/READY------last---------------------------+
+ / ^ | \
+ / / w \
+ | / | +--owcL------------------->--owcL----\---------------------------+
+ | / v / / V |
+ | irt OPEN/PENDING----last---->CLOSE/PENDING----owc---->CLOSING/PENDING--owcL----+ |
+ | \ / | | ^ | | |
+ owc \/ owc irf / irf | |
+ | /\ | | / | | |
+ | / \ V | / | V V
+ | irf OPEN/ASYNC------last----------|----------------+ | CLOSED/ASYNC
+ | \ | | ^ ^
+ \ \ | | | |
+ \ \ | | | |
+ \ v v v | |
+ +--OPEN/UNREADY----last---->CLOSE/UNREADY----owc----->CLOSING/UNREADY--owcL---+ |
+ \ \ |
+ +--owcL------------------->--owcL--------------------------------+
+
+ swl : setWriteListener
+ w : write
+ owc : onWriteComplete last == false
+ owcL : onWriteComplete last == true
+ irf : isReady() == false
+ irt : isReady() == true
+ last : close() or complete(Callback) or write of known last content
+
+ */
+ enum ApiState
+ {
+ BLOCKING, // Open in blocking mode
+ BLOCKED, // Blocked in blocking operation
+ ASYNC, // Open in async mode
+ READY, // isReady() has returned true
+ PENDING, // write operating in progress
+ UNREADY, // write operating in progress, isReady has returned false
+ }
/**
* The HttpOutput.Interceptor is a single intercept point for all
@@ -103,14 +159,6 @@ public class HttpOutput extends ServletOutputStream implements Runnable
*/
Interceptor getNextInterceptor();
- /**
- * @return True if the Interceptor is optimized to receive direct
- * {@link ByteBuffer}s in the {@link #write(ByteBuffer, boolean, Callback)}
- * method. If false is returned, then passing direct buffers may cause
- * inefficiencies.
- */
- boolean isOptimizedForDirectBuffers();
-
/**
* Reset the buffers.
* {@code
+ * UNPARSED - Parsing has not started, there are no parts which need to be cleaned up.
+ * PARSING - The parsing thread is reading from the InputStream and generating parts.
+ * PARSED - Parsing has complete and no more parts will be generated.
+ * DELETING - deleteParts() has been called while we were in PARSING state, parsing thread will do the delete.
+ * DELETED - The parts have been deleted, this is the terminal state.
*
+ * deleteParts()
+ * +--------------------------------------------------------------+
+ * | |
+ * | deleteParts() v
+ * UNPARSED -------> PARSING --------> PARSED ------------------>DELETED
+ * | ^
+ * | |
+ * +---------------> DELETING -------------------+
+ * deleteParts() parsing thread
+ * }
* @see https://tools.ietf.org/html/rfc7578
*/
public class MultiPartFormInputStream
{
- private static final Logger LOG = Log.getLogger(MultiPartFormInputStream.class);
- private static final MultiMap> values = _parts.values();
- for (List
> values = _parts.values();
- List
+ *
+ * @param code The error code
+ * @param message The message
+ * @throws IOException If an IO problem occurred sending the error response.
+ */
@Override
public void sendError(int code, String message) throws IOException
{
if (isIncluding())
return;
- if (isCommitted())
- {
- if (LOG.isDebugEnabled())
- LOG.debug("Aborting on sendError on committed response {} {}", code, message);
- code = -1;
- }
- else
- resetBuffer();
-
switch (code)
{
case -1:
- _channel.abort(new IOException());
- return;
- case 102:
+ _channel.abort(new IOException(message));
+ break;
+ case HttpStatus.PROCESSING_102:
sendProcessing();
- return;
+ break;
default:
+ _channel.getState().sendError(code, message);
break;
}
-
- _outputType = OutputType.NONE;
- setContentType(null);
- setCharacterEncoding(null);
- setHeader(HttpHeader.EXPIRES, null);
- setHeader(HttpHeader.LAST_MODIFIED, null);
- setHeader(HttpHeader.CACHE_CONTROL, null);
- setHeader(HttpHeader.CONTENT_TYPE, null);
- setHeader(HttpHeader.CONTENT_LENGTH, null);
-
- setStatus(code);
-
- Request request = _channel.getRequest();
- Throwable cause = (Throwable)request.getAttribute(Dispatcher.ERROR_EXCEPTION);
- _reason = HttpStatus.getMessage(code);
- if (message == null)
- message = cause == null ? _reason : cause.toString();
-
- // If we are allowed to have a body, then produce the error page.
- if (code != SC_NO_CONTENT && code != SC_NOT_MODIFIED &&
- code != SC_PARTIAL_CONTENT && code >= SC_OK)
- {
- ContextHandler.Context context = request.getContext();
- ContextHandler contextHandler = context == null ? _channel.getState().getContextHandler() : context.getContextHandler();
- request.setAttribute(RequestDispatcher.ERROR_STATUS_CODE, code);
- request.setAttribute(RequestDispatcher.ERROR_MESSAGE, message);
- request.setAttribute(RequestDispatcher.ERROR_REQUEST_URI, request.getRequestURI());
- request.setAttribute(RequestDispatcher.ERROR_SERVLET_NAME, request.getServletName());
- ErrorHandler errorHandler = ErrorHandler.getErrorHandler(_channel.getServer(), contextHandler);
- if (errorHandler != null)
- errorHandler.handle(null, request, request, this);
- }
- if (!request.isAsyncStarted())
- closeOutput();
}
/**
* Sends a 102-Processing response.
- * If the connection is a HTTP connection, the version is 1.1 and the
+ * If the connection is an HTTP connection, the version is 1.1 and the
* request has a Expect header starting with 102, then a 102 response is
* sent. This indicates that the request still be processed and real response
* can still be sent. This method is called by sendError if it is passed 102.
@@ -481,7 +496,7 @@ public class Response implements HttpServletResponse
if ((code < HttpServletResponse.SC_MULTIPLE_CHOICES) || (code >= HttpServletResponse.SC_BAD_REQUEST))
throw new IllegalArgumentException("Not a 3xx redirect code");
- if (isIncluding())
+ if (!isMutable())
return;
if (location == null)
@@ -527,34 +542,34 @@ public class Response implements HttpServletResponse
@Override
public void setDateHeader(String name, long date)
{
- if (!isIncluding())
+ if (isMutable())
_fields.putDateField(name, date);
}
@Override
public void addDateHeader(String name, long date)
{
- if (!isIncluding())
+ if (isMutable())
_fields.addDateField(name, date);
}
public void setHeader(HttpHeader name, String value)
{
- if (HttpHeader.CONTENT_TYPE == name)
- setContentType(value);
- else
+ if (isMutable())
{
- if (isIncluding())
- return;
-
- _fields.put(name, value);
-
- if (HttpHeader.CONTENT_LENGTH == name)
+ if (HttpHeader.CONTENT_TYPE == name)
+ setContentType(value);
+ else
{
- if (value == null)
- _contentLength = -1L;
- else
- _contentLength = Long.parseLong(value);
+ _fields.put(name, value);
+
+ if (HttpHeader.CONTENT_LENGTH == name)
+ {
+ if (value == null)
+ _contentLength = -1L;
+ else
+ _contentLength = Long.parseLong(value);
+ }
}
}
}
@@ -562,17 +577,21 @@ public class Response implements HttpServletResponse
@Override
public void setHeader(String name, String value)
{
+ long biInt = _errorSentAndIncludes.get();
+ if (biInt != 0)
+ {
+ boolean errorSent = AtomicBiInteger.getHi(biInt) != 0;
+ boolean including = AtomicBiInteger.getLo(biInt) > 0;
+ if (!errorSent && including && name.startsWith(SET_INCLUDE_HEADER_PREFIX))
+ name = name.substring(SET_INCLUDE_HEADER_PREFIX.length());
+ else
+ return;
+ }
+
if (HttpHeader.CONTENT_TYPE.is(name))
setContentType(value);
else
{
- if (isIncluding())
- {
- if (name.startsWith(SET_INCLUDE_HEADER_PREFIX))
- name = name.substring(SET_INCLUDE_HEADER_PREFIX.length());
- else
- return;
- }
_fields.put(name, value);
if (HttpHeader.CONTENT_LENGTH.is(name))
{
@@ -608,9 +627,12 @@ public class Response implements HttpServletResponse
@Override
public void addHeader(String name, String value)
{
- if (isIncluding())
+ long biInt = _errorSentAndIncludes.get();
+ if (biInt != 0)
{
- if (name.startsWith(SET_INCLUDE_HEADER_PREFIX))
+ boolean errorSent = AtomicBiInteger.getHi(biInt) != 0;
+ boolean including = AtomicBiInteger.getLo(biInt) > 0;
+ if (!errorSent && including && name.startsWith(SET_INCLUDE_HEADER_PREFIX))
name = name.substring(SET_INCLUDE_HEADER_PREFIX.length());
else
return;
@@ -634,7 +656,7 @@ public class Response implements HttpServletResponse
@Override
public void setIntHeader(String name, int value)
{
- if (!isIncluding())
+ if (isMutable())
{
_fields.putLongField(name, value);
if (HttpHeader.CONTENT_LENGTH.is(name))
@@ -645,7 +667,7 @@ public class Response implements HttpServletResponse
@Override
public void addIntHeader(String name, int value)
{
- if (!isIncluding())
+ if (isMutable())
{
_fields.add(name, Integer.toString(value));
if (HttpHeader.CONTENT_LENGTH.is(name))
@@ -658,10 +680,13 @@ public class Response implements HttpServletResponse
{
if (sc <= 0)
throw new IllegalArgumentException();
- if (!isIncluding())
+ if (isMutable())
{
+ // Null the reason only if the status is different. This allows
+ // a specific reason to be sent with setStatusWithReason followed by sendError.
+ if (_status != sc)
+ _reason = null;
_status = sc;
- _reason = null;
}
}
@@ -676,7 +701,7 @@ public class Response implements HttpServletResponse
{
if (sc <= 0)
throw new IllegalArgumentException();
- if (!isIncluding())
+ if (isMutable())
{
_status = sc;
_reason = message;
@@ -691,9 +716,18 @@ public class Response implements HttpServletResponse
String encoding = MimeTypes.getCharsetAssumedFromContentType(_contentType);
if (encoding != null)
return encoding;
+
encoding = MimeTypes.getCharsetInferredFromContentType(_contentType);
if (encoding != null)
return encoding;
+
+ Context context = _channel.getRequest().getContext();
+ if (context != null)
+ {
+ encoding = context.getResponseCharacterEncoding();
+ if (encoding != null)
+ return encoding;
+ }
return StringUtil.__ISO_8859_1;
}
return _characterEncoding;
@@ -724,6 +758,11 @@ public class Response implements HttpServletResponse
return _outputType == OutputType.STREAM;
}
+ public boolean isWritingOrStreaming()
+ {
+ return isWriting() || isStreaming();
+ }
+
@Override
public PrintWriter getWriter() throws IOException
{
@@ -732,23 +771,42 @@ public class Response implements HttpServletResponse
if (_outputType == OutputType.NONE)
{
- /* get encoding from Content-Type header */
+ //first try explicit char encoding
String encoding = _characterEncoding;
+
+ //try char set from mime type
if (encoding == null)
{
if (_mimeType != null && _mimeType.isCharsetAssumed())
encoding = _mimeType.getCharsetString();
- else
- {
- encoding = MimeTypes.getCharsetAssumedFromContentType(_contentType);
- if (encoding == null)
- {
- encoding = MimeTypes.getCharsetInferredFromContentType(_contentType);
- if (encoding == null)
- encoding = StringUtil.__ISO_8859_1;
- setCharacterEncoding(encoding, EncodingFrom.INFERRED);
- }
- }
+ }
+
+ //try char set assumed from content type
+ if (encoding == null)
+ {
+ encoding = MimeTypes.getCharsetAssumedFromContentType(_contentType);
+ }
+
+ //try char set inferred from content type
+ if (encoding == null)
+ {
+ encoding = MimeTypes.getCharsetInferredFromContentType(_contentType);
+ setCharacterEncoding(encoding, EncodingFrom.INFERRED);
+ }
+
+ //try any default char encoding for the context
+ if (encoding == null)
+ {
+ Context context = _channel.getRequest().getContext();
+ if (context != null)
+ encoding = context.getResponseCharacterEncoding();
+ }
+
+ //fallback to last resort iso-8859-1
+ if (encoding == null)
+ {
+ encoding = StringUtil.__ISO_8859_1;
+ setCharacterEncoding(encoding, EncodingFrom.INFERRED);
}
Locale locale = getLocale();
@@ -777,7 +835,7 @@ public class Response implements HttpServletResponse
// Protect from setting after committed as default handling
// of a servlet HEAD request ALWAYS sets _content length, even
// if the getHandling committed the response!
- if (isCommitted() || isIncluding())
+ if (isCommitted() || !isMutable())
return;
if (len > 0)
@@ -832,21 +890,29 @@ public class Response implements HttpServletResponse
public void closeOutput() throws IOException
{
- switch (_outputType)
- {
- case WRITER:
- _writer.close();
- if (!_out.isClosed())
- _out.close();
- break;
- case STREAM:
- if (!_out.isClosed())
- getOutputStream().close();
- break;
- default:
- if (!_out.isClosed())
- _out.close();
- }
+ if (_outputType == OutputType.WRITER)
+ _writer.close();
+ else
+ _out.close();
+ }
+
+ /**
+ * close the output
+ *
+ * @deprecated Use {@link #closeOutput()}
+ */
+ @Deprecated
+ public void completeOutput() throws IOException
+ {
+ closeOutput();
+ }
+
+ public void completeOutput(Callback callback)
+ {
+ if (_outputType == OutputType.WRITER)
+ _writer.complete(callback);
+ else
+ _out.complete(callback);
}
public long getLongContentLength()
@@ -859,7 +925,7 @@ public class Response implements HttpServletResponse
// Protect from setting after committed as default handling
// of a servlet HEAD request ALWAYS sets _content length, even
// if the getHandling committed the response!
- if (isCommitted() || isIncluding())
+ if (isCommitted() || !isMutable())
return;
_contentLength = len;
_fields.putLongField(HttpHeader.CONTENT_LENGTH.toString(), len);
@@ -879,7 +945,7 @@ public class Response implements HttpServletResponse
private void setCharacterEncoding(String encoding, EncodingFrom from)
{
- if (isIncluding() || isWriting())
+ if (!isMutable() || isWriting())
return;
if (_outputType != OutputType.WRITER && !isCommitted())
@@ -932,7 +998,7 @@ public class Response implements HttpServletResponse
@Override
public void setContentType(String contentType)
{
- if (isCommitted() || isIncluding())
+ if (isCommitted() || !isMutable())
return;
if (contentType == null)
@@ -1039,19 +1105,21 @@ public class Response implements HttpServletResponse
@Override
public void reset()
{
- reset(false);
- }
-
- public void reset(boolean preserveCookies)
- {
- resetForForward();
_status = 200;
_reason = null;
+ _out.resetBuffer();
+ _outputType = OutputType.NONE;
_contentLength = -1;
+ _contentType = null;
+ _mimeType = null;
+ _characterEncoding = null;
+ _encodingFrom = EncodingFrom.NOT_SET;
+ _trailers = null;
- ListAccept
header, until {@link Request#isHandled()} is true and a
- * response of the appropriate type is generated.
- *
- * @param baseRequest The base request
- * @param request The servlet request (may be wrapped)
- * @param response The response (may be wrapped)
- * @param code the http error code
- * @param message the http error message
- * @param mimeType The mimetype to generate (may be */*or other wildcard)
- * @throws IOException if a response cannot be generated
- */
- protected void generateAcceptableResponse(Request baseRequest, HttpServletRequest request, HttpServletResponse response, int code, String message, String mimeType)
- throws IOException
- {
- switch (mimeType)
- {
- case "text/html":
- case "text/*":
- case "*/*":
- {
- baseRequest.setHandled(true);
- Writer writer = getAcceptableWriter(baseRequest, request, response);
- if (writer != null)
- {
- response.setContentType(MimeTypes.Type.TEXT_HTML.asString());
- handleErrorPage(request, writer, code, message);
- }
- break;
- }
- default:
- break;
- }
}
/**
@@ -236,6 +183,7 @@ public class ErrorHandler extends AbstractHandler
* @return A {@link Writer} if there is a known acceptable charset or null
* @throws IOException if a Writer cannot be returned
*/
+ @Deprecated
protected Writer getAcceptableWriter(Request baseRequest, HttpServletRequest request, HttpServletResponse response)
throws IOException
{
@@ -258,12 +206,146 @@ public class ErrorHandler extends AbstractHandler
}
catch (Exception e)
{
- LOG.ignore(e);
+ LOG.trace("IGNORED", e);
}
}
return null;
}
+ /**
+ * Generate an acceptable error response for a mime type.
+ * Accept
header, until {@link Request#isHandled()} is true and a
+ * response of the appropriate type is generated.
+ * HTTP ERROR ");
+ String status = Integer.toString(code);
+ writer.write(status);
+ if (message != null && !message.equals(status))
+ {
+ writer.write(' ');
+ writer.write(StringUtil.sanitizeXmlString(message));
+ }
+ writer.write("
\n");
+ writer.write("\n");
+ htmlRow(writer, "URI", uri);
+ htmlRow(writer, "STATUS", status);
+ htmlRow(writer, "MESSAGE", message);
+ htmlRow(writer, "SERVLET", request.getAttribute(Dispatcher.ERROR_SERVLET_NAME));
+ Throwable cause = (Throwable)request.getAttribute(Dispatcher.ERROR_EXCEPTION);
+ while (cause != null)
+ {
+ htmlRow(writer, "CAUSED BY", cause);
+ cause = cause.getCause();
+ }
+ writer.write("
\n");
+ }
+
+ private void htmlRow(Writer writer, String tag, Object value)
+ throws IOException
+ {
+ writer.write(" \n");
+ }
+
+ private void writeErrorPlain(HttpServletRequest request, PrintWriter writer, int code, String message)
+ {
+ writer.write("HTTP ERROR ");
writer.write(Integer.toString(code));
- writer.write("\n");
+ writer.write(tag);
+ writer.write(": ");
+ if (value == null)
+ writer.write("-");
+ else
+ writer.write(StringUtil.sanitizeXmlString(value.toString()));
+ writer.write(" ");
- write(writer, message);
- writer.write("
Caused by:
");
- StringWriter sw = new StringWriter();
- PrintWriter pw = new PrintWriter(sw);
- th.printStackTrace(pw);
- pw.flush();
- write(writer, sw.getBuffer().toString());
+ // You have to pre-generate and then use #write(writer, String)
+ try (StringWriter sw = new StringWriter();
+ PrintWriter pw = new PrintWriter(sw))
+ {
+ th.printStackTrace(pw);
+ pw.flush();
+ write(writer, sw.getBuffer().toString()); // sanitize
+ }
writer.write("
\n");
-
- th = th.getCause();
}
}
/**
* Bad Message Error body
- *
Examples:
+ *
+ *
+ *
+ * @param pattern InetAccess pattern to include
* @see InetAddressSet
*/
public void include(String pattern)
{
- _addrs.include(pattern);
+ _set.include(PatternTuple.from(pattern));
}
/**
- * Includes InetAddress patterns
+ * Includes InetAccess patterns
*
* @param patterns InetAddress patterns to include
* @see InetAddressSet
*/
public void include(String... patterns)
{
- _addrs.include(patterns);
+ for (String pattern : patterns)
+ {
+ include(pattern);
+ }
}
/**
- * Excludes an InetAddress pattern
+ * Includes an InetAccess entry.
+ *
+ * @param connectorName optional name of a connector to include.
+ * @param addressPattern optional InetAddress pattern to include.
+ * @param pathSpec optional pathSpec to include.
+ */
+ public void include(String connectorName, String addressPattern, PathSpec pathSpec)
+ {
+ _set.include(new PatternTuple(connectorName, InetAddressPattern.from(addressPattern), pathSpec));
+ }
+
+ /**
+ * Excludes an InetAccess entry pattern with an optional connector name, address and URI mapping.
+ *
+ *
Examples:
+ *
+ *
*
* @param pattern InetAddress pattern to exclude
* @see InetAddressSet
*/
public void exclude(String pattern)
{
- _addrs.exclude(pattern);
+ _set.exclude(PatternTuple.from(pattern));
}
/**
- * Excludes InetAddress patterns
+ * Excludes InetAccess patterns
*
* @param patterns InetAddress patterns to exclude
* @see InetAddressSet
*/
public void exclude(String... patterns)
{
- _addrs.exclude(patterns);
+ for (String pattern : patterns)
+ {
+ exclude(pattern);
+ }
+ }
+
+ /**
+ * Excludes an InetAccess entry.
+ *
+ * @param connectorName optional name of a connector to exclude.
+ * @param addressPattern optional InetAddress pattern to exclude.
+ * @param pathSpec optional pathSpec to exclude.
+ */
+ public void exclude(String connectorName, String addressPattern, PathSpec pathSpec)
+ {
+ _set.exclude(new PatternTuple(connectorName, InetAddressPattern.from(addressPattern), pathSpec));
}
/**
* Includes a connector name.
*
* @param name Connector name to include in this handler.
+ * @deprecated use {@link InetAccessHandler#include(String)} instead.
*/
+ @Deprecated
public void includeConnector(String name)
{
- _names.include(name);
+ throw new UnsupportedOperationException();
}
/**
* Excludes a connector name.
*
* @param name Connector name to exclude in this handler.
+ * @deprecated use {@link InetAccessHandler#include(String)} instead.
*/
+ @Deprecated
public void excludeConnector(String name)
{
- _names.exclude(name);
+ _set.exclude(new PatternTuple(name, null, null));
}
/**
* Includes connector names.
*
* @param names Connector names to include in this handler.
+ * @deprecated use {@link InetAccessHandler#include(String)} instead.
*/
+ @Deprecated
public void includeConnectors(String... names)
{
- _names.include(names);
+ throw new UnsupportedOperationException();
}
/**
* Excludes connector names.
*
* @param names Connector names to exclude in this handler.
+ * @deprecated use {@link InetAccessHandler#include(String)} instead.
*/
+ @Deprecated
public void excludeConnectors(String... names)
{
- _names.exclude(names);
+ for (String name : names)
+ {
+ excludeConnector(name);
+ }
}
/**
@@ -187,23 +252,16 @@ public class InetAccessHandler extends HandlerWrapper
*/
protected boolean isAllowed(InetAddress addr, Request baseRequest, HttpServletRequest request)
{
- String name = baseRequest.getHttpChannel().getConnector().getName();
- if (LOG.isDebugEnabled())
- {
- Boolean allowedByName = _names.isIncludedAndNotExcluded(name);
- Boolean allowedByAddr = _addrs.isIncludedAndNotExcluded(addr);
- LOG.debug("{} allowedByName={} allowedByAddr={} for {}/{}", this, allowedByName, allowedByAddr, addr, request);
- }
- return _names.test(name) && _addrs.test(addr);
+ String connectorName = baseRequest.getHttpChannel().getConnector().getName();
+ String path = baseRequest.getMetaData().getURI().getDecodedPath();
+ return _set.test(new AccessTuple(connectorName, addr, path));
}
@Override
public void dump(Appendable out, String indent) throws IOException
{
dumpObjects(out, indent,
- new DumpableCollection("included", _addrs.getIncluded()),
- new DumpableCollection("excluded", _addrs.getExcluded()),
- new DumpableCollection("includedConnector", _names.getIncluded()),
- new DumpableCollection("excludedConnector", _names.getExcluded()));
+ new DumpableCollection("included", _set.getIncluded()),
+ new DumpableCollection("excluded", _set.getExcluded()));
}
}
diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/handler/InetAccessSet.java b/jetty-server/src/main/java/org/eclipse/jetty/server/handler/InetAccessSet.java
new file mode 100644
index 00000000000..8cf62c3f279
--- /dev/null
+++ b/jetty-server/src/main/java/org/eclipse/jetty/server/handler/InetAccessSet.java
@@ -0,0 +1,158 @@
+//
+// ========================================================================
+// 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.server.handler;
+
+import java.net.InetAddress;
+import java.util.AbstractSet;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.Set;
+import java.util.function.Predicate;
+
+import org.eclipse.jetty.http.pathmap.PathSpec;
+import org.eclipse.jetty.http.pathmap.ServletPathSpec;
+import org.eclipse.jetty.util.InetAddressPattern;
+import org.eclipse.jetty.util.StringUtil;
+
+public class InetAccessSet extends AbstractSet
(Default: 16 bytes. see {@link GzipHandler#DEFAULT_MIN_GZIP_SIZE})
+ * value meet the minimum gzip size requirements (default 32 bytes)?
* true
unloadable session will be deleted
*/
boolean isRemoveUnloadableSessions();
+
+ /**
+ * If true, a dirty session will be written to the SessionDataStore
+ * just before a response is returned to the client. This ensures
+ * that subsequent requests to either the same node or a different
+ * node see the changed session data.
+ */
+ void setFlushOnResponseCommit(boolean flushOnResponse);
+
+ /**
+ * @return true
if dirty sessions should be written
+ * before the response is committed.
+ */
+ boolean isFlushOnResponseCommit();
}
diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/session/SessionCacheFactory.java b/jetty-server/src/main/java/org/eclipse/jetty/server/session/SessionCacheFactory.java
index 2bd63588b7d..503abe64b3a 100644
--- a/jetty-server/src/main/java/org/eclipse/jetty/server/session/SessionCacheFactory.java
+++ b/jetty-server/src/main/java/org/eclipse/jetty/server/session/SessionCacheFactory.java
@@ -1,19 +1,19 @@
//
-// ========================================================================
-// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd.
-// ------------------------------------------------------------------------
-// All rights reserved. This program and the accompanying materials
-// are made available under the terms of the Eclipse Public License v1.0
-// and Apache License v2.0 which accompanies this distribution.
+// ========================================================================
+// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others.
//
-// The Eclipse Public License is available at
-// http://www.eclipse.org/legal/epl-v10.html
+// 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
//
-// The Apache License v2.0 is available at
-// http://www.opensource.org/licenses/apache2.0.php
+// 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
//
-// You may elect to redistribute this code under either of these licenses.
-// ========================================================================
+// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
+// ========================================================================
//
package org.eclipse.jetty.server.session;
diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/session/SessionContext.java b/jetty-server/src/main/java/org/eclipse/jetty/server/session/SessionContext.java
index 1e4a506781c..8c6b681fa8c 100644
--- a/jetty-server/src/main/java/org/eclipse/jetty/server/session/SessionContext.java
+++ b/jetty-server/src/main/java/org/eclipse/jetty/server/session/SessionContext.java
@@ -1,19 +1,19 @@
//
-// ========================================================================
-// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd.
-// ------------------------------------------------------------------------
-// All rights reserved. This program and the accompanying materials
-// are made available under the terms of the Eclipse Public License v1.0
-// and Apache License v2.0 which accompanies this distribution.
+// ========================================================================
+// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others.
//
-// The Eclipse Public License is available at
-// http://www.eclipse.org/legal/epl-v10.html
+// 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
//
-// The Apache License v2.0 is available at
-// http://www.opensource.org/licenses/apache2.0.php
+// 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
//
-// You may elect to redistribute this code under either of these licenses.
-// ========================================================================
+// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
+// ========================================================================
//
package org.eclipse.jetty.server.session;
diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/session/SessionData.java b/jetty-server/src/main/java/org/eclipse/jetty/server/session/SessionData.java
index 57a041c9ccc..63c5af54d5b 100644
--- a/jetty-server/src/main/java/org/eclipse/jetty/server/session/SessionData.java
+++ b/jetty-server/src/main/java/org/eclipse/jetty/server/session/SessionData.java
@@ -1,19 +1,19 @@
//
-// ========================================================================
-// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd.
-// ------------------------------------------------------------------------
-// All rights reserved. This program and the accompanying materials
-// are made available under the terms of the Eclipse Public License v1.0
-// and Apache License v2.0 which accompanies this distribution.
+// ========================================================================
+// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others.
//
-// The Eclipse Public License is available at
-// http://www.eclipse.org/legal/epl-v10.html
+// 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
//
-// The Apache License v2.0 is available at
-// http://www.opensource.org/licenses/apache2.0.php
+// 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
//
-// You may elect to redistribute this code under either of these licenses.
-// ========================================================================
+// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
+// ========================================================================
//
package org.eclipse.jetty.server.session;
@@ -28,8 +28,8 @@ import java.util.concurrent.ConcurrentHashMap;
import org.eclipse.jetty.util.ClassLoadingObjectInputStream;
import org.eclipse.jetty.util.ClassVisibilityChecker;
-import org.eclipse.jetty.util.log.Log;
-import org.eclipse.jetty.util.log.Logger;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* SessionData
@@ -41,7 +41,7 @@ import org.eclipse.jetty.util.log.Logger;
*/
public class SessionData implements Serializable
{
- private static final Logger LOG = Log.getLogger("org.eclipse.jetty.server.session");
+ private static final Logger LOG = LoggerFactory.getLogger(SessionData.class);
private static final long serialVersionUID = 1L;
@@ -58,6 +58,7 @@ public class SessionData implements Serializable
protected MapHttpSession
with the given session id
*
* @param extendedId the session id
* @return the HttpSession
with the corresponding id or null if no session with the given id exists
*/
- public HttpSession getHttpSession(String extendedId)
+ protected HttpSession getHttpSession(String extendedId)
{
String id = getSessionIdManager().getId(extendedId);
-
Session session = getSession(id);
+
if (session != null && !session.getExtendedId().equals(extendedId))
session.setIdChanged(true);
return session;
@@ -618,7 +567,7 @@ public class SessionHandler extends ScopedHandler
/**
* @return same as SessionCookieConfig.getSecure(). If true, session
* cookies are ALWAYS marked as secure. If false, a session cookie is
- * ONLY marked as secure if _secureRequestOnly == true and it is a HTTPS request.
+ * ONLY marked as secure if _secureRequestOnly == true and it is an HTTPS request.
*/
@ManagedAttribute("if true, secure cookie flag is set on session cookies")
public boolean getSecureCookies()
@@ -692,30 +641,18 @@ public class SessionHandler extends ScopedHandler
sessionPath = (StringUtil.isEmpty(sessionPath)) ? "/" : sessionPath;
String id = getExtendedId(session);
HttpCookie cookie = null;
- if (_sessionComment == null)
- {
- cookie = new HttpCookie(
- _cookieConfig.getName(),
- id,
- _cookieConfig.getDomain(),
- sessionPath,
- _cookieConfig.getMaxAge(),
- _cookieConfig.isHttpOnly(),
- _cookieConfig.isSecure() || (isSecureRequestOnly() && requestIsSecure));
- }
- else
- {
- cookie = new HttpCookie(
- _cookieConfig.getName(),
- id,
- _cookieConfig.getDomain(),
- sessionPath,
- _cookieConfig.getMaxAge(),
- _cookieConfig.isHttpOnly(),
- _cookieConfig.isSecure() || (isSecureRequestOnly() && requestIsSecure),
- _sessionComment,
- 1);
- }
+
+ cookie = new HttpCookie(
+ _cookieConfig.getName(),
+ id,
+ _cookieConfig.getDomain(),
+ sessionPath,
+ _cookieConfig.getMaxAge(),
+ _cookieConfig.isHttpOnly(),
+ _cookieConfig.isSecure() || (isSecureRequestOnly() && requestIsSecure),
+ HttpCookie.getCommentWithoutAttributes(_cookieConfig.getComment()),
+ 0,
+ HttpCookie.getSameSiteFromComment(_cookieConfig.getComment()));
return cookie;
}
@@ -810,7 +747,8 @@ public class SessionHandler extends ScopedHandler
try
{
- _sessionCache.put(id, session);
+ _sessionCache.add(id, session);
+ Request.getBaseRequest(request).enterSession(session);
_sessionsCreatedStats.increment();
if (request != null && request.isSecure())
@@ -822,26 +760,25 @@ public class SessionHandler extends ScopedHandler
}
catch (Exception e)
{
- LOG.warn(e);
+ LOG.warn("Unable to add Session {}", id, e);
return null;
}
}
- /**
- * Removes an event listener for for session-related events.
- *
- * @param listener the session event listener to remove
- * @see #addEventListener(EventListener)
- */
- public void removeEventListener(EventListener listener)
+ @Override
+ public boolean removeEventListener(EventListener listener)
{
- if (listener instanceof HttpSessionAttributeListener)
- _sessionAttributeListeners.remove(listener);
- if (listener instanceof HttpSessionListener)
- _sessionListeners.remove(listener);
- if (listener instanceof HttpSessionIdListener)
- _sessionIdListeners.remove(listener);
- removeBean(listener);
+ if (super.removeEventListener(listener))
+ {
+ if (listener instanceof HttpSessionAttributeListener)
+ _sessionAttributeListeners.remove(listener);
+ if (listener instanceof HttpSessionListener)
+ _sessionListeners.remove(listener);
+ if (listener instanceof HttpSessionIdListener)
+ _sessionIdListeners.remove(listener);
+ return true;
+ }
+ return false;
}
/**
@@ -855,13 +792,30 @@ public class SessionHandler extends ScopedHandler
}
/**
- * @param httpOnly The httpOnly to set.
+ * Set if Session cookies should use HTTP Only
+ *
+ * @param httpOnly True if cookies should be HttpOnly.
+ * @see HttpCookie
*/
public void setHttpOnly(boolean httpOnly)
{
_httpOnly = httpOnly;
}
+ /**
+ * Set Session cookie sameSite mode.
+ * Currently this is encoded in the session comment until sameSite is supported by {@link SessionCookieConfig}
+ *
+ * @param sameSite The sameSite setting for Session cookies (or null for no sameSite setting)
+ */
+ public void setSameSite(HttpCookie.SameSite sameSite)
+ {
+ // Encode in comment whilst not supported by SessionConfig, so that it can be set/saved in
+ // web.xml and quickstart.
+ // Always pass false for httpOnly as it has it's own setter.
+ _sessionComment = HttpCookie.getCommentWithAttributes(_sessionComment, false, sameSite);
+ }
+
/**
* @param metaManager The metaManager used for cross context session management.
*/
@@ -909,7 +863,8 @@ public class SessionHandler extends ScopedHandler
public void setSessionIdPathParameterName(String param)
{
_sessionIdPathParameterName = (param == null || "none".equals(param)) ? null : param;
- _sessionIdPathParameterNamePrefix = (param == null || "none".equals(param)) ? null : (";" + _sessionIdPathParameterName + "=");
+ _sessionIdPathParameterNamePrefix = (param == null || "none".equals(param))
+ ? null : (";" + _sessionIdPathParameterName + "=");
}
/**
@@ -950,13 +905,12 @@ public class SessionHandler extends ScopedHandler
}
session.setExtendedId(_sessionIdManager.getExtendedId(id, null));
- //session.getSessionData().setLastNode(_sessionIdManager.getWorkerName()); //TODO write through the change of node?
}
return session;
}
catch (UnreadableSessionDataException e)
{
- LOG.warn(e);
+ LOG.warn("Error loading session {}", id, e);
try
{
//tell id mgr to remove session from all other contexts
@@ -970,7 +924,7 @@ public class SessionHandler extends ScopedHandler
}
catch (Exception other)
{
- LOG.warn(other);
+ LOG.warn("Unable to get Session", other);
return null;
}
}
@@ -1055,7 +1009,7 @@ public class SessionHandler extends ScopedHandler
}
catch (Exception e)
{
- LOG.warn(e);
+ LOG.warn("Unable to remove Session", e);
return null;
}
}
@@ -1081,6 +1035,12 @@ public class SessionHandler extends ScopedHandler
public void setSessionTrackingModes(Set\nlocal=" + request.getLocalAddr() + ":" + request.getLocalPort() + "\n
\n");
writer.write("\nremote=" + request.getRemoteAddr() + ":" + request.getRemotePort() + "\n
\n");
writer.write("Header:
");
- writer.write(request.getMethod() + " " + request.getRequestURI() + " " + request.getProtocol() + "\n");
+ writer.write(String.format("%4s %s %s\n", request.getMethod(), request.getRequestURI(), request.getProtocol()));
Enumeration
%3Cscript%3E";
+ throw new ServletException(new RuntimeException(message));
+ }
+
+ // produce an exception with a UTF-8 cause message
+ if (target.startsWith("/utf8message/"))
+ {
+ // @checkstyle-disable-check : AvoidEscapedUnicodeCharacters
+ String message = "Euro is € and \u20AC and %E2%82%AC";
+ // @checkstyle-enable-check : AvoidEscapedUnicodeCharacters
+ throw new ServletException(new RuntimeException(message));
}
}
});
@@ -151,193 +133,238 @@ public class ErrorHandlerTest
public static void after() throws Exception
{
server.stop();
+ stacklessLogging.close();
}
@Test
public void test404NoAccept() throws Exception
{
- String response = connector.getResponse(
+ String rawResponse = connector.getResponse(
"GET / HTTP/1.1\r\n" +
"Host: Localhost\r\n" +
"\r\n");
- assertThat(response, startsWith("HTTP/1.1 404 "));
- assertThat(response, not(containsString("Content-Length: 0")));
- assertThat(response, containsString("Content-Type: text/html;charset=iso-8859-1"));
+ HttpTester.Response response = HttpTester.parseResponse(rawResponse);
+
+ assertThat("Response status code", response.getStatus(), is(404));
+ assertThat("Response Content-Length", response.getField(HttpHeader.CONTENT_LENGTH).getIntValue(), greaterThan(0));
+ assertThat("Response Content-Type", response.get(HttpHeader.CONTENT_TYPE), containsString("text/html;charset=ISO-8859-1"));
+
+ assertContent(response);
}
@Test
public void test404EmptyAccept() throws Exception
{
- String response = connector.getResponse(
+ String rawResponse = connector.getResponse(
"GET / HTTP/1.1\r\n" +
"Accept: \r\n" +
"Host: Localhost\r\n" +
"\r\n");
- assertThat(response, startsWith("HTTP/1.1 404 "));
- assertThat(response, containsString("Content-Length: 0"));
- assertThat(response, not(containsString("Content-Type")));
+ HttpTester.Response response = HttpTester.parseResponse(rawResponse);
+
+ assertThat("Response status code", response.getStatus(), is(404));
+ assertThat("Response Content-Length", response.getField(HttpHeader.CONTENT_LENGTH).getIntValue(), is(0));
+ assertThat("Response Content-Type", response.getField(HttpHeader.CONTENT_TYPE), is(nullValue()));
}
@Test
public void test404UnAccept() throws Exception
{
- String response = connector.getResponse(
+ String rawResponse = connector.getResponse(
"GET / HTTP/1.1\r\n" +
"Accept: text/*;q=0\r\n" +
"Host: Localhost\r\n" +
"\r\n");
+ HttpTester.Response response = HttpTester.parseResponse(rawResponse);
- assertThat(response, startsWith("HTTP/1.1 404 "));
- assertThat(response, containsString("Content-Length: 0"));
- assertThat(response, not(containsString("Content-Type")));
+ assertThat("Response status code", response.getStatus(), is(404));
+ assertThat("Response Content-Length", response.getField(HttpHeader.CONTENT_LENGTH).getIntValue(), is(0));
+ assertThat("Response Content-Type", response.getField(HttpHeader.CONTENT_TYPE), is(nullValue()));
}
@Test
public void test404AllAccept() throws Exception
{
- String response = connector.getResponse(
+ String rawResponse = connector.getResponse(
"GET / HTTP/1.1\r\n" +
"Host: Localhost\r\n" +
"Accept: */*\r\n" +
"\r\n");
+ HttpTester.Response response = HttpTester.parseResponse(rawResponse);
- assertThat(response, startsWith("HTTP/1.1 404 "));
- assertThat(response, not(containsString("Content-Length: 0")));
- assertThat(response, containsString("Content-Type: text/html;charset=iso-8859-1"));
+ assertThat("Response status code", response.getStatus(), is(404));
+ assertThat("Response Content-Length", response.getField(HttpHeader.CONTENT_LENGTH).getIntValue(), greaterThan(0));
+ assertThat("Response Content-Type", response.get(HttpHeader.CONTENT_TYPE), containsString("text/html;charset=ISO-8859-1"));
+
+ assertContent(response);
}
@Test
public void test404HtmlAccept() throws Exception
{
- String response = connector.getResponse(
+ String rawResponse = connector.getResponse(
"GET / HTTP/1.1\r\n" +
"Host: Localhost\r\n" +
"Accept: text/html\r\n" +
"\r\n");
- assertThat(response, startsWith("HTTP/1.1 404 "));
- assertThat(response, not(containsString("Content-Length: 0")));
- assertThat(response, containsString("Content-Type: text/html;charset=iso-8859-1"));
+ HttpTester.Response response = HttpTester.parseResponse(rawResponse);
+
+ assertThat("Response status code", response.getStatus(), is(404));
+ assertThat("Response Content-Length", response.getField(HttpHeader.CONTENT_LENGTH).getIntValue(), greaterThan(0));
+ assertThat("Response Content-Type", response.get(HttpHeader.CONTENT_TYPE), containsString("text/html;charset=ISO-8859-1"));
+
+ assertContent(response);
}
@Test
public void testMoreSpecificAccept() throws Exception
{
- String response = connector.getResponse(
+ String rawResponse = connector.getResponse(
"GET / HTTP/1.1\r\n" +
"Host: Localhost\r\n" +
"Accept: text/html, some/other;specific=true\r\n" +
"\r\n");
- assertThat(response, startsWith("HTTP/1.1 404 "));
- assertThat(response, not(containsString("Content-Length: 0")));
- assertThat(response, containsString("Content-Type: text/html;charset=iso-8859-1"));
+ HttpTester.Response response = HttpTester.parseResponse(rawResponse);
+
+ assertThat("Response status code", response.getStatus(), is(404));
+ assertThat("Response Content-Length", response.getField(HttpHeader.CONTENT_LENGTH).getIntValue(), greaterThan(0));
+ assertThat("Response Content-Type", response.get(HttpHeader.CONTENT_TYPE), containsString("text/html;charset=ISO-8859-1"));
+
+ assertContent(response);
}
@Test
public void test404HtmlAcceptAnyCharset() throws Exception
{
- String response = connector.getResponse(
+ String rawResponse = connector.getResponse(
"GET / HTTP/1.1\r\n" +
"Host: Localhost\r\n" +
"Accept: text/html\r\n" +
"Accept-Charset: *\r\n" +
"\r\n");
- assertThat(response, startsWith("HTTP/1.1 404 "));
- assertThat(response, not(containsString("Content-Length: 0")));
- assertThat(response, containsString("Content-Type: text/html;charset=utf-8"));
+ HttpTester.Response response = HttpTester.parseResponse(rawResponse);
+
+ assertThat("Response status code", response.getStatus(), is(404));
+ assertThat("Response Content-Length", response.getField(HttpHeader.CONTENT_LENGTH).getIntValue(), greaterThan(0));
+ assertThat("Response Content-Type", response.get(HttpHeader.CONTENT_TYPE), containsString("text/html;charset=UTF-8"));
+
+ assertContent(response);
}
@Test
public void test404HtmlAcceptUtf8Charset() throws Exception
{
- String response = connector.getResponse(
+ String rawResponse = connector.getResponse(
"GET / HTTP/1.1\r\n" +
"Host: Localhost\r\n" +
"Accept: text/html\r\n" +
"Accept-Charset: utf-8\r\n" +
"\r\n");
- assertThat(response, startsWith("HTTP/1.1 404 "));
- assertThat(response, not(containsString("Content-Length: 0")));
- assertThat(response, containsString("Content-Type: text/html;charset=utf-8"));
+ HttpTester.Response response = HttpTester.parseResponse(rawResponse);
+
+ assertThat("Response status code", response.getStatus(), is(404));
+ assertThat("Response Content-Length", response.getField(HttpHeader.CONTENT_LENGTH).getIntValue(), greaterThan(0));
+ assertThat("Response Content-Type", response.get(HttpHeader.CONTENT_TYPE), containsString("text/html;charset=UTF-8"));
+
+ assertContent(response);
}
@Test
public void test404HtmlAcceptNotUtf8Charset() throws Exception
{
- String response = connector.getResponse(
+ String rawResponse = connector.getResponse(
"GET / HTTP/1.1\r\n" +
"Host: Localhost\r\n" +
"Accept: text/html\r\n" +
"Accept-Charset: utf-8;q=0\r\n" +
"\r\n");
- assertThat(response, startsWith("HTTP/1.1 404 "));
- assertThat(response, not(containsString("Content-Length: 0")));
- assertThat(response, containsString("Content-Type: text/html;charset=iso-8859-1"));
+ HttpTester.Response response = HttpTester.parseResponse(rawResponse);
+
+ assertThat("Response status code", response.getStatus(), is(404));
+ assertThat("Response Content-Length", response.getField(HttpHeader.CONTENT_LENGTH).getIntValue(), greaterThan(0));
+ assertThat("Response Content-Type", response.get(HttpHeader.CONTENT_TYPE), containsString("text/html;charset=ISO-8859-1"));
+
+ assertContent(response);
}
@Test
public void test404HtmlAcceptNotUtf8UnknownCharset() throws Exception
{
- String response = connector.getResponse(
+ String rawResponse = connector.getResponse(
"GET / HTTP/1.1\r\n" +
"Host: Localhost\r\n" +
"Accept: text/html\r\n" +
"Accept-Charset: utf-8;q=0,unknown\r\n" +
"\r\n");
- assertThat(response, startsWith("HTTP/1.1 404 "));
- assertThat(response, containsString("Content-Length: 0"));
- assertThat(response, not(containsString("Content-Type")));
+ HttpTester.Response response = HttpTester.parseResponse(rawResponse);
+
+ assertThat("Response status code", response.getStatus(), is(404));
+ assertThat("Response Content-Length", response.getField(HttpHeader.CONTENT_LENGTH).getIntValue(), is(0));
+ assertThat("Response Content-Type", response.getField(HttpHeader.CONTENT_TYPE), is(nullValue()));
}
@Test
public void test404HtmlAcceptUnknownUtf8Charset() throws Exception
{
- String response = connector.getResponse(
+ String rawResponse = connector.getResponse(
"GET / HTTP/1.1\r\n" +
"Host: Localhost\r\n" +
"Accept: text/html\r\n" +
"Accept-Charset: utf-8;q=0.1,unknown\r\n" +
"\r\n");
- assertThat(response, startsWith("HTTP/1.1 404 "));
- assertThat(response, not(containsString("Content-Length: 0")));
- assertThat(response, containsString("Content-Type: text/html;charset=utf-8"));
+ HttpTester.Response response = HttpTester.parseResponse(rawResponse);
+
+ assertThat("Response status code", response.getStatus(), is(404));
+ assertThat("Response Content-Length", response.getField(HttpHeader.CONTENT_LENGTH).getIntValue(), greaterThan(0));
+ assertThat("Response Content-Type", response.get(HttpHeader.CONTENT_TYPE), containsString("text/html;charset=UTF-8"));
+
+ assertContent(response);
}
@Test
public void test404PreferHtml() throws Exception
{
- String response = connector.getResponse(
+ String rawResponse = connector.getResponse(
"GET / HTTP/1.1\r\n" +
"Host: Localhost\r\n" +
"Accept: text/html;q=1.0,text/json;q=0.5,*/*\r\n" +
"Accept-Charset: *\r\n" +
"\r\n");
- assertThat(response, startsWith("HTTP/1.1 404 "));
- assertThat(response, not(containsString("Content-Length: 0")));
- assertThat(response, containsString("Content-Type: text/html;charset=utf-8"));
+ HttpTester.Response response = HttpTester.parseResponse(rawResponse);
+
+ assertThat("Response status code", response.getStatus(), is(404));
+ assertThat("Response Content-Length", response.getField(HttpHeader.CONTENT_LENGTH).getIntValue(), greaterThan(0));
+ assertThat("Response Content-Type", response.get(HttpHeader.CONTENT_TYPE), containsString("text/html;charset=UTF-8"));
+
+ assertContent(response);
}
@Test
public void test404PreferJson() throws Exception
{
- String response = connector.getResponse(
+ String rawResponse = connector.getResponse(
"GET / HTTP/1.1\r\n" +
"Host: Localhost\r\n" +
"Accept: text/html;q=0.5,text/json;q=1.0,*/*\r\n" +
"Accept-Charset: *\r\n" +
"\r\n");
- assertThat(response, startsWith("HTTP/1.1 404 "));
- assertThat(response, not(containsString("Content-Length: 0")));
- assertThat(response, containsString("Content-Type: text/json"));
+ HttpTester.Response response = HttpTester.parseResponse(rawResponse);
+
+ assertThat("Response status code", response.getStatus(), is(404));
+ assertThat("Response Content-Length", response.getField(HttpHeader.CONTENT_LENGTH).getIntValue(), greaterThan(0));
+ assertThat("Response Content-Type", response.get(HttpHeader.CONTENT_TYPE), containsString("text/json"));
+
+ assertContent(response);
}
@Test
@@ -348,12 +375,14 @@ public class ErrorHandlerTest
"Host: Localhost\r\n" +
"Accept: text/plain\r\n" +
"\r\n");
+
HttpTester.Response response = HttpTester.parseResponse(rawResponse);
assertThat("Response status code", response.getStatus(), is(404));
- HttpField contentType = response.getField(HttpHeader.CONTENT_TYPE);
- assertThat("Response Content-Type", contentType, is(notNullValue()));
- assertThat("Response Content-Type value", contentType.getValue(), not(containsString("null")));
+ assertThat("Response Content-Length", response.getField(HttpHeader.CONTENT_LENGTH).getIntValue(), greaterThan(0));
+ assertThat("Response Content-Type", response.get(HttpHeader.CONTENT_TYPE), containsString("text/plain"));
+
+ assertContent(response);
}
@Test
@@ -363,8 +392,178 @@ public class ErrorHandlerTest
"GET /badmessage/444 HTTP/1.1\r\n" +
"Host: Localhost\r\n" +
"\r\n");
+
HttpTester.Response response = HttpTester.parseResponse(rawResponse);
assertThat("Response status code", response.getStatus(), is(444));
+ assertThat("Response Content-Length", response.getField(HttpHeader.CONTENT_LENGTH).getIntValue(), greaterThan(0));
+ assertThat("Response Content-Type", response.get(HttpHeader.CONTENT_TYPE), containsString("text/html;charset=ISO-8859-1"));
+
+ assertContent(response);
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {
+ "/jsonmessage/",
+ "/xmlmessage/",
+ "/htmlmessage/",
+ "/utf8message/",
+ })
+ public void testComplexCauseMessageNoAcceptHeader(String path) throws Exception
+ {
+ String rawResponse = connector.getResponse(
+ "GET " + path + " HTTP/1.1\r\n" +
+ "Host: Localhost\r\n" +
+ "\r\n");
+
+ HttpTester.Response response = HttpTester.parseResponse(rawResponse);
+
+ assertThat("Response status code", response.getStatus(), is(500));
+ assertThat("Response Content-Length", response.getField(HttpHeader.CONTENT_LENGTH).getIntValue(), greaterThan(0));
+ assertThat("Response Content-Type", response.get(HttpHeader.CONTENT_TYPE), containsString("text/html;charset=ISO-8859-1"));
+
+ String content = assertContent(response);
+
+ if (path.startsWith("/utf8"))
+ {
+ // we are Not expecting UTF-8 output, look for mangled ISO-8859-1 version
+ assertThat("content", content, containsString("Euro is € and ? and %E2%82%AC"));
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {
+ "/jsonmessage/",
+ "/xmlmessage/",
+ "/htmlmessage/",
+ "/utf8message/",
+ })
+ public void testComplexCauseMessageAcceptUtf8Header(String path) throws Exception
+ {
+ String rawResponse = connector.getResponse(
+ "GET " + path + " HTTP/1.1\r\n" +
+ "Host: Localhost\r\n" +
+ "Accept: text/html\r\n" +
+ "Accept-Charset: utf-8\r\n" +
+ "\r\n");
+
+ HttpTester.Response response = HttpTester.parseResponse(rawResponse);
+
+ assertThat("Response status code", response.getStatus(), is(500));
+ assertThat("Response Content-Length", response.getField(HttpHeader.CONTENT_LENGTH).getIntValue(), greaterThan(0));
+ assertThat("Response Content-Type", response.get(HttpHeader.CONTENT_TYPE), containsString("text/html;charset=UTF-8"));
+
+ String content = assertContent(response);
+
+ if (path.startsWith("/utf8"))
+ {
+ // @checkstyle-disable-check : AvoidEscapedUnicodeCharacters
+ // we are Not expecting UTF-8 output, look for mangled ISO-8859-1 version
+ assertThat("content", content, containsString("Euro is € and \u20AC and %E2%82%AC"));
+ // @checkstyle-enabled-check : AvoidEscapedUnicodeCharacters
+ }
+ }
+
+ private String assertContent(HttpTester.Response response)
+ {
+ String contentType = response.get(HttpHeader.CONTENT_TYPE);
+ String content = response.getContent();
+
+ if (contentType.contains("text/html"))
+ {
+ assertThat(content, not(containsString("",
+ "/context/%27list%27/%22me%22/%3B%3Cscript%3Ewindow.alert(%27xss%27)%3B%3C/script%3E"),
+ Arguments.of("test\u00f6?\u00f6:\u00df", "test%C3%B6%3F%C3%B6:%C3%9F"),
+ Arguments.of("test?\u00f6?\u00f6:\u00df", "test%3F%C3%B6%3F%C3%B6:%C3%9F")
+ );
+ }
+
+ @ParameterizedTest(name = "[{index}] {0}")
+ @MethodSource("encodePathSource")
+ public void testEncodePath(String rawPath, String expectedEncoded)
{
// test basic encode/decode
StringBuilder buf = new StringBuilder();
-
buf.setLength(0);
- URIUtil.encodePath(buf, "/foo%23+;,:=/b a r/?info ");
- assertEquals("/foo%2523+%3B,:=/b%20a%20r/%3Finfo%20", buf.toString());
-
- assertEquals("/foo%2523+%3B,:=/b%20a%20r/%3Finfo%20", URIUtil.encodePath("/foo%23+;,:=/b a r/?info "));
+ URIUtil.encodePath(buf, rawPath);
+ assertEquals(expectedEncoded, buf.toString());
+ }
+ @Test
+ public void testEncodeString()
+ {
+ StringBuilder buf = new StringBuilder();
buf.setLength(0);
URIUtil.encodeString(buf, "foo%23;,:=b a r", ";,= ");
assertEquals("foo%2523%3b%2c:%3db%20a%20r", buf.toString());
-
- buf.setLength(0);
- URIUtil.encodePath(buf, "/context/'list'/\"me\"/;");
- assertEquals("/context/%27list%27/%22me%22/%3B%3Cscript%3Ewindow.alert(%27xss%27)%3B%3C/script%3E", buf.toString());
-
- buf.setLength(0);
- URIUtil.encodePath(buf, "test\u00f6?\u00f6:\u00df");
- assertEquals("test%C3%B6%3F%C3%B6:%C3%9F", buf.toString());
-
- buf.setLength(0);
- URIUtil.encodePath(buf, "test?\u00f6?\u00f6:\u00df");
- assertEquals("test%3F%C3%B6%3F%C3%B6:%C3%9F", buf.toString());
}
- @Test // TODO: Parameterize
- public void testDecodePath()
+ public static Stream