├── .github └── workflows │ └── ci-build.yml ├── .gitignore ├── NOTICE.txt ├── README.md ├── build.gradle ├── channel_client.sh ├── channel_server.sh ├── gradle.properties ├── gradle ├── dependency-management.gradle ├── publishing.gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── handshake_server.sh ├── license.md ├── lws_client.sh ├── multiprotocol_callbacks_server.sh ├── multiprotocol_client.sh ├── multiprotocol_default_server.sh ├── netty-websocket-http2-callbacks-codec ├── build.gradle ├── gradle.lockfile └── src │ └── main │ └── java │ └── com │ └── jauntsdn │ └── netty │ └── handler │ └── codec │ └── http2 │ └── websocketx │ └── WebSocketCallbacksCodec.java ├── netty-websocket-http2-example ├── build.gradle └── src │ └── main │ ├── java │ └── com │ │ └── jauntsdn │ │ └── netty │ │ └── handler │ │ └── codec │ │ └── http2 │ │ └── websocketx │ │ └── example │ │ ├── Security.java │ │ ├── channelclient │ │ └── Main.java │ │ ├── channelserver │ │ └── Main.java │ │ ├── handshakeserver │ │ └── Main.java │ │ ├── lwsclient │ │ └── Main.java │ │ └── multiprotocol │ │ ├── client │ │ └── Main.java │ │ └── server │ │ ├── callbackscodec │ │ └── Main.java │ │ └── defaultcodec │ │ └── Main.java │ └── resources │ ├── localhost.crt │ ├── localhost.key │ ├── localhost.p12 │ ├── localhost.pem │ ├── logback.xml │ └── web │ ├── index.html │ └── index.js ├── netty-websocket-http2-perftest ├── build.gradle └── src │ └── main │ ├── java │ └── com │ │ └── jauntsdn │ │ └── netty │ │ └── handler │ │ └── codec │ │ └── http2 │ │ └── websocketx │ │ └── perftest │ │ ├── Security.java │ │ ├── Transport.java │ │ ├── bulkcodec │ │ ├── client │ │ │ └── Main.java │ │ └── server │ │ │ └── Main.java │ │ ├── callbackscodec │ │ ├── client │ │ │ └── Main.java │ │ └── server │ │ │ └── Main.java │ │ └── messagecodec │ │ ├── client │ │ └── Main.java │ │ └── server │ │ └── Main.java │ └── resources │ ├── localhost.p12 │ └── logback.xml ├── netty-websocket-http2 ├── build.gradle ├── gradle.lockfile └── src │ ├── main │ └── java │ │ └── com │ │ └── jauntsdn │ │ └── netty │ │ └── handler │ │ └── codec │ │ └── http2 │ │ └── websocketx │ │ ├── Http1WebSocketCodec.java │ │ ├── Http2WebSocket.java │ │ ├── Http2WebSocketAcceptor.java │ │ ├── Http2WebSocketChannel.java │ │ ├── Http2WebSocketChannelFutureListener.java │ │ ├── Http2WebSocketChannelHandler.java │ │ ├── Http2WebSocketClientBuilder.java │ │ ├── Http2WebSocketClientHandler.java │ │ ├── Http2WebSocketClientHandshaker.java │ │ ├── Http2WebSocketEvent.java │ │ ├── Http2WebSocketHandler.java │ │ ├── Http2WebSocketHandshakeOnlyServerHandler.java │ │ ├── Http2WebSocketPathNotFoundException.java │ │ ├── Http2WebSocketProtocol.java │ │ ├── Http2WebSocketServerBuilder.java │ │ ├── Http2WebSocketServerHandler.java │ │ ├── Http2WebSocketServerHandshaker.java │ │ └── WebSocketEvent.java │ └── test │ ├── java │ └── com │ │ └── jauntsdn │ │ └── netty │ │ └── handler │ │ └── codec │ │ └── http2 │ │ └── websocketx │ │ ├── AbstractTest.java │ │ ├── ApplicationHandshakeTest.java │ │ ├── HeadersValidatorTest.java │ │ ├── NomaskingTest.java │ │ ├── ProtocolHandshakeTest.java │ │ ├── SingleElementOptimizedMapTest.java │ │ ├── TerminationTest.java │ │ └── WebSocketTest.java │ └── resources │ └── localhost.p12 ├── netty-websocket-multiprotocol ├── build.gradle ├── gradle.lockfile └── src │ ├── main │ └── java │ │ └── com │ │ └── jauntsdn │ │ └── netty │ │ └── handler │ │ └── codec │ │ └── websocketx │ │ └── multiprotocol │ │ ├── MultiProtocolWebSocketServerHandler.java │ │ └── MultiprotocolWebSocketServerBuilder.java │ └── test │ ├── java │ └── com │ │ └── jauntsdn │ │ └── netty │ │ └── handler │ │ └── codec │ │ └── websocketx │ │ └── multiprotocol │ │ ├── Security.java │ │ └── WebSocketMultiprotocolTest.java │ └── resources │ ├── localhost.p12 │ └── logback.xml ├── perf_client.sh ├── perf_client_bulk.sh ├── perf_client_bulk_run.sh ├── perf_client_callbacks.sh ├── perf_client_callbacks_run.sh ├── perf_client_run.sh ├── perf_server.sh ├── perf_server_bulk.sh ├── perf_server_bulk_run.sh ├── perf_server_callbacks.sh ├── perf_server_callbacks_run.sh ├── perf_server_run.sh └── settings.gradle /.github/workflows/ci-build.yml: -------------------------------------------------------------------------------- 1 | name: Build 2 | 3 | on: 4 | push: 5 | branches: [ "develop" ] 6 | pull_request: 7 | branches: [ "develop" ] 8 | 9 | permissions: 10 | contents: read 11 | 12 | jobs: 13 | build: 14 | runs-on: ${{ matrix.os }} 15 | 16 | strategy: 17 | matrix: 18 | os: [ ubuntu-24.04, macos-13, windows-2019 ] 19 | jdk: [ 8, 11, 17, 21 ] 20 | fail-fast: false 21 | 22 | steps: 23 | - uses: actions/checkout@v3 24 | - name: Set up JDK ${{ matrix.jdk }} 25 | uses: actions/setup-java@v3 26 | with: 27 | java-version: ${{ matrix.jdk }} 28 | distribution: 'temurin' 29 | - name: Cache Gradle packages 30 | uses: actions/cache@v3 31 | with: 32 | path: ~/.gradle/caches 33 | key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle') }} 34 | restore-keys: ${{ runner.os }}-gradle 35 | - name: Build with Gradle 36 | run: ./gradlew clean build --no-daemon 37 | 38 | 39 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled source # 2 | ################### 3 | *.com 4 | *.class 5 | *.dll 6 | *.exe 7 | *.o 8 | *.so 9 | 10 | # Packages # 11 | ############ 12 | # it's better to unpack these files and commit the raw source 13 | # git has its own built in compression methods 14 | *.7z 15 | *.dmg 16 | *.gz 17 | *.iso 18 | *.jar 19 | *.rar 20 | *.tar 21 | *.zip 22 | 23 | # Logs and databases # 24 | ###################### 25 | *.log 26 | 27 | # OS generated files # 28 | ###################### 29 | .DS_Store* 30 | ehthumbs.db 31 | Icon? 32 | Thumbs.db 33 | 34 | # Editor Files # 35 | ################ 36 | *~ 37 | *.swp 38 | 39 | # Gradle Files # 40 | ################ 41 | .gradle 42 | .ivy2 43 | .ivy2.cache 44 | .m2 45 | !gradle-wrapper.jar 46 | 47 | # Build output directies 48 | /target 49 | */target 50 | /build 51 | */build 52 | 53 | # IntelliJ specific files/directories 54 | out 55 | .idea 56 | *.ipr 57 | *.iws 58 | *.iml 59 | atlassian-ide-plugin.xml 60 | 61 | # Eclipse specific files/directories 62 | .classpath 63 | .project 64 | .settings 65 | .metadata 66 | 67 | # NetBeans specific files/directories 68 | .nbattrs 69 | /bin 70 | 71 | #.gitignore in subdirectory 72 | #.gitignore 73 | 74 | ### infer ### 75 | # infer- http://fbinfer.com/ 76 | infer-out 77 | */infer-out 78 | .inferConfig 79 | */.inferConfig 80 | 81 | */src/generated/* 82 | 83 | bin 84 | -------------------------------------------------------------------------------- /NOTICE.txt: -------------------------------------------------------------------------------- 1 | Copyright 2020-Present Maksym Ostroverkhov. 2 | 3 | Licensed under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. 5 | You may obtain a copy of the License at 6 | 7 | http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | Unless required by applicable law or agreed to in writing, software 10 | distributed under the License is distributed on an "AS IS" BASIS, 11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | See the License for the specific language governing permissions and 13 | limitations under the License. 14 | 15 | ------------------------------------------------------------------------------- 16 | This product contains modified portion of Netty Project, asynchronous event-driven network application framework: 17 | 18 | * LICENSE: 19 | * http://www.apache.org/licenses/LICENSE-2.0 20 | * HOMEPAGE: 21 | * https://netty.io/ -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 - present Maksym Ostroverkhov. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | plugins { 18 | id "com.palantir.git-version" 19 | id "com.github.ben-manes.versions" 20 | 21 | id "com.github.sherter.google-java-format" apply false 22 | id "com.google.osdetector" apply false 23 | id "io.spring.dependency-management" apply false 24 | } 25 | 26 | description = "Netty based implementation of rfc8441 - bootstrapping websockets with http/2. Parent project" 27 | 28 | apply from: "gradle/dependency-management.gradle" 29 | apply from: "gradle/publishing.gradle" 30 | 31 | subprojects { 32 | apply plugin: "com.google.osdetector" 33 | apply plugin: "com.github.sherter.google-java-format" 34 | 35 | version = projectVersion(project) 36 | 37 | println "Building module ${name}:${version}" 38 | 39 | repositories { 40 | mavenCentral() 41 | } 42 | 43 | plugins.withType(JavaPlugin) { 44 | 45 | compileJava { 46 | sourceCompatibility = 1.8 47 | targetCompatibility = 1.8 48 | dependsOn "googleJavaFormat" 49 | } 50 | 51 | javadoc { 52 | options.with { 53 | links jdkJavaDoc() 54 | links "https://netty.io/4.1/api/" 55 | addBooleanOption("Xdoclint:all,-missing", true) 56 | } 57 | } 58 | 59 | test { 60 | if (JavaVersion.current() >= JavaVersion.VERSION_1_9) { 61 | jvmArgs "--add-exports=java.base/sun.security.x509=ALL-UNNAMED" 62 | } 63 | 64 | useJUnitPlatform() 65 | testLogging { 66 | events "failed" 67 | exceptionFormat "full" 68 | } 69 | } 70 | } 71 | 72 | plugins.withType(JavaLibraryPlugin) { 73 | 74 | task sourcesJar(type: Jar, dependsOn: classes) { 75 | classifier "sources" 76 | from sourceSets.main.allJava 77 | } 78 | 79 | task javadocJar(type: Jar, dependsOn: javadoc) { 80 | classifier "javadoc" 81 | from javadoc.destinationDir 82 | } 83 | 84 | artifacts { 85 | archives sourcesJar, javadocJar, jar 86 | } 87 | } 88 | 89 | googleJavaFormat { 90 | toolVersion = "1.6" 91 | } 92 | } 93 | 94 | task printProjectVersion { 95 | doLast { 96 | println "Project version: ${projectVersion(project)}" 97 | } 98 | } 99 | 100 | def jdkJavaDoc() { 101 | def version = JavaVersion.current() 102 | def majorVersion = version.majorVersion 103 | if (version.isJava11Compatible()) { 104 | return "https://docs.oracle.com/en/java/javase/$majorVersion/docs/api/" 105 | } else { 106 | return "https://docs.oracle.com/javase/$majorVersion/docs/api/" 107 | } 108 | } 109 | 110 | def projectVersion(project) { 111 | def versionSuffix = "" 112 | def gitBranchName = versionDetails().branchName 113 | def branchName = gitBranchName ?: project.findProperty("branch") 114 | if (branchName != null) { 115 | if (branchName == "develop") { 116 | versionSuffix = "-SNAPSHOT" 117 | } else if (branchName.startsWith("feature")) { 118 | versionSuffix = "-${branchName.replace("/", "-")}-SNAPSHOT" 119 | } 120 | } 121 | return project.version + versionSuffix 122 | } 123 | 124 | defaultTasks "clean", "build", "installDist" -------------------------------------------------------------------------------- /channel_client.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | ./gradlew netty-websocket-http2-example:runChannelClient -------------------------------------------------------------------------------- /channel_server.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | ./gradlew netty-websocket-http2-example:runChannelServer -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | group=com.jauntsdn.netty 2 | version=1.4.1 3 | 4 | googleJavaFormatPluginVersion=0.9 5 | dependencyManagementPluginVersion=1.1.0 6 | gitPluginVersion=0.13.0 7 | osDetectorPluginVersion=1.7.3 8 | versionsPluginVersion=0.45.0 9 | 10 | nettyVersion=4.1.119.Final 11 | jauntNettyWebsocketHttp1=1.3.0 12 | nettyTcnativeVersion=2.0.70.Final 13 | hdrHistogramVersion=2.1.12 14 | slf4jVersion=1.7.36 15 | logbackVersion=1.2.13 16 | jsr305Version=3.0.2 17 | 18 | junitVersion=5.11.4 19 | assertjVersion=3.27.3 20 | 21 | org.gradle.parallel=true 22 | org.gradle.configureondemand=true -------------------------------------------------------------------------------- /gradle/dependency-management.gradle: -------------------------------------------------------------------------------- 1 | subprojects { 2 | apply plugin: "io.spring.dependency-management" 3 | 4 | dependencyManagement { 5 | imports { 6 | mavenBom "io.netty:netty-bom:${nettyVersion}" 7 | mavenBom "org.junit:junit-bom:${junitVersion}" 8 | } 9 | dependencies { 10 | dependency "com.jauntsdn.netty:netty-websocket-http1:${jauntNettyWebsocketHttp1}" 11 | dependency "org.hdrhistogram:HdrHistogram:${hdrHistogramVersion}" 12 | dependency "io.netty:netty-tcnative-classes:${nettyTcnativeVersion}" 13 | dependency "io.netty:netty-tcnative-boringssl-static:${nettyTcnativeVersion}" 14 | dependency "org.slf4j:slf4j-api:${slf4jVersion}" 15 | dependency "ch.qos.logback:logback-classic:${logbackVersion}" 16 | dependency "com.google.code.findbugs:jsr305:${jsr305Version}" 17 | dependency "org.assertj:assertj-core:${assertjVersion}" 18 | } 19 | 20 | generatedPomCustomization { 21 | enabled = false 22 | } 23 | } 24 | } -------------------------------------------------------------------------------- /gradle/publishing.gradle: -------------------------------------------------------------------------------- 1 | subprojects { 2 | def isRelease = isRelease(project) 3 | def releasedModules = isRelease ? releaseModules() : [] 4 | 5 | tasks.withType(GenerateModuleMetadata) { 6 | enabled = false 7 | } 8 | 9 | plugins.withType(MavenPublishPlugin) { 10 | publishing { 11 | publications { 12 | maven(MavenPublication) { 13 | 14 | plugins.withType(JavaLibraryPlugin) { 15 | from components.java 16 | artifact sourcesJar 17 | artifact javadocJar 18 | } 19 | 20 | pom { 21 | groupId = project.group 22 | name = project.name 23 | afterEvaluate { 24 | description = project.description 25 | } 26 | url = "https://jauntsdn.com" 27 | 28 | licenses { 29 | license { 30 | name = "The Apache Software License, Version 2.0" 31 | url = "http://www.apache.org/license/LICENSE-2.0.txt" 32 | distribution = "repo" 33 | } 34 | } 35 | 36 | developers { 37 | developer { 38 | id = "mostroverkhov" 39 | name = "Maksym Ostroverkhov" 40 | email = "m.ostroverkhov@gmail.com" 41 | } 42 | } 43 | 44 | scm { 45 | connection = "scm:git:https://github.com/jauntsdn/netty-websocket-http2.git" 46 | developerConnection = "scm:git:https://github.com/jauntsdn/netty-websocket-http2.git" 47 | url = "https://github.com/jauntsdn/netty-websocket-http2" 48 | } 49 | 50 | versionMapping { 51 | usage("java-api") { 52 | fromResolutionResult() 53 | } 54 | usage("java-runtime") { 55 | fromResolutionResult() 56 | } 57 | } 58 | } 59 | } 60 | } 61 | 62 | if (project.hasProperty("ossrhUsername") && project.hasProperty("ossrhPassword")) { 63 | 64 | task publishToSonatype { 65 | finalizedBy "publishMavenPublicationToSonatypeRepository" 66 | doLast { 67 | println "\nPublishing ${project.name} artifacts to Sonatype" 68 | println "Sonatype repository url: ${repositories.sonatype.url}\n" 69 | publishing.publications.maven.publishableArtifacts 70 | .collect { it.file.name } 71 | .sort { it } 72 | .each { println "[${project.name}] Uploading artifact..................${it}" } 73 | } 74 | } 75 | 76 | repositories { 77 | maven { 78 | name = "sonatype" 79 | def releasesRepoUrl = "https://oss.sonatype.org/service/local/staging/deploy/maven2/" 80 | def snapshotsRepoUrl = "https://oss.sonatype.org/content/repositories/snapshots/" 81 | url = version.endsWith("SNAPSHOT") ? snapshotsRepoUrl : releasesRepoUrl 82 | credentials { 83 | username = project.property("ossrhUsername") 84 | password = project.property("ossrhPassword") 85 | } 86 | } 87 | } 88 | } 89 | } 90 | 91 | plugins.withType(SigningPlugin) { 92 | signing { 93 | def isSigned = isRelease && releasedModules.contains(project.name) 94 | println("Publication signed: ${isSigned}") 95 | if (isSigned) { 96 | sign publishing.publications.maven 97 | } 98 | } 99 | } 100 | } 101 | } 102 | 103 | def isRelease(Project project) { 104 | return project.hasProperty("release") && project.property("release") == "true" 105 | } 106 | 107 | def releaseModules() { 108 | return ["netty-websocket-http2", "netty-websocket-http2-callbacks-codec", "netty-websocket-multiprotocol"] 109 | } -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jauntsdn/netty-websocket-http2/175e23f9f177d410f670748c453f600c2a3d311e/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.6-bin.zip 4 | networkTimeout=10000 5 | zipStoreBase=GRADLE_USER_HOME 6 | zipStorePath=wrapper/dists 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | # This is normally unused 84 | # shellcheck disable=SC2034 85 | APP_BASE_NAME=${0##*/} 86 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit 87 | 88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | 142 | # Increase the maximum file descriptors if we can. 143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 144 | case $MAX_FD in #( 145 | max*) 146 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. 147 | # shellcheck disable=SC3045 148 | MAX_FD=$( ulimit -H -n ) || 149 | warn "Could not query maximum file descriptor limit" 150 | esac 151 | case $MAX_FD in #( 152 | '' | soft) :;; #( 153 | *) 154 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. 155 | # shellcheck disable=SC3045 156 | ulimit -n "$MAX_FD" || 157 | warn "Could not set maximum file descriptor limit to $MAX_FD" 158 | esac 159 | fi 160 | 161 | # Collect all arguments for the java command, stacking in reverse order: 162 | # * args from the command line 163 | # * the main class name 164 | # * -classpath 165 | # * -D...appname settings 166 | # * --module-path (only if needed) 167 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 168 | 169 | # For Cygwin or MSYS, switch paths to Windows format before running java 170 | if "$cygwin" || "$msys" ; then 171 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 172 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 173 | 174 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 175 | 176 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 177 | for arg do 178 | if 179 | case $arg in #( 180 | -*) false ;; # don't mess with options #( 181 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 182 | [ -e "$t" ] ;; #( 183 | *) false ;; 184 | esac 185 | then 186 | arg=$( cygpath --path --ignore --mixed "$arg" ) 187 | fi 188 | # Roll the args list around exactly as many times as the number of 189 | # args, so each arg winds up back in the position where it started, but 190 | # possibly modified. 191 | # 192 | # NB: a `for` loop captures its iteration list before it begins, so 193 | # changing the positional parameters here affects neither the number of 194 | # iterations, nor the values presented in `arg`. 195 | shift # remove old arg 196 | set -- "$@" "$arg" # push replacement arg 197 | done 198 | fi 199 | 200 | # Collect all arguments for the java command; 201 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 202 | # shell script including quotes and variable substitutions, so put them in 203 | # double quotes to make sure that they get re-expanded; and 204 | # * put everything else in single quotes, so that it's not re-expanded. 205 | 206 | set -- \ 207 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 208 | -classpath "$CLASSPATH" \ 209 | org.gradle.wrapper.GradleWrapperMain \ 210 | "$@" 211 | 212 | # Stop when "xargs" is not available. 213 | if ! command -v xargs >/dev/null 2>&1 214 | then 215 | die "xargs is not available" 216 | fi 217 | 218 | # Use "xargs" to parse quoted args. 219 | # 220 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 221 | # 222 | # In Bash we could simply go: 223 | # 224 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 225 | # set -- "${ARGS[@]}" "$@" 226 | # 227 | # but POSIX shell has neither arrays nor command substitution, so instead we 228 | # post-process each arg (as a line of input to sed) to backslash-escape any 229 | # character that might be a shell metacharacter, then use eval to reverse 230 | # that process (while maintaining the separation between arguments), and wrap 231 | # the whole thing up as a single "set" statement. 232 | # 233 | # This will of course break if any of these variables contains a newline or 234 | # an unmatched quote. 235 | # 236 | 237 | eval "set -- $( 238 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 239 | xargs -n1 | 240 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 241 | tr '\n' ' ' 242 | )" '"$@"' 243 | 244 | exec "$JAVACMD" "$@" 245 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%"=="" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%"=="" set DIRNAME=. 29 | @rem This is normally unused 30 | set APP_BASE_NAME=%~n0 31 | set APP_HOME=%DIRNAME% 32 | 33 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 34 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 35 | 36 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 37 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 38 | 39 | @rem Find java.exe 40 | if defined JAVA_HOME goto findJavaFromJavaHome 41 | 42 | set JAVA_EXE=java.exe 43 | %JAVA_EXE% -version >NUL 2>&1 44 | if %ERRORLEVEL% equ 0 goto execute 45 | 46 | echo. 47 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 48 | echo. 49 | echo Please set the JAVA_HOME variable in your environment to match the 50 | echo location of your Java installation. 51 | 52 | goto fail 53 | 54 | :findJavaFromJavaHome 55 | set JAVA_HOME=%JAVA_HOME:"=% 56 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 57 | 58 | if exist "%JAVA_EXE%" goto execute 59 | 60 | echo. 61 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 62 | echo. 63 | echo Please set the JAVA_HOME variable in your environment to match the 64 | echo location of your Java installation. 65 | 66 | goto fail 67 | 68 | :execute 69 | @rem Setup the command line 70 | 71 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 72 | 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if %ERRORLEVEL% equ 0 goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | set EXIT_CODE=%ERRORLEVEL% 85 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 86 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 87 | exit /b %EXIT_CODE% 88 | 89 | :mainEnd 90 | if "%OS%"=="Windows_NT" endlocal 91 | 92 | :omega 93 | -------------------------------------------------------------------------------- /handshake_server.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | ./gradlew netty-websocket-http2-example:runHandshakeServer -------------------------------------------------------------------------------- /lws_client.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | ./gradlew netty-websocket-http2-example:runLwsClient -------------------------------------------------------------------------------- /multiprotocol_callbacks_server.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | ./gradlew netty-websocket-http2-example:runMultiProtocolCallbacksServer -------------------------------------------------------------------------------- /multiprotocol_client.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | ./gradlew netty-websocket-http2-example:runMultiProtocolClient -------------------------------------------------------------------------------- /multiprotocol_default_server.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | ./gradlew netty-websocket-http2-example:runMultiProtocolDefaultServer -------------------------------------------------------------------------------- /netty-websocket-http2-callbacks-codec/build.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2020 - present Maksym Ostroverkhov. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | plugins { 18 | id "java-library" 19 | id "maven-publish" 20 | id "signing" 21 | } 22 | 23 | description = "netty-websocket-http2 integration with jauntsdn/netty-websocket-http1: high-performance websocket codec" 24 | 25 | dependencies { 26 | api project(":netty-websocket-http2") 27 | api "com.jauntsdn.netty:netty-websocket-http1" 28 | } 29 | 30 | dependencyLocking { 31 | lockAllConfigurations() 32 | } 33 | 34 | tasks.named("jar") { 35 | manifest { 36 | attributes("Automatic-Module-Name": "com.jauntsdn.netty.websocket.http2.codec.callbacks") 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /netty-websocket-http2-callbacks-codec/gradle.lockfile: -------------------------------------------------------------------------------- 1 | # This is a Gradle generated file for dependency locking. 2 | # Manual edits can break the build and are not advised. 3 | # This file is expected to be part of source control. 4 | com.google.code.findbugs:jsr305:3.0.2=googleJavaFormat1.6 5 | com.google.errorprone:error_prone_annotations:2.0.18=googleJavaFormat1.6 6 | com.google.errorprone:javac-shaded:9+181-r4173-1=googleJavaFormat1.6 7 | com.google.googlejavaformat:google-java-format:1.6=googleJavaFormat1.6 8 | com.google.guava:guava:22.0=googleJavaFormat1.6 9 | com.google.j2objc:j2objc-annotations:1.1=googleJavaFormat1.6 10 | com.jauntsdn.netty:netty-websocket-http1:1.3.0=compileClasspath 11 | io.netty:netty-buffer:4.1.119.Final=compileClasspath 12 | io.netty:netty-codec-http2:4.1.119.Final=compileClasspath 13 | io.netty:netty-codec-http:4.1.119.Final=compileClasspath 14 | io.netty:netty-codec:4.1.119.Final=compileClasspath 15 | io.netty:netty-common:4.1.119.Final=compileClasspath 16 | io.netty:netty-handler:4.1.119.Final=compileClasspath 17 | io.netty:netty-resolver:4.1.119.Final=compileClasspath 18 | io.netty:netty-transport-native-unix-common:4.1.119.Final=compileClasspath 19 | io.netty:netty-transport:4.1.119.Final=compileClasspath 20 | org.codehaus.mojo:animal-sniffer-annotations:1.14=googleJavaFormat1.6 21 | empty=annotationProcessor 22 | -------------------------------------------------------------------------------- /netty-websocket-http2-callbacks-codec/src/main/java/com/jauntsdn/netty/handler/codec/http2/websocketx/WebSocketCallbacksCodec.java: -------------------------------------------------------------------------------- 1 | package com.jauntsdn.netty.handler.codec.http2.websocketx; 2 | 3 | import com.jauntsdn.netty.handler.codec.http.websocketx.WebSocketProtocol; 4 | import io.netty.handler.codec.http.websocketx.WebSocketDecoderConfig; 5 | import io.netty.handler.codec.http.websocketx.WebSocketFrameDecoder; 6 | import io.netty.handler.codec.http.websocketx.WebSocketFrameEncoder; 7 | 8 | /** Provides integration with jauntsdn/netty-websocket-http1 - high performance websocket codec. */ 9 | public final class WebSocketCallbacksCodec implements Http1WebSocketCodec { 10 | private static final WebSocketCallbacksCodec INSTANCE = new WebSocketCallbacksCodec(); 11 | 12 | private WebSocketCallbacksCodec() {} 13 | 14 | public static WebSocketCallbacksCodec instance() { 15 | return INSTANCE; 16 | } 17 | 18 | @Override 19 | public WebSocketFrameEncoder encoder(boolean maskPayload) { 20 | return WebSocketProtocol.frameEncoder(maskPayload); 21 | } 22 | 23 | @Override 24 | public WebSocketFrameDecoder decoder(WebSocketDecoderConfig config) { 25 | return WebSocketProtocol.frameDecoder( 26 | config.maxFramePayloadLength(), config.expectMaskedFrames(), config.allowMaskMismatch()); 27 | } 28 | 29 | @Override 30 | public WebSocketFrameDecoder decoder(boolean maskPayload, WebSocketDecoderConfig config) { 31 | return WebSocketProtocol.frameDecoder( 32 | config.maxFramePayloadLength(), config.expectMaskedFrames(), config.allowMaskMismatch()); 33 | } 34 | 35 | @Override 36 | public void validate(boolean maskPayload, WebSocketDecoderConfig config) { 37 | WebSocketProtocol.validateDecoderConfig(config); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /netty-websocket-http2-example/build.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2020 - present Maksym Ostroverkhov. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | plugins { 18 | id "application" 19 | } 20 | 21 | description = "Netty based implementation of rfc8441 - bootstrapping websockets with http/2. Example project" 22 | 23 | dependencies { 24 | implementation project(":netty-websocket-http2") 25 | implementation project(":netty-websocket-multiprotocol") 26 | implementation project(":netty-websocket-http2-callbacks-codec") 27 | implementation "org.slf4j:slf4j-api" 28 | runtimeOnly "io.netty:netty-tcnative-boringssl-static::${osdetector.classifier}" 29 | runtimeOnly "ch.qos.logback:logback-classic" 30 | } 31 | 32 | task runHandshakeServer(type: JavaExec) { 33 | classpath = sourceSets.main.runtimeClasspath 34 | mainClass = "com.jauntsdn.netty.handler.codec.http2.websocketx.example.handshakeserver.Main" 35 | } 36 | 37 | task runChannelServer(type: JavaExec) { 38 | classpath = sourceSets.main.runtimeClasspath 39 | mainClass = "com.jauntsdn.netty.handler.codec.http2.websocketx.example.channelserver.Main" 40 | } 41 | 42 | task runMultiProtocolDefaultServer(type: JavaExec) { 43 | classpath = sourceSets.main.runtimeClasspath 44 | mainClass = "com.jauntsdn.netty.handler.codec.http2.websocketx.example.multiprotocol.server.defaultcodec.Main" 45 | } 46 | 47 | task runMultiProtocolCallbacksServer(type: JavaExec) { 48 | classpath = sourceSets.main.runtimeClasspath 49 | mainClass = "com.jauntsdn.netty.handler.codec.http2.websocketx.example.multiprotocol.server.callbackscodec.Main" 50 | } 51 | 52 | task runChannelClient(type: JavaExec) { 53 | classpath = sourceSets.main.runtimeClasspath 54 | mainClass = "com.jauntsdn.netty.handler.codec.http2.websocketx.example.channelclient.Main" 55 | } 56 | 57 | task runLwsClient(type: JavaExec) { 58 | classpath = sourceSets.main.runtimeClasspath 59 | mainClass = "com.jauntsdn.netty.handler.codec.http2.websocketx.example.lwsclient.Main" 60 | } 61 | 62 | task runMultiProtocolClient(type: JavaExec) { 63 | classpath = sourceSets.main.runtimeClasspath 64 | mainClass = "com.jauntsdn.netty.handler.codec.http2.websocketx.example.multiprotocol.client.Main" 65 | } 66 | 67 | -------------------------------------------------------------------------------- /netty-websocket-http2-example/src/main/java/com/jauntsdn/netty/handler/codec/http2/websocketx/example/Security.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2020 - present Maksym Ostroverkhov. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.jauntsdn.netty.handler.codec.http2.websocketx.example; 18 | 19 | import io.netty.handler.codec.http2.Http2SecurityUtil; 20 | import io.netty.handler.ssl.ApplicationProtocolConfig; 21 | import io.netty.handler.ssl.ApplicationProtocolNames; 22 | import io.netty.handler.ssl.OpenSsl; 23 | import io.netty.handler.ssl.SslContext; 24 | import io.netty.handler.ssl.SslContextBuilder; 25 | import io.netty.handler.ssl.SslProvider; 26 | import io.netty.handler.ssl.SupportedCipherSuiteFilter; 27 | import io.netty.handler.ssl.util.InsecureTrustManagerFactory; 28 | import java.io.InputStream; 29 | import java.security.KeyStore; 30 | import javax.net.ssl.KeyManagerFactory; 31 | import javax.net.ssl.SSLException; 32 | 33 | public final class Security { 34 | 35 | public static SslContext serverSslContext(String keystoreFile, String keystorePassword) 36 | throws Exception { 37 | 38 | KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509"); 39 | SslProvider sslProvider = sslProvider(); 40 | KeyStore keyStore = KeyStore.getInstance("PKCS12"); 41 | 42 | InputStream keystoreStream = Security.class.getClassLoader().getResourceAsStream(keystoreFile); 43 | char[] keystorePasswordArray = keystorePassword.toCharArray(); 44 | keyStore.load(keystoreStream, keystorePasswordArray); 45 | keyManagerFactory.init(keyStore, keystorePasswordArray); 46 | 47 | return SslContextBuilder.forServer(keyManagerFactory) 48 | .protocols("TLSv1.3") 49 | .sslProvider(sslProvider) 50 | .applicationProtocolConfig(alpnConfigHttp2()) 51 | .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE) 52 | .build(); 53 | } 54 | 55 | public static SslContext clientLocalSslContextHttp2() throws SSLException { 56 | return clientSslContextBuilder().trustManager(InsecureTrustManagerFactory.INSTANCE).build(); 57 | } 58 | 59 | public static SslContext clientLocalSslContextHttp1() throws SSLException { 60 | return clientSslContextBuilder() 61 | .trustManager(InsecureTrustManagerFactory.INSTANCE) 62 | .applicationProtocolConfig(alpnConfigHttp1()) 63 | .build(); 64 | } 65 | 66 | public static SslContext clientSslContextHttp2() throws SSLException { 67 | return clientSslContextBuilder().build(); 68 | } 69 | 70 | private static SslContextBuilder clientSslContextBuilder() throws SSLException { 71 | return SslContextBuilder.forClient() 72 | .protocols("TLSv1.3") 73 | .sslProvider(sslProvider()) 74 | .applicationProtocolConfig(alpnConfigHttp2()) 75 | .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE); 76 | } 77 | 78 | private static ApplicationProtocolConfig alpnConfigHttp2() { 79 | return new ApplicationProtocolConfig( 80 | ApplicationProtocolConfig.Protocol.ALPN, 81 | ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE, 82 | ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT, 83 | ApplicationProtocolNames.HTTP_2); 84 | } 85 | 86 | private static ApplicationProtocolConfig alpnConfigHttp1() { 87 | return new ApplicationProtocolConfig( 88 | ApplicationProtocolConfig.Protocol.ALPN, 89 | ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE, 90 | ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT, 91 | ApplicationProtocolNames.HTTP_1_1); 92 | } 93 | 94 | private static SslProvider sslProvider() { 95 | final SslProvider sslProvider; 96 | if (OpenSsl.isAvailable()) { 97 | sslProvider = SslProvider.OPENSSL_REFCNT; 98 | } else { 99 | sslProvider = SslProvider.JDK; 100 | } 101 | return sslProvider; 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /netty-websocket-http2-example/src/main/java/com/jauntsdn/netty/handler/codec/http2/websocketx/example/handshakeserver/Main.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2020 - present Maksym Ostroverkhov. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.jauntsdn.netty.handler.codec.http2.websocketx.example.handshakeserver; 18 | 19 | import com.jauntsdn.netty.handler.codec.http2.websocketx.Http2WebSocketHandler; 20 | import com.jauntsdn.netty.handler.codec.http2.websocketx.Http2WebSocketServerBuilder; 21 | import com.jauntsdn.netty.handler.codec.http2.websocketx.example.Security; 22 | import io.netty.bootstrap.ServerBootstrap; 23 | import io.netty.buffer.Unpooled; 24 | import io.netty.channel.Channel; 25 | import io.netty.channel.ChannelHandlerContext; 26 | import io.netty.channel.ChannelInitializer; 27 | import io.netty.channel.nio.NioEventLoopGroup; 28 | import io.netty.channel.socket.SocketChannel; 29 | import io.netty.channel.socket.nio.NioServerSocketChannel; 30 | import io.netty.handler.codec.http.QueryStringDecoder; 31 | import io.netty.handler.codec.http2.DefaultHttp2GoAwayFrame; 32 | import io.netty.handler.codec.http2.DefaultHttp2HeadersFrame; 33 | import io.netty.handler.codec.http2.DefaultHttp2WindowUpdateFrame; 34 | import io.netty.handler.codec.http2.Http2ChannelDuplexHandler; 35 | import io.netty.handler.codec.http2.Http2DataFrame; 36 | import io.netty.handler.codec.http2.Http2Error; 37 | import io.netty.handler.codec.http2.Http2Frame; 38 | import io.netty.handler.codec.http2.Http2FrameCodec; 39 | import io.netty.handler.codec.http2.Http2FrameCodecBuilder; 40 | import io.netty.handler.codec.http2.Http2FrameStream; 41 | import io.netty.handler.codec.http2.Http2Headers; 42 | import io.netty.handler.codec.http2.Http2HeadersFrame; 43 | import io.netty.handler.codec.http2.Http2ResetFrame; 44 | import io.netty.handler.codec.http2.ReadOnlyHttp2Headers; 45 | import io.netty.handler.ssl.SslContext; 46 | import io.netty.handler.ssl.SslHandler; 47 | import io.netty.util.AsciiString; 48 | import io.netty.util.collection.IntObjectHashMap; 49 | import io.netty.util.collection.IntObjectMap; 50 | import java.io.IOException; 51 | import org.slf4j.Logger; 52 | import org.slf4j.LoggerFactory; 53 | 54 | public class Main { 55 | private static final Logger logger = LoggerFactory.getLogger(Main.class); 56 | 57 | public static void main(String[] args) throws Exception { 58 | String host = System.getProperty("HOST", "localhost"); 59 | int port = Integer.parseInt(System.getProperty("PORT", "8099")); 60 | String echoPath = System.getProperty("PING", "echo"); 61 | String keyStoreFile = System.getProperty("KEYSTORE", "localhost.p12"); 62 | String keyStorePassword = System.getProperty("KEYSTORE_PASS", "localhost"); 63 | 64 | logger.info("\n==> Handshake only websocket server\n"); 65 | logger.info("\n==> Bind address: {}:{}", host, port); 66 | logger.info("\n==> Keystore file: {}", keyStoreFile); 67 | 68 | SslContext sslContext = Security.serverSslContext(keyStoreFile, keyStorePassword); 69 | 70 | ServerBootstrap bootstrap = new ServerBootstrap(); 71 | Channel server = 72 | bootstrap 73 | .group(new NioEventLoopGroup()) 74 | .channel(NioServerSocketChannel.class) 75 | .childHandler(new ConnectionAcceptor(sslContext)) 76 | .bind(host, port) 77 | .sync() 78 | .channel(); 79 | logger.info("\n==> Server is listening on {}:{}", host, port); 80 | 81 | logger.info("\n==> Echo path: {}", echoPath); 82 | 83 | server.closeFuture().sync(); 84 | } 85 | 86 | private static class ConnectionAcceptor extends ChannelInitializer { 87 | private static final int FLOW_CONTROL_WINDOW_SIZE = 1_000; 88 | private final SslContext sslContext; 89 | 90 | ConnectionAcceptor(SslContext sslContext) { 91 | this.sslContext = sslContext; 92 | } 93 | 94 | @Override 95 | protected void initChannel(SocketChannel ch) { 96 | SslHandler sslHandler = sslContext.newHandler(ch.alloc()); 97 | Http2FrameCodecBuilder http2Builder = 98 | Http2WebSocketServerBuilder.configureHttp2Server(Http2FrameCodecBuilder.forServer()); 99 | http2Builder.initialSettings().initialWindowSize(FLOW_CONTROL_WINDOW_SIZE); 100 | Http2FrameCodec frameCodec = http2Builder.build(); 101 | 102 | Http2WebSocketHandler http2webSocketHandler = 103 | Http2WebSocketServerBuilder.buildHandshakeOnly(); 104 | 105 | Http2StreamsHandler http2StreamsHandler = new Http2StreamsHandler(FLOW_CONTROL_WINDOW_SIZE); 106 | ch.pipeline().addLast(sslHandler, frameCodec, http2webSocketHandler, http2StreamsHandler); 107 | } 108 | } 109 | 110 | private static class Http2StreamsHandler extends Http2ChannelDuplexHandler { 111 | private static final ReadOnlyHttp2Headers HEADERS_404 = 112 | ReadOnlyHttp2Headers.serverHeaders(false, AsciiString.of("404")); 113 | private static final ReadOnlyHttp2Headers HEADERS_405 = 114 | ReadOnlyHttp2Headers.serverHeaders(false, AsciiString.of("405")); 115 | private static final ReadOnlyHttp2Headers HEADERS_200 = 116 | ReadOnlyHttp2Headers.serverHeaders(true, AsciiString.of("200")); 117 | private static final ReadOnlyHttp2Headers HEADERS_200_ECHO_PROTOCOL = 118 | ReadOnlyHttp2Headers.serverHeaders( 119 | true, 120 | AsciiString.of("200"), 121 | AsciiString.of("sec-websocket-protocol"), 122 | AsciiString.of("echo.jauntsdn.com")); 123 | 124 | private final IntObjectMap echos = new IntObjectHashMap<>(); 125 | private int receiveBytes; 126 | private final int receiveWindowBytes; 127 | 128 | public Http2StreamsHandler(int receiveWindowBytes) { 129 | this.receiveWindowBytes = receiveWindowBytes; 130 | } 131 | 132 | @Override 133 | public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { 134 | if (msg instanceof Http2Frame) { 135 | if (msg instanceof Http2HeadersFrame) { 136 | Http2HeadersFrame headersFrame = (Http2HeadersFrame) msg; 137 | Http2Headers requestHeaders = headersFrame.headers(); 138 | Http2FrameStream stream = headersFrame.stream(); 139 | CharSequence method = requestHeaders.method(); 140 | String query = requestHeaders.get(":path").toString(); 141 | String path = new QueryStringDecoder(query).path(); 142 | 143 | if (!"POST".contentEquals(method)) { 144 | ctx.write(new DefaultHttp2HeadersFrame(HEADERS_405, true).stream(stream)); 145 | return; 146 | } 147 | 148 | CharSequence protocol = requestHeaders.get("x-protocol"); 149 | if (!"websocket".contentEquals(protocol)) { 150 | ctx.write(new DefaultHttp2HeadersFrame(HEADERS_404, true).stream(stream)); 151 | return; 152 | } 153 | 154 | switch (path) { 155 | case "/echo": 156 | echos.put(stream.id(), stream); 157 | CharSequence subprotocol = requestHeaders.get("sec-websocket-protocol"); 158 | Http2Headers responseHeaders = 159 | subprotocol != null && "echo.jauntsdn.com".contentEquals(subprotocol) 160 | ? HEADERS_200_ECHO_PROTOCOL 161 | : HEADERS_200; 162 | ctx.write(new DefaultHttp2HeadersFrame(responseHeaders, false).stream(stream)); 163 | return; 164 | default: 165 | ctx.write(new DefaultHttp2HeadersFrame(HEADERS_404, true).stream(stream)); 166 | return; 167 | } 168 | 169 | } else if (msg instanceof Http2DataFrame) { 170 | Http2DataFrame dataFrame = (Http2DataFrame) msg; 171 | receiveBytes += dataFrame.content().readableBytes(); 172 | if (receiveBytes >= receiveWindowBytes / 2) { 173 | int windowUpdateBytes = receiveBytes; 174 | receiveBytes = 0; 175 | ctx.writeAndFlush( 176 | new DefaultHttp2WindowUpdateFrame(windowUpdateBytes).stream(dataFrame.stream())); 177 | } 178 | 179 | int streamId = dataFrame.stream().id(); 180 | Http2FrameStream echoStream = 181 | dataFrame.isEndStream() ? echos.remove(streamId) : echos.get(streamId); 182 | if (echoStream != null) { 183 | ctx.write(dataFrame); 184 | return; 185 | } 186 | logger.info("Unknown DATA frame: {}", dataFrame); 187 | 188 | } else if (msg instanceof Http2ResetFrame) { 189 | Http2ResetFrame resetFrame = (Http2ResetFrame) msg; 190 | boolean isEcho = echos.remove(resetFrame.stream().id()) != null; 191 | if (isEcho && resetFrame.errorCode() != Http2Error.CANCEL.code()) { 192 | logger.info("Unexpected RESET frame with non-CANCEL code: {}", resetFrame); 193 | ctx.write( 194 | new DefaultHttp2GoAwayFrame(Http2Error.PROTOCOL_ERROR, Unpooled.EMPTY_BUFFER)); 195 | return; 196 | } 197 | } 198 | } else { 199 | logger.info("Unexpected message: {}", msg); 200 | } 201 | super.channelRead(ctx, msg); 202 | } 203 | 204 | @Override 205 | public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { 206 | ctx.flush(); 207 | super.channelReadComplete(ctx); 208 | } 209 | 210 | @Override 211 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { 212 | if (cause instanceof IOException) { 213 | return; 214 | } 215 | logger.error("Unexpected connection error", cause); 216 | ctx.close(); 217 | } 218 | 219 | @Override 220 | public void channelInactive(ChannelHandlerContext ctx) throws Exception { 221 | echos.clear(); 222 | super.channelInactive(ctx); 223 | } 224 | } 225 | } 226 | -------------------------------------------------------------------------------- /netty-websocket-http2-example/src/main/java/com/jauntsdn/netty/handler/codec/http2/websocketx/example/lwsclient/Main.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2020 - present Maksym Ostroverkhov. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.jauntsdn.netty.handler.codec.http2.websocketx.example.lwsclient; 18 | 19 | import static io.netty.channel.ChannelHandler.Sharable; 20 | 21 | import com.jauntsdn.netty.handler.codec.http2.websocketx.Http2WebSocketClientBuilder; 22 | import com.jauntsdn.netty.handler.codec.http2.websocketx.Http2WebSocketClientHandler; 23 | import com.jauntsdn.netty.handler.codec.http2.websocketx.Http2WebSocketClientHandshaker; 24 | import com.jauntsdn.netty.handler.codec.http2.websocketx.example.Security; 25 | import io.netty.bootstrap.Bootstrap; 26 | import io.netty.channel.Channel; 27 | import io.netty.channel.ChannelFuture; 28 | import io.netty.channel.ChannelHandlerContext; 29 | import io.netty.channel.ChannelInitializer; 30 | import io.netty.channel.EventLoopGroup; 31 | import io.netty.channel.SimpleChannelInboundHandler; 32 | import io.netty.channel.nio.NioEventLoopGroup; 33 | import io.netty.channel.socket.SocketChannel; 34 | import io.netty.channel.socket.nio.NioSocketChannel; 35 | import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; 36 | import io.netty.handler.codec.http.websocketx.WebSocketDecoderConfig; 37 | import io.netty.handler.codec.http2.DefaultHttp2Headers; 38 | import io.netty.handler.codec.http2.Http2FrameCodec; 39 | import io.netty.handler.codec.http2.Http2FrameCodecBuilder; 40 | import io.netty.handler.codec.http2.Http2Headers; 41 | import io.netty.handler.ssl.SslContext; 42 | import io.netty.handler.ssl.SslHandler; 43 | import io.netty.util.concurrent.Future; 44 | import io.netty.util.concurrent.GenericFutureListener; 45 | import io.netty.util.concurrent.ScheduledFuture; 46 | import java.net.InetSocketAddress; 47 | import java.util.concurrent.TimeUnit; 48 | import org.slf4j.Logger; 49 | import org.slf4j.LoggerFactory; 50 | 51 | public class Main { 52 | private static final Logger logger = LoggerFactory.getLogger(Main.class); 53 | 54 | public static void main(String[] args) throws Exception { 55 | String host = System.getProperty("HOST", "libwebsockets.org"); 56 | int port = Integer.parseInt(System.getProperty("PORT", "443")); 57 | InetSocketAddress address = new InetSocketAddress(host, port); 58 | 59 | logger.info("\n==> libwebsockets.org websocket-over-http2 client\n"); 60 | logger.info("\n==> Remote address: {}:{}", host, port); 61 | logger.info("\n==> Dumb increment demo of https://libwebsockets.org/testserver/"); 62 | 63 | SslContext sslContext = Security.clientSslContextHttp2(); 64 | Channel channel = 65 | new Bootstrap() 66 | .group(new NioEventLoopGroup()) 67 | .channel(NioSocketChannel.class) 68 | .handler( 69 | new ChannelInitializer() { 70 | @Override 71 | protected void initChannel(SocketChannel ch) { 72 | SslHandler sslHandler = sslContext.newHandler(ch.alloc()); 73 | Http2FrameCodecBuilder http2FrameCodecBuilder = 74 | Http2FrameCodecBuilder.forClient(); 75 | http2FrameCodecBuilder.initialSettings().initialWindowSize(10_000); 76 | Http2FrameCodec http2FrameCodec = http2FrameCodecBuilder.build(); 77 | Http2WebSocketClientHandler http2WebSocketClientHandler = 78 | Http2WebSocketClientBuilder.create() 79 | .decoderConfig( 80 | WebSocketDecoderConfig.newBuilder() 81 | .expectMaskedFrames(false) 82 | .allowMaskMismatch(false) 83 | .build()) 84 | .handshakeTimeoutMillis(15_000) 85 | .compression(true) 86 | .build(); 87 | 88 | ch.pipeline().addLast(sslHandler, http2FrameCodec, http2WebSocketClientHandler); 89 | } 90 | }) 91 | .connect(address) 92 | .sync() 93 | .channel(); 94 | 95 | Http2WebSocketClientHandshaker handShaker = Http2WebSocketClientHandshaker.create(channel); 96 | 97 | Http2Headers headers = 98 | new DefaultHttp2Headers().set("user-agent", "jauntsdn-websocket-http2-client/1.1.5"); 99 | ChannelFuture handshake = 100 | handShaker.handshake( 101 | "/", "dumb-increment-protocol", headers, new WebSocketDumbIncrementHandler()); 102 | 103 | handshake.addListener(new WebSocketFutureListener()); 104 | 105 | Channel echoWebSocketChannel = handshake.channel(); 106 | 107 | EventLoopGroup eventLoop = echoWebSocketChannel.eventLoop(); 108 | 109 | echoWebSocketChannel.closeFuture().sync(); 110 | logger.info("==> Websocket closed. Terminating client..."); 111 | eventLoop.shutdownGracefully(); 112 | logger.info("==> Client terminated"); 113 | } 114 | 115 | @Sharable 116 | private static class WebSocketDumbIncrementHandler 117 | extends SimpleChannelInboundHandler { 118 | private ScheduledFuture sendResetFuture; 119 | private ScheduledFuture receiveReportFuture; 120 | private int receiveCounter; 121 | private int receiveValue; 122 | 123 | @Override 124 | public void channelActive(ChannelHandlerContext ctx) throws Exception { 125 | sendResetFuture = 126 | ctx.executor() 127 | .scheduleAtFixedRate( 128 | () -> { 129 | ctx.writeAndFlush(new TextWebSocketFrame("reset\n")); 130 | logger.info("==> Sent reset counter websocket frame"); 131 | }, 132 | 5_000, 133 | 5_000, 134 | TimeUnit.MILLISECONDS); 135 | 136 | receiveReportFuture = 137 | ctx.executor() 138 | .scheduleAtFixedRate( 139 | () -> 140 | logger.info( 141 | "==> Received {} frames, latest value: {}", receiveCounter, receiveValue), 142 | 1_000, 143 | 1_000, 144 | TimeUnit.MILLISECONDS); 145 | 146 | super.channelActive(ctx); 147 | } 148 | 149 | @Override 150 | public void channelInactive(ChannelHandlerContext ctx) throws Exception { 151 | sendResetFuture.cancel(true); 152 | receiveReportFuture.cancel(true); 153 | super.channelInactive(ctx); 154 | } 155 | 156 | @Override 157 | protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame webSocketFrame) { 158 | receiveValue = Integer.parseInt(webSocketFrame.text()); 159 | receiveCounter++; 160 | } 161 | } 162 | 163 | private static class WebSocketFutureListener 164 | implements GenericFutureListener> { 165 | @Override 166 | public void operationComplete(Future future) { 167 | if (future.isSuccess()) { 168 | logger.info("==> Websocket channel future success"); 169 | } else { 170 | logger.info("==> Websocket channel future error: {}", future.cause().toString()); 171 | } 172 | } 173 | } 174 | } 175 | -------------------------------------------------------------------------------- /netty-websocket-http2-example/src/main/java/com/jauntsdn/netty/handler/codec/http2/websocketx/example/multiprotocol/server/callbackscodec/Main.java: -------------------------------------------------------------------------------- 1 | package com.jauntsdn.netty.handler.codec.http2.websocketx.example.multiprotocol.server.callbackscodec; 2 | 3 | import com.jauntsdn.netty.handler.codec.http.websocketx.WebSocketCallbacksHandler; 4 | import com.jauntsdn.netty.handler.codec.http.websocketx.WebSocketFrameListener; 5 | import com.jauntsdn.netty.handler.codec.http2.websocketx.Http2WebSocketEvent.Http2WebSocketHandshakeSuccessEvent; 6 | import com.jauntsdn.netty.handler.codec.http2.websocketx.example.Security; 7 | import com.jauntsdn.netty.handler.codec.websocketx.multiprotocol.MultiProtocolWebSocketServerHandler; 8 | import com.jauntsdn.netty.handler.codec.websocketx.multiprotocol.MultiprotocolWebSocketServerBuilder; 9 | import io.netty.bootstrap.ServerBootstrap; 10 | import io.netty.buffer.ByteBuf; 11 | import io.netty.channel.Channel; 12 | import io.netty.channel.ChannelHandlerContext; 13 | import io.netty.channel.ChannelInboundHandlerAdapter; 14 | import io.netty.channel.ChannelInitializer; 15 | import io.netty.channel.nio.NioEventLoopGroup; 16 | import io.netty.channel.socket.SocketChannel; 17 | import io.netty.channel.socket.nio.NioServerSocketChannel; 18 | import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler.HandshakeComplete; 19 | import io.netty.handler.ssl.SslContext; 20 | import io.netty.handler.ssl.SslHandler; 21 | import io.netty.util.ReferenceCountUtil; 22 | import java.io.IOException; 23 | import org.slf4j.Logger; 24 | import org.slf4j.LoggerFactory; 25 | 26 | public class Main { 27 | static final Logger logger = LoggerFactory.getLogger(Main.class); 28 | 29 | public static void main(String[] args) throws Exception { 30 | String host = "localhost"; 31 | int port = 8099; 32 | SslContext sslContext = Security.serverSslContext("localhost.p12", "localhost"); 33 | 34 | Channel server = 35 | new ServerBootstrap() 36 | .group(new NioEventLoopGroup()) 37 | .channel(NioServerSocketChannel.class) 38 | .childHandler( 39 | new ChannelInitializer() { 40 | 41 | @Override 42 | protected void initChannel(SocketChannel ch) { 43 | SslHandler sslHandler = sslContext.newHandler(ch.alloc()); 44 | MultiProtocolWebSocketServerHandler multiprotocolHandler = 45 | MultiprotocolWebSocketServerBuilder.create() 46 | .path("/echo") 47 | .subprotocols("echo.jauntsdn.com") 48 | .callbacksCodec() 49 | .handler( 50 | new ChannelInitializer() { 51 | @Override 52 | protected void initChannel(Channel ch) { 53 | ch.pipeline().addLast(new CallbacksServerHandler()); 54 | } 55 | }) 56 | .build(); 57 | ch.pipeline().addLast(sslHandler, multiprotocolHandler); 58 | } 59 | }) 60 | .bind(host, port) 61 | .sync() 62 | .channel(); 63 | logger.info("\n==> Websocket server (callbacks codec) is listening on {}:{}", host, port); 64 | server.closeFuture().await(); 65 | } 66 | 67 | private static class CallbacksServerHandler extends ChannelInboundHandlerAdapter { 68 | 69 | @Override 70 | public void userEventTriggered(ChannelHandlerContext c, Object evt) throws Exception { 71 | if (evt instanceof HandshakeComplete || evt instanceof Http2WebSocketHandshakeSuccessEvent) { 72 | WebSocketCallbacksHandler.exchange( 73 | c, 74 | (ctx, webSocketFrameFactory) -> 75 | new WebSocketFrameListener() { 76 | @Override 77 | public void onChannelRead( 78 | ChannelHandlerContext context, 79 | boolean finalFragment, 80 | int rsv, 81 | int opcode, 82 | ByteBuf payload) { 83 | ByteBuf textFrame = 84 | webSocketFrameFactory.mask( 85 | webSocketFrameFactory.createTextFrame( 86 | ctx.alloc(), payload.readableBytes())); 87 | textFrame.writeBytes(payload); 88 | payload.release(); 89 | ctx.write(textFrame); 90 | } 91 | 92 | @Override 93 | public void onChannelReadComplete(ChannelHandlerContext ctx1) { 94 | ctx1.flush(); 95 | } 96 | 97 | @Override 98 | public void onExceptionCaught(ChannelHandlerContext ctx1, Throwable cause) { 99 | if (cause instanceof IOException) { 100 | return; 101 | } 102 | logger.error("Unexpected websocket error", cause); 103 | ctx1.close(); 104 | } 105 | }); 106 | } 107 | super.userEventTriggered(c, evt); 108 | } 109 | 110 | @Override 111 | public void channelRead(ChannelHandlerContext ctx, Object msg) { 112 | ReferenceCountUtil.safeRelease(msg); 113 | } 114 | } 115 | } 116 | -------------------------------------------------------------------------------- /netty-websocket-http2-example/src/main/java/com/jauntsdn/netty/handler/codec/http2/websocketx/example/multiprotocol/server/defaultcodec/Main.java: -------------------------------------------------------------------------------- 1 | package com.jauntsdn.netty.handler.codec.http2.websocketx.example.multiprotocol.server.defaultcodec; 2 | 3 | import com.jauntsdn.netty.handler.codec.http2.websocketx.example.Security; 4 | import com.jauntsdn.netty.handler.codec.websocketx.multiprotocol.MultiProtocolWebSocketServerHandler; 5 | import com.jauntsdn.netty.handler.codec.websocketx.multiprotocol.MultiprotocolWebSocketServerBuilder; 6 | import io.netty.bootstrap.ServerBootstrap; 7 | import io.netty.channel.Channel; 8 | import io.netty.channel.ChannelHandler; 9 | import io.netty.channel.ChannelHandlerContext; 10 | import io.netty.channel.ChannelInitializer; 11 | import io.netty.channel.SimpleChannelInboundHandler; 12 | import io.netty.channel.nio.NioEventLoopGroup; 13 | import io.netty.channel.socket.SocketChannel; 14 | import io.netty.channel.socket.nio.NioServerSocketChannel; 15 | import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; 16 | import io.netty.handler.ssl.SslContext; 17 | import io.netty.handler.ssl.SslHandler; 18 | import java.io.IOException; 19 | import org.slf4j.Logger; 20 | import org.slf4j.LoggerFactory; 21 | 22 | public class Main { 23 | static final Logger logger = LoggerFactory.getLogger(Main.class); 24 | 25 | public static void main(String[] args) throws Exception { 26 | String host = "localhost"; 27 | int port = 8099; 28 | SslContext sslContext = Security.serverSslContext("localhost.p12", "localhost"); 29 | 30 | Channel server = 31 | new ServerBootstrap() 32 | .group(new NioEventLoopGroup()) 33 | .channel(NioServerSocketChannel.class) 34 | .childHandler( 35 | new ChannelInitializer() { 36 | 37 | @Override 38 | protected void initChannel(SocketChannel ch) { 39 | SslHandler sslHandler = sslContext.newHandler(ch.alloc()); 40 | MultiProtocolWebSocketServerHandler multiprotocolHandler = 41 | MultiprotocolWebSocketServerBuilder.create() 42 | .path("/echo") 43 | .subprotocols("echo.jauntsdn.com") 44 | .defaultCodec() 45 | .handler(new DefaultEchoWebSocketHandler()) 46 | .build(); 47 | ch.pipeline().addLast(sslHandler, multiprotocolHandler); 48 | } 49 | }) 50 | .bind(host, port) 51 | .sync() 52 | .channel(); 53 | logger.info("\n==> Websocket server (default codec) is listening on {}:{}", host, port); 54 | server.closeFuture().await(); 55 | } 56 | 57 | @ChannelHandler.Sharable 58 | private static class DefaultEchoWebSocketHandler 59 | extends SimpleChannelInboundHandler { 60 | 61 | @Override 62 | protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame webSocketFrame) { 63 | ctx.write(webSocketFrame.retain()); 64 | } 65 | 66 | @Override 67 | public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { 68 | ctx.flush(); 69 | super.channelReadComplete(ctx); 70 | } 71 | 72 | @Override 73 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { 74 | if (cause instanceof IOException) { 75 | return; 76 | } 77 | logger.error("Unexpected websocket error", cause); 78 | ctx.close(); 79 | } 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /netty-websocket-http2-example/src/main/resources/localhost.crt: -------------------------------------------------------------------------------- 1 | -----BEGIN CERTIFICATE----- 2 | MIIFKTCCAxGgAwIBAgIUNCjrdqhXXacTgpuyGsrbIJ4mVA4wDQYJKoZIhvcNAQEL 3 | BQAwFDESMBAGA1UEAwwJbG9jYWxob3N0MB4XDTIwMDYxNzEzNTM1M1oXDTMwMDYx 4 | NTEzNTM1M1owFDESMBAGA1UEAwwJbG9jYWxob3N0MIICIjANBgkqhkiG9w0BAQEF 5 | AAOCAg8AMIICCgKCAgEAwUaMBUSHML7ZivN+pTyXjo4Mz/WpytuPUqjgfFGHBmwV 6 | +sWLXtp1DFYOZGGK4bTPGIMY/gAKEJPxbQlMnurUBvHiXN6SyIt1llB6Kc5W5fOj 7 | xAizZLvR4mNYFdgpVD+R+cRj3GTBE3NNb/DqcrkV3jlhhjiFdgq1DoeXgPcyJiay 8 | UOoXmV9XBKvhqbnQ7NBwRYaLtDSAcDXtN+3hvURb1dC6C8/cuTi3NZqPT1GPwof2 9 | qOsSu2HdGhsldnTy6dp76aQ+4QAkMCywyJ5m1QxmSRkTSARvydhV2lJ1NRfSdP8G 10 | cMBZVHQm78N21eP6081O3EUromt11JNiHEIZEVAXtYEtaWvW8GovNILc2GAOASxX 11 | UM/r9ZHtLSimMVvwMjE9WDUkXNM2uy0VKB6/xIUR4om+WuSgxA4cWRdBcvtQ4YPf 12 | 6tgbNXlM0O0ss4wwc9dEoVDmyxZZQ8rqFEXIbIzZI+0+33MUSt/+rR5bFNLfISxd 13 | +4otQkQr3017tEbP6dH1O32mqMb4655LWmPh79NPvH+5qZRWu9PD9aH7YSR1r36e 14 | hUXkYgFCTrmU5tfSsexBkLI3MeG16kOS9WDYVbgaAHYN28xkhSu8irpW8UY6Hloj 15 | fW4XngMQx1OWI0/p2GBP1bu32Gbknq2OO6V0OA0QdYH1BlHSg9yzLgl01QQTmzEC 16 | AwEAAaNzMHEwHQYDVR0OBBYEFGXIPYFuV/utsuJnY+1czpYpN1lSMB8GA1UdIwQY 17 | MBaAFGXIPYFuV/utsuJnY+1czpYpN1lSMA8GA1UdEwEB/wQFMAMBAf8wHgYDVR0R 18 | BBcwFYINd3d3LmxvY2FsaG9zdIcEfwAAATANBgkqhkiG9w0BAQsFAAOCAgEAPA8n 19 | s/EgLiNHsaF4dcsr+dx8tG6a7V8EqyV8n2PgmBoFfYxi1rTkrxuwS0eLcgzVGdWe 20 | QMseww5mxcfIZbyKiC8EWLdh5BeKj2G3dseOEQj6xR+MbmvZBzycEMXvLBc9EcIK 21 | 2YbCjgoK+raJg1ljbtjBP5gwXYpUrJpER54zI7tTLZ/+V2S8scN+IgA6zBf1D0kZ 22 | MriIXilro59qu4GsM2SAlHHHQDohrKCvhWjQw2hu6o+TA/ZhaFQ+c+NBuvGiHnKr 23 | hV21Lxevta/vuhKdmrCtj6P69x7wiAq0zlFGvr8uop1/CejqkEitieY7HJhCQBjb 24 | 8ENTs4IT0HV9SRK+w86Mf16tly4l/GettNS5eGZpkdxYH7twCSM1pEBdJPcjx9ug 25 | 8rAloI2Zh5JuYyKA0qf0ZnAQ5K0glSp36uyCOTCONb8gW2l05GbFWdBq7ZZlFNxn 26 | WHtCJQDl/HIxZUnVpqcgiZVv+JpdAczq384XBQcn/HbqbX6Hr7QBZ/lC68fbu/kz 27 | FPAun0bKNVbqurk8yE5qI8EaTnoJdY9hkR0w27Ywts6kRjCYTZM+SguFd0bzTXt0 28 | x2XBxUlkX21BHiB7KGpG9bpXiZqlG4c3THtIWwIK79Mz3suMkzWcPK9xhPGStvdD 29 | AxfSkKeVUsV9hLVHS3HYfNDpnhqd8iyOHs1JkKE= 30 | -----END CERTIFICATE----- 31 | -------------------------------------------------------------------------------- /netty-websocket-http2-example/src/main/resources/localhost.key: -------------------------------------------------------------------------------- 1 | -----BEGIN PRIVATE KEY----- 2 | MIIJQwIBADANBgkqhkiG9w0BAQEFAASCCS0wggkpAgEAAoICAQDBRowFRIcwvtmK 3 | 836lPJeOjgzP9anK249SqOB8UYcGbBX6xYte2nUMVg5kYYrhtM8Ygxj+AAoQk/Ft 4 | CUye6tQG8eJc3pLIi3WWUHopzlbl86PECLNku9HiY1gV2ClUP5H5xGPcZMETc01v 5 | 8OpyuRXeOWGGOIV2CrUOh5eA9zImJrJQ6heZX1cEq+GpudDs0HBFhou0NIBwNe03 6 | 7eG9RFvV0LoLz9y5OLc1mo9PUY/Ch/ao6xK7Yd0aGyV2dPLp2nvppD7hACQwLLDI 7 | nmbVDGZJGRNIBG/J2FXaUnU1F9J0/wZwwFlUdCbvw3bV4/rTzU7cRSuia3XUk2Ic 8 | QhkRUBe1gS1pa9bwai80gtzYYA4BLFdQz+v1ke0tKKYxW/AyMT1YNSRc0za7LRUo 9 | Hr/EhRHiib5a5KDEDhxZF0Fy+1Dhg9/q2Bs1eUzQ7SyzjDBz10ShUObLFllDyuoU 10 | RchsjNkj7T7fcxRK3/6tHlsU0t8hLF37ii1CRCvfTXu0Rs/p0fU7faaoxvjrnkta 11 | Y+Hv00+8f7mplFa708P1ofthJHWvfp6FReRiAUJOuZTm19Kx7EGQsjcx4bXqQ5L1 12 | YNhVuBoAdg3bzGSFK7yKulbxRjoeWiN9bheeAxDHU5YjT+nYYE/Vu7fYZuSerY47 13 | pXQ4DRB1gfUGUdKD3LMuCXTVBBObMQIDAQABAoICAD+36FWcQA2b/dBHcks7bKO8 14 | xRCSZwXP2LJhppCVuDQv0hc4pTgCQXBttpT1a3n5yATGw6iJjsfkXkWaOT5zIK+h 15 | cwU3A6FGCOAjbAL4WcG5zxXD4JCnMwy1v8aD2yxBQPjc/CceuGCXNMJg5Iop5sG6 16 | nSJI5AcEhKhjn1kPJeNaApOWeW1A90k8+UqhTfWkyj7BmrEwVd+oh6pWrINfU/9r 17 | rspSHuyZfB0Z9YEq3IA/ntwVk7lfDCudI36oE6VxOETQt0Iqb8PKGAYr4q7+RYJ3 18 | 19l4TPp4beVqJeX5EpMruI3XfBvRpzyIblcZsAm/t+36h+YmE1Sfukqip+0DQK0t 19 | W8+PGLfOq1mcQR+M/KQ2NZtvBOfrn+2L3dTcsMftlSRqLLOyE3WH9fKfH5oU1jh3 20 | V67+U3tqdUBrxTZOohdqHrqIdvCOONic1w0aJp4V1MSdi3Ti5t5pc9cHf6wG0sjX 21 | gjmA9UXrrSp5JM0Z1UdILs+U3dv0nSEZSujaI+q1Z+nfW4r4kP6se/yzphJ+gO8N 22 | 7v1XCo5IJi3y0THIK7Wlz1gTvi9k8906Ux1RBc11Cn9w+rcigQNs/0JDd+DVCr4I 23 | RlCO9gyAeZYw8H4bQ4fflu7Ob6NdNyNhf9rpK40XhzmRkZen/M2Z3HLcaBYmmaHj 24 | XVMp02z+f4GbjFfC96w5AoIBAQDfr1yjDYIVId1bF6gFZcBPwwxdKvI9vutqatml 25 | QNNo2JqDUGUD3w5q7632bQpIW0l+9DvVfKiwHIQBqWapd+i9ItTh1ylkVxJJCbvg 26 | dFZZWLC3w/+zrdpiBUwGsoDNrfqqvyytuHh6QXpb9fr5h1g6YCNbQlBFrKMPXCWp 27 | Cx4tCR6tzr2cZvFNol/GcK8nv6AE5omPV2LA23XAQmNGm1RuWgPpYPHCdf4zUgX0 28 | quuSl7arJDjLqCWXPOjB+pIBQmR6HdyV3OUXoij74wr6DJgaZmK4ft6D0dQXrHE9 29 | xoJHsujtSz9pri+d2OZjLCctM8DwedxsStvv3XTqhG2WjZ/7AoIBAQDdMoo/9NVZ 30 | 00Fn9QMRT/emsa4C8mkN5ZZqU+Jb+ghU1Wu8ASjy07viTz+QxwTIea5HqmkczwN7 31 | L7CsaCGyRDNgdcwPaintLffTdra5+ujnFFB/KbuNL2Ofs79F5u9j5sBlgrIkCw05 32 | 4vIuWAp8WdVYYr/lxXhsG2cbEzud1KmZeB+qB531s812bOqZnjRRMFs+QRytiFlZ 33 | kUsAa6kuPVc69UNznXHFqs3/nDJ5kkmlYFZldThLrbmDAA+rPAcxVnKAit8WmkHy 34 | he9mLEA1E9LA8xTpOjj7abFTJSWVCROpCw5mQviQiD29YkoupikbxWGwCTi9tjYJ 35 | pQY4At9LyQ3DAoIBADbxuk2K6eMK+HaBrxH0VnLBNG5GOE6WcPko2eFPtR5R5lJP 36 | EyEKT15RFWgsjJQNaFY44+Gix0TLHFnUJJWIELE0txnqYg51nNY3/+A4c2Vq9a2O 37 | BWc7UyM0reIPQrhC/gmm//CEGYPeRZIFL+rPJgrgxo6KEXGr4DnLpqyJQJZLYS/M 38 | UqLyXl91fRUfZMbcuQ+7GRsOmgFJZvkc1YnoaarZjZBr8baUiSZOBYx913OgtIwB 39 | T7omyWUG3x2W0PpiNpAQebiOE+/kMzD8KhwVr978O0+aSkoS5ogSIZbNBf9aoQB4 40 | tVDeKnAZcS33EIB37/Kh3FT1ZmTa/vcEJG8QxrUCggEBAM2caCQxOozHsZmnh5V1 41 | JvgdW2pD2OFhE2N83AGxNkNdK0rULTMjHBeuoKC8TrbnXNgjEJgF2e+NEgYAuanS 42 | eYtllCyT+6sLur0nMY1JLWt3V6gMq9j+PvW5iMe6dbYATcFOLrcQStgPHB12GzEh 43 | 9A23pTc5Ssn64umpBBafEpOktJJBiFRXMVquvZfUFj+N2pLQxY6NGrkGNJiMevOP 44 | c2FLkMqMhLBAKEI8+DJHiAugtE6VGqJGNxYNXYNHRkxXVhIkhGCnPTvpwfHQmlJ8 45 | PcC7dCmjxEn3Iizub7PMfyj4LQdjo1f+PJ2pGtmn/Lhizn5q5AJ8uFhYvKIeEWCJ 46 | 4C8CggEBAMxw805RiDyyeM6cTh5wvA+5jVjYuV/V9aw7luG/8fGQc5BlIoT7oLsA 47 | qL2OA6q3zomsiCBTdrJM4Nm/DYJeYZoum1IYjtNlimTwUgfImCOdnQlY925I2jLG 48 | JC0wCzN6FfizVsz6isAg9zm029BmAFjx+Qhg3L4KiZcCxhqRKDuUpqqy55XjAAWw 49 | Zo4MWlY4FCeWcNeUklFIIUJGkmPfZduCQ3Q43vAdmG71aQ6PGPmu/si/dCVXGOZ7 50 | Fg6rT2J2+FZP6wEq9Lw8AMo/EhBYBbgxo5nT2NlQoqGzyII2eDsrtWkbYZJ9hICA 51 | 6Pr4omHuZW/QlLrRSvz6XsbULVzGyG0= 52 | -----END PRIVATE KEY----- 53 | -------------------------------------------------------------------------------- /netty-websocket-http2-example/src/main/resources/localhost.p12: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jauntsdn/netty-websocket-http2/175e23f9f177d410f670748c453f600c2a3d311e/netty-websocket-http2-example/src/main/resources/localhost.p12 -------------------------------------------------------------------------------- /netty-websocket-http2-example/src/main/resources/localhost.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN CERTIFICATE----- 2 | MIIFKTCCAxGgAwIBAgIUNCjrdqhXXacTgpuyGsrbIJ4mVA4wDQYJKoZIhvcNAQEL 3 | BQAwFDESMBAGA1UEAwwJbG9jYWxob3N0MB4XDTIwMDYxNzEzNTM1M1oXDTMwMDYx 4 | NTEzNTM1M1owFDESMBAGA1UEAwwJbG9jYWxob3N0MIICIjANBgkqhkiG9w0BAQEF 5 | AAOCAg8AMIICCgKCAgEAwUaMBUSHML7ZivN+pTyXjo4Mz/WpytuPUqjgfFGHBmwV 6 | +sWLXtp1DFYOZGGK4bTPGIMY/gAKEJPxbQlMnurUBvHiXN6SyIt1llB6Kc5W5fOj 7 | xAizZLvR4mNYFdgpVD+R+cRj3GTBE3NNb/DqcrkV3jlhhjiFdgq1DoeXgPcyJiay 8 | UOoXmV9XBKvhqbnQ7NBwRYaLtDSAcDXtN+3hvURb1dC6C8/cuTi3NZqPT1GPwof2 9 | qOsSu2HdGhsldnTy6dp76aQ+4QAkMCywyJ5m1QxmSRkTSARvydhV2lJ1NRfSdP8G 10 | cMBZVHQm78N21eP6081O3EUromt11JNiHEIZEVAXtYEtaWvW8GovNILc2GAOASxX 11 | UM/r9ZHtLSimMVvwMjE9WDUkXNM2uy0VKB6/xIUR4om+WuSgxA4cWRdBcvtQ4YPf 12 | 6tgbNXlM0O0ss4wwc9dEoVDmyxZZQ8rqFEXIbIzZI+0+33MUSt/+rR5bFNLfISxd 13 | +4otQkQr3017tEbP6dH1O32mqMb4655LWmPh79NPvH+5qZRWu9PD9aH7YSR1r36e 14 | hUXkYgFCTrmU5tfSsexBkLI3MeG16kOS9WDYVbgaAHYN28xkhSu8irpW8UY6Hloj 15 | fW4XngMQx1OWI0/p2GBP1bu32Gbknq2OO6V0OA0QdYH1BlHSg9yzLgl01QQTmzEC 16 | AwEAAaNzMHEwHQYDVR0OBBYEFGXIPYFuV/utsuJnY+1czpYpN1lSMB8GA1UdIwQY 17 | MBaAFGXIPYFuV/utsuJnY+1czpYpN1lSMA8GA1UdEwEB/wQFMAMBAf8wHgYDVR0R 18 | BBcwFYINd3d3LmxvY2FsaG9zdIcEfwAAATANBgkqhkiG9w0BAQsFAAOCAgEAPA8n 19 | s/EgLiNHsaF4dcsr+dx8tG6a7V8EqyV8n2PgmBoFfYxi1rTkrxuwS0eLcgzVGdWe 20 | QMseww5mxcfIZbyKiC8EWLdh5BeKj2G3dseOEQj6xR+MbmvZBzycEMXvLBc9EcIK 21 | 2YbCjgoK+raJg1ljbtjBP5gwXYpUrJpER54zI7tTLZ/+V2S8scN+IgA6zBf1D0kZ 22 | MriIXilro59qu4GsM2SAlHHHQDohrKCvhWjQw2hu6o+TA/ZhaFQ+c+NBuvGiHnKr 23 | hV21Lxevta/vuhKdmrCtj6P69x7wiAq0zlFGvr8uop1/CejqkEitieY7HJhCQBjb 24 | 8ENTs4IT0HV9SRK+w86Mf16tly4l/GettNS5eGZpkdxYH7twCSM1pEBdJPcjx9ug 25 | 8rAloI2Zh5JuYyKA0qf0ZnAQ5K0glSp36uyCOTCONb8gW2l05GbFWdBq7ZZlFNxn 26 | WHtCJQDl/HIxZUnVpqcgiZVv+JpdAczq384XBQcn/HbqbX6Hr7QBZ/lC68fbu/kz 27 | FPAun0bKNVbqurk8yE5qI8EaTnoJdY9hkR0w27Ywts6kRjCYTZM+SguFd0bzTXt0 28 | x2XBxUlkX21BHiB7KGpG9bpXiZqlG4c3THtIWwIK79Mz3suMkzWcPK9xhPGStvdD 29 | AxfSkKeVUsV9hLVHS3HYfNDpnhqd8iyOHs1JkKE= 30 | -----END CERTIFICATE----- 31 | -----BEGIN PRIVATE KEY----- 32 | MIIJQwIBADANBgkqhkiG9w0BAQEFAASCCS0wggkpAgEAAoICAQDBRowFRIcwvtmK 33 | 836lPJeOjgzP9anK249SqOB8UYcGbBX6xYte2nUMVg5kYYrhtM8Ygxj+AAoQk/Ft 34 | CUye6tQG8eJc3pLIi3WWUHopzlbl86PECLNku9HiY1gV2ClUP5H5xGPcZMETc01v 35 | 8OpyuRXeOWGGOIV2CrUOh5eA9zImJrJQ6heZX1cEq+GpudDs0HBFhou0NIBwNe03 36 | 7eG9RFvV0LoLz9y5OLc1mo9PUY/Ch/ao6xK7Yd0aGyV2dPLp2nvppD7hACQwLLDI 37 | nmbVDGZJGRNIBG/J2FXaUnU1F9J0/wZwwFlUdCbvw3bV4/rTzU7cRSuia3XUk2Ic 38 | QhkRUBe1gS1pa9bwai80gtzYYA4BLFdQz+v1ke0tKKYxW/AyMT1YNSRc0za7LRUo 39 | Hr/EhRHiib5a5KDEDhxZF0Fy+1Dhg9/q2Bs1eUzQ7SyzjDBz10ShUObLFllDyuoU 40 | RchsjNkj7T7fcxRK3/6tHlsU0t8hLF37ii1CRCvfTXu0Rs/p0fU7faaoxvjrnkta 41 | Y+Hv00+8f7mplFa708P1ofthJHWvfp6FReRiAUJOuZTm19Kx7EGQsjcx4bXqQ5L1 42 | YNhVuBoAdg3bzGSFK7yKulbxRjoeWiN9bheeAxDHU5YjT+nYYE/Vu7fYZuSerY47 43 | pXQ4DRB1gfUGUdKD3LMuCXTVBBObMQIDAQABAoICAD+36FWcQA2b/dBHcks7bKO8 44 | xRCSZwXP2LJhppCVuDQv0hc4pTgCQXBttpT1a3n5yATGw6iJjsfkXkWaOT5zIK+h 45 | cwU3A6FGCOAjbAL4WcG5zxXD4JCnMwy1v8aD2yxBQPjc/CceuGCXNMJg5Iop5sG6 46 | nSJI5AcEhKhjn1kPJeNaApOWeW1A90k8+UqhTfWkyj7BmrEwVd+oh6pWrINfU/9r 47 | rspSHuyZfB0Z9YEq3IA/ntwVk7lfDCudI36oE6VxOETQt0Iqb8PKGAYr4q7+RYJ3 48 | 19l4TPp4beVqJeX5EpMruI3XfBvRpzyIblcZsAm/t+36h+YmE1Sfukqip+0DQK0t 49 | W8+PGLfOq1mcQR+M/KQ2NZtvBOfrn+2L3dTcsMftlSRqLLOyE3WH9fKfH5oU1jh3 50 | V67+U3tqdUBrxTZOohdqHrqIdvCOONic1w0aJp4V1MSdi3Ti5t5pc9cHf6wG0sjX 51 | gjmA9UXrrSp5JM0Z1UdILs+U3dv0nSEZSujaI+q1Z+nfW4r4kP6se/yzphJ+gO8N 52 | 7v1XCo5IJi3y0THIK7Wlz1gTvi9k8906Ux1RBc11Cn9w+rcigQNs/0JDd+DVCr4I 53 | RlCO9gyAeZYw8H4bQ4fflu7Ob6NdNyNhf9rpK40XhzmRkZen/M2Z3HLcaBYmmaHj 54 | XVMp02z+f4GbjFfC96w5AoIBAQDfr1yjDYIVId1bF6gFZcBPwwxdKvI9vutqatml 55 | QNNo2JqDUGUD3w5q7632bQpIW0l+9DvVfKiwHIQBqWapd+i9ItTh1ylkVxJJCbvg 56 | dFZZWLC3w/+zrdpiBUwGsoDNrfqqvyytuHh6QXpb9fr5h1g6YCNbQlBFrKMPXCWp 57 | Cx4tCR6tzr2cZvFNol/GcK8nv6AE5omPV2LA23XAQmNGm1RuWgPpYPHCdf4zUgX0 58 | quuSl7arJDjLqCWXPOjB+pIBQmR6HdyV3OUXoij74wr6DJgaZmK4ft6D0dQXrHE9 59 | xoJHsujtSz9pri+d2OZjLCctM8DwedxsStvv3XTqhG2WjZ/7AoIBAQDdMoo/9NVZ 60 | 00Fn9QMRT/emsa4C8mkN5ZZqU+Jb+ghU1Wu8ASjy07viTz+QxwTIea5HqmkczwN7 61 | L7CsaCGyRDNgdcwPaintLffTdra5+ujnFFB/KbuNL2Ofs79F5u9j5sBlgrIkCw05 62 | 4vIuWAp8WdVYYr/lxXhsG2cbEzud1KmZeB+qB531s812bOqZnjRRMFs+QRytiFlZ 63 | kUsAa6kuPVc69UNznXHFqs3/nDJ5kkmlYFZldThLrbmDAA+rPAcxVnKAit8WmkHy 64 | he9mLEA1E9LA8xTpOjj7abFTJSWVCROpCw5mQviQiD29YkoupikbxWGwCTi9tjYJ 65 | pQY4At9LyQ3DAoIBADbxuk2K6eMK+HaBrxH0VnLBNG5GOE6WcPko2eFPtR5R5lJP 66 | EyEKT15RFWgsjJQNaFY44+Gix0TLHFnUJJWIELE0txnqYg51nNY3/+A4c2Vq9a2O 67 | BWc7UyM0reIPQrhC/gmm//CEGYPeRZIFL+rPJgrgxo6KEXGr4DnLpqyJQJZLYS/M 68 | UqLyXl91fRUfZMbcuQ+7GRsOmgFJZvkc1YnoaarZjZBr8baUiSZOBYx913OgtIwB 69 | T7omyWUG3x2W0PpiNpAQebiOE+/kMzD8KhwVr978O0+aSkoS5ogSIZbNBf9aoQB4 70 | tVDeKnAZcS33EIB37/Kh3FT1ZmTa/vcEJG8QxrUCggEBAM2caCQxOozHsZmnh5V1 71 | JvgdW2pD2OFhE2N83AGxNkNdK0rULTMjHBeuoKC8TrbnXNgjEJgF2e+NEgYAuanS 72 | eYtllCyT+6sLur0nMY1JLWt3V6gMq9j+PvW5iMe6dbYATcFOLrcQStgPHB12GzEh 73 | 9A23pTc5Ssn64umpBBafEpOktJJBiFRXMVquvZfUFj+N2pLQxY6NGrkGNJiMevOP 74 | c2FLkMqMhLBAKEI8+DJHiAugtE6VGqJGNxYNXYNHRkxXVhIkhGCnPTvpwfHQmlJ8 75 | PcC7dCmjxEn3Iizub7PMfyj4LQdjo1f+PJ2pGtmn/Lhizn5q5AJ8uFhYvKIeEWCJ 76 | 4C8CggEBAMxw805RiDyyeM6cTh5wvA+5jVjYuV/V9aw7luG/8fGQc5BlIoT7oLsA 77 | qL2OA6q3zomsiCBTdrJM4Nm/DYJeYZoum1IYjtNlimTwUgfImCOdnQlY925I2jLG 78 | JC0wCzN6FfizVsz6isAg9zm029BmAFjx+Qhg3L4KiZcCxhqRKDuUpqqy55XjAAWw 79 | Zo4MWlY4FCeWcNeUklFIIUJGkmPfZduCQ3Q43vAdmG71aQ6PGPmu/si/dCVXGOZ7 80 | Fg6rT2J2+FZP6wEq9Lw8AMo/EhBYBbgxo5nT2NlQoqGzyII2eDsrtWkbYZJ9hICA 81 | 6Pr4omHuZW/QlLrRSvz6XsbULVzGyG0= 82 | -----END PRIVATE KEY----- 83 | -------------------------------------------------------------------------------- /netty-websocket-http2-example/src/main/resources/logback.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | %date{HH:mm:ss.SSS} %-10thread %-42logger %msg%n 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /netty-websocket-http2-example/src/main/resources/web/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | htt2-websocket echo example 5 | 6 | 7 | 27 |
35 |
36 |

netty-websocket-http2

37 |

rfc8441 - bootstrapping websockets with http2

38 |
open this page in http2-websocket compatible browser, e.g. Mozilla Firefox
39 |
42 |
state: disconnected
43 |
sent: press start button to run echo example
44 |
received: press start button to run echo example
45 |
counter: 0
46 |
47 | 59 |
60 | 61 |
62 | 63 | 64 | 65 | -------------------------------------------------------------------------------- /netty-websocket-http2-example/src/main/resources/web/index.js: -------------------------------------------------------------------------------- 1 | const address = 'wss://www.localhost:8099/echo'; 2 | const subprotocol = 'echo.jauntsdn.com'; 3 | 4 | const startMessage = 'start'; 5 | const stopMessage = 'stop'; 6 | 7 | const stateView = document.getElementById('state'); 8 | const sentView = document.getElementById('sent'); 9 | const receivedView = document.getElementById('received'); 10 | const counterView = document.getElementById('counter'); 11 | const pingButton = document.getElementById('ping'); 12 | 13 | let receivedCounter = 0; 14 | let sentCounter = 0; 15 | let isStarted = false; 16 | let pingHandle; 17 | pingButton.innerHTML = startMessage; 18 | 19 | const websocket = new WebSocket(address, [subprotocol]); 20 | 21 | websocket.onopen = () => { 22 | pingButton.disabled = false; 23 | stateView.style.textDecoration = 'underline'; 24 | stateView.style.textDecorationColor = 'green'; 25 | stateView.innerHTML = `state: connected ${address}`; 26 | }; 27 | 28 | websocket.onmessage = msg => { 29 | receivedCounter++; 30 | receivedView.innerHTML = `received: ${msg.data}`; 31 | counterView.innerHTML = `counter: ${receivedCounter}`; 32 | }; 33 | 34 | websocket.onerror = error => { 35 | pingButton.disabled = true; 36 | if (pingHandle) { 37 | clearInterval(pingHandle); 38 | } 39 | stateView.style.textDecoration = 'underline'; 40 | stateView.style.textDecorationColor = 'red'; 41 | stateView.innerHTML = `state: disconnected, websocket error, message=${error.message}`; 42 | }; 43 | 44 | websocket.onclose = event => { 45 | pingButton.disabled = true; 46 | if (pingHandle) { 47 | clearInterval(pingHandle); 48 | } 49 | stateView.style.textDecoration = 'underline'; 50 | stateView.style.textDecorationColor = 'red'; 51 | stateView.innerHTML = `state: disconnected, websocket close, code=${event.code}`; 52 | }; 53 | 54 | pingButton.onclick = () => { 55 | if (isStarted) { 56 | if (pingHandle) { 57 | clearInterval(pingHandle); 58 | pingHandle = null; 59 | } 60 | pingButton.innerHTML = startMessage; 61 | } else { 62 | pingHandle = setInterval(() => { 63 | const message = JSON.stringify({ content: new Date().toUTCString() }); 64 | sentView.innerHTML = `sent: ${message}`; 65 | websocket.send(message); 66 | }, 67 | 1000); 68 | pingButton.innerHTML = stopMessage; 69 | } 70 | isStarted = !isStarted; 71 | } -------------------------------------------------------------------------------- /netty-websocket-http2-perftest/build.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2020 - present Maksym Ostroverkhov. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | plugins { 18 | id "application" 19 | } 20 | 21 | description = "Netty based implementation of rfc8441 - bootstrapping websockets with http/2. Performance test project" 22 | 23 | dependencies { 24 | implementation project(":netty-websocket-http2") 25 | implementation project(":netty-websocket-http2-callbacks-codec") 26 | implementation "io.netty:netty-transport-classes-epoll" 27 | implementation "io.netty:netty-transport-classes-kqueue" 28 | implementation "org.hdrhistogram:HdrHistogram" 29 | implementation "org.slf4j:slf4j-api" 30 | 31 | runtimeOnly "io.netty:netty-tcnative-boringssl-static::${osdetector.classifier}" 32 | runtimeOnly "ch.qos.logback:logback-classic" 33 | if (osdetector.os == "linux") { 34 | runtimeOnly "io.netty:netty-transport-native-epoll::${osdetector.classifier}" 35 | } else if (osdetector.os == "osx") { 36 | runtimeOnly "io.netty:netty-transport-native-kqueue::${osdetector.classifier}" 37 | } 38 | } 39 | 40 | task runServerMessages(type: JavaExec) { 41 | classpath = sourceSets.main.runtimeClasspath 42 | mainClass = "com.jauntsdn.netty.handler.codec.http2.websocketx.perftest.messagecodec.server.Main" 43 | } 44 | 45 | task runClientMessages(type: JavaExec) { 46 | classpath = sourceSets.main.runtimeClasspath 47 | mainClass = "com.jauntsdn.netty.handler.codec.http2.websocketx.perftest.messagecodec.client.Main" 48 | } 49 | 50 | task runServerCallbacks(type: JavaExec) { 51 | classpath = sourceSets.main.runtimeClasspath 52 | mainClass = "com.jauntsdn.netty.handler.codec.http2.websocketx.perftest.callbackscodec.server.Main" 53 | } 54 | 55 | task runClientCallbacks(type: JavaExec) { 56 | classpath = sourceSets.main.runtimeClasspath 57 | mainClass = "com.jauntsdn.netty.handler.codec.http2.websocketx.perftest.callbackscodec.client.Main" 58 | } 59 | 60 | task runServerBulk(type: JavaExec) { 61 | classpath = sourceSets.main.runtimeClasspath 62 | mainClass = "com.jauntsdn.netty.handler.codec.http2.websocketx.perftest.bulkcodec.server.Main" 63 | } 64 | 65 | task runClientBulk(type: JavaExec) { 66 | classpath = sourceSets.main.runtimeClasspath 67 | mainClass = "com.jauntsdn.netty.handler.codec.http2.websocketx.perftest.bulkcodec.client.Main" 68 | } 69 | 70 | task serverMessagesScripts(type: CreateStartScripts) { 71 | mainClass = "com.jauntsdn.netty.handler.codec.http2.websocketx.perftest.messagecodec.server.Main" 72 | applicationName = "${project.name}-messages-server" 73 | classpath = startScripts.classpath 74 | outputDir = startScripts.outputDir 75 | } 76 | 77 | task clientMessagesScripts(type: CreateStartScripts) { 78 | mainClass = "com.jauntsdn.netty.handler.codec.http2.websocketx.perftest.messagecodec.client.Main" 79 | applicationName = "${project.name}-messages-client" 80 | classpath = startScripts.classpath 81 | outputDir = startScripts.outputDir 82 | } 83 | 84 | task serverCallbacksScripts(type: CreateStartScripts) { 85 | mainClass = "com.jauntsdn.netty.handler.codec.http2.websocketx.perftest.callbackscodec.server.Main" 86 | applicationName = "${project.name}-callbacks-server" 87 | classpath = startScripts.classpath 88 | outputDir = startScripts.outputDir 89 | } 90 | 91 | task clientCallbacksScripts(type: CreateStartScripts) { 92 | mainClass = "com.jauntsdn.netty.handler.codec.http2.websocketx.perftest.callbackscodec.client.Main" 93 | applicationName = "${project.name}-callbacks-client" 94 | classpath = startScripts.classpath 95 | outputDir = startScripts.outputDir 96 | } 97 | 98 | task serverBulkScripts(type: CreateStartScripts) { 99 | mainClass = "com.jauntsdn.netty.handler.codec.http2.websocketx.perftest.bulkcodec.server.Main" 100 | applicationName = "${project.name}-bulk-server" 101 | classpath = startScripts.classpath 102 | outputDir = startScripts.outputDir 103 | } 104 | 105 | task clientBulkScripts(type: CreateStartScripts) { 106 | mainClass = "com.jauntsdn.netty.handler.codec.http2.websocketx.perftest.bulkcodec.client.Main" 107 | applicationName = "${project.name}-bulk-client" 108 | classpath = startScripts.classpath 109 | outputDir = startScripts.outputDir 110 | } 111 | 112 | startScripts.dependsOn serverMessagesScripts 113 | startScripts.dependsOn clientMessagesScripts 114 | startScripts.dependsOn serverCallbacksScripts 115 | startScripts.dependsOn clientCallbacksScripts 116 | startScripts.dependsOn serverBulkScripts 117 | startScripts.dependsOn clientBulkScripts 118 | 119 | tasks.named("startScripts") { 120 | enabled = false 121 | } -------------------------------------------------------------------------------- /netty-websocket-http2-perftest/src/main/java/com/jauntsdn/netty/handler/codec/http2/websocketx/perftest/Security.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2020 - present Maksym Ostroverkhov. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.jauntsdn.netty.handler.codec.http2.websocketx.perftest; 18 | 19 | import io.netty.handler.codec.http2.Http2SecurityUtil; 20 | import io.netty.handler.ssl.ApplicationProtocolConfig; 21 | import io.netty.handler.ssl.ApplicationProtocolNames; 22 | import io.netty.handler.ssl.OpenSsl; 23 | import io.netty.handler.ssl.SslContext; 24 | import io.netty.handler.ssl.SslContextBuilder; 25 | import io.netty.handler.ssl.SslProvider; 26 | import io.netty.handler.ssl.SupportedCipherSuiteFilter; 27 | import io.netty.handler.ssl.util.InsecureTrustManagerFactory; 28 | import java.io.InputStream; 29 | import java.security.KeyStore; 30 | import javax.net.ssl.KeyManagerFactory; 31 | import javax.net.ssl.SSLException; 32 | 33 | public final class Security { 34 | 35 | public static SslContext serverSslContext(String keystoreFile, String keystorePassword) 36 | throws Exception { 37 | SslProvider sslProvider = sslProvider(); 38 | KeyStore keyStore = KeyStore.getInstance("PKCS12"); 39 | InputStream keystoreStream = Security.class.getClassLoader().getResourceAsStream(keystoreFile); 40 | char[] keystorePasswordArray = keystorePassword.toCharArray(); 41 | keyStore.load(keystoreStream, keystorePasswordArray); 42 | 43 | KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509"); 44 | keyManagerFactory.init(keyStore, keystorePasswordArray); 45 | 46 | return SslContextBuilder.forServer(keyManagerFactory) 47 | .protocols("TLSv1.3") 48 | .sslProvider(sslProvider) 49 | .applicationProtocolConfig(alpnConfig()) 50 | .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE) 51 | .build(); 52 | } 53 | 54 | public static SslContext clientLocalSslContext() throws SSLException { 55 | return SslContextBuilder.forClient() 56 | .protocols("TLSv1.3") 57 | .sslProvider(sslProvider()) 58 | .applicationProtocolConfig(alpnConfig()) 59 | .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE) 60 | .trustManager(InsecureTrustManagerFactory.INSTANCE) 61 | .build(); 62 | } 63 | 64 | private static ApplicationProtocolConfig alpnConfig() { 65 | return new ApplicationProtocolConfig( 66 | ApplicationProtocolConfig.Protocol.ALPN, 67 | ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE, 68 | ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT, 69 | ApplicationProtocolNames.HTTP_2); 70 | } 71 | 72 | private static SslProvider sslProvider() { 73 | final SslProvider sslProvider; 74 | if (OpenSsl.isAvailable()) { 75 | sslProvider = SslProvider.OPENSSL_REFCNT; 76 | } else { 77 | sslProvider = SslProvider.JDK; 78 | } 79 | return sslProvider; 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /netty-websocket-http2-perftest/src/main/java/com/jauntsdn/netty/handler/codec/http2/websocketx/perftest/Transport.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2020 - present Maksym Ostroverkhov. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.jauntsdn.netty.handler.codec.http2.websocketx.perftest; 18 | 19 | import io.netty.channel.Channel; 20 | import io.netty.channel.EventLoopGroup; 21 | import io.netty.channel.ServerChannel; 22 | import io.netty.channel.epoll.Epoll; 23 | import io.netty.channel.epoll.EpollEventLoopGroup; 24 | import io.netty.channel.epoll.EpollServerSocketChannel; 25 | import io.netty.channel.epoll.EpollSocketChannel; 26 | import io.netty.channel.kqueue.KQueue; 27 | import io.netty.channel.kqueue.KQueueEventLoopGroup; 28 | import io.netty.channel.kqueue.KQueueServerSocketChannel; 29 | import io.netty.channel.kqueue.KQueueSocketChannel; 30 | import io.netty.channel.nio.NioEventLoopGroup; 31 | import io.netty.channel.socket.nio.NioServerSocketChannel; 32 | import io.netty.channel.socket.nio.NioSocketChannel; 33 | 34 | public class Transport { 35 | static final boolean isEpollAvailable; 36 | static final boolean isKqueueAvailable; 37 | 38 | static { 39 | boolean available; 40 | try { 41 | Class.forName("io.netty.channel.epoll.Epoll"); 42 | available = Epoll.isAvailable(); 43 | } catch (ClassNotFoundException e) { 44 | available = false; 45 | } 46 | isEpollAvailable = available; 47 | 48 | try { 49 | Class.forName("io.netty.channel.kqueue.KQueue"); 50 | available = KQueue.isAvailable(); 51 | } catch (ClassNotFoundException e) { 52 | available = false; 53 | } 54 | isKqueueAvailable = available; 55 | } 56 | 57 | private final String type; 58 | private final Class clientChannel; 59 | private final Class serverChannel; 60 | private final EventLoopGroup eventLoopGroup; 61 | 62 | public static boolean isEpollAvailable() { 63 | return isEpollAvailable; 64 | } 65 | 66 | public static boolean isKqueueAvailable() { 67 | return isKqueueAvailable; 68 | } 69 | 70 | public static Transport get(boolean isNative) { 71 | int threadCount = Runtime.getRuntime().availableProcessors() * 2; 72 | if (isNative) { 73 | if (isEpollAvailable()) { 74 | return new Transport( 75 | "epoll", 76 | EpollSocketChannel.class, 77 | EpollServerSocketChannel.class, 78 | new EpollEventLoopGroup(threadCount)); 79 | } 80 | if (isKqueueAvailable()) { 81 | return new Transport( 82 | "kqueue", 83 | KQueueSocketChannel.class, 84 | KQueueServerSocketChannel.class, 85 | new KQueueEventLoopGroup(threadCount)); 86 | } 87 | } 88 | return new Transport( 89 | "nio", 90 | NioSocketChannel.class, 91 | NioServerSocketChannel.class, 92 | new NioEventLoopGroup(threadCount)); 93 | } 94 | 95 | Transport( 96 | String type, 97 | Class clientChannel, 98 | Class serverChannel, 99 | EventLoopGroup eventLoopGroup) { 100 | this.type = type; 101 | this.clientChannel = clientChannel; 102 | this.serverChannel = serverChannel; 103 | this.eventLoopGroup = eventLoopGroup; 104 | } 105 | 106 | public Class clientChannel() { 107 | return clientChannel; 108 | } 109 | 110 | public Class serverChannel() { 111 | return serverChannel; 112 | } 113 | 114 | public EventLoopGroup eventLoopGroup() { 115 | return eventLoopGroup; 116 | } 117 | 118 | public String type() { 119 | return type; 120 | } 121 | 122 | @Override 123 | public String toString() { 124 | return "Transport{" + "type='" + type + '\'' + '}'; 125 | } 126 | } 127 | -------------------------------------------------------------------------------- /netty-websocket-http2-perftest/src/main/java/com/jauntsdn/netty/handler/codec/http2/websocketx/perftest/callbackscodec/server/Main.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 - present Maksym Ostroverkhov. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.jauntsdn.netty.handler.codec.http2.websocketx.perftest.callbackscodec.server; 18 | 19 | import com.jauntsdn.netty.handler.codec.http.websocketx.WebSocketCallbacksHandler; 20 | import com.jauntsdn.netty.handler.codec.http.websocketx.WebSocketFrameFactory; 21 | import com.jauntsdn.netty.handler.codec.http.websocketx.WebSocketFrameListener; 22 | import com.jauntsdn.netty.handler.codec.http.websocketx.WebSocketProtocol; 23 | import com.jauntsdn.netty.handler.codec.http2.websocketx.Http2WebSocketEvent; 24 | import com.jauntsdn.netty.handler.codec.http2.websocketx.Http2WebSocketServerBuilder; 25 | import com.jauntsdn.netty.handler.codec.http2.websocketx.Http2WebSocketServerHandler; 26 | import com.jauntsdn.netty.handler.codec.http2.websocketx.WebSocketCallbacksCodec; 27 | import com.jauntsdn.netty.handler.codec.http2.websocketx.perftest.Security; 28 | import com.jauntsdn.netty.handler.codec.http2.websocketx.perftest.Transport; 29 | import io.netty.bootstrap.ServerBootstrap; 30 | import io.netty.buffer.ByteBuf; 31 | import io.netty.channel.Channel; 32 | import io.netty.channel.ChannelHandler.Sharable; 33 | import io.netty.channel.ChannelHandlerContext; 34 | import io.netty.channel.ChannelInboundHandlerAdapter; 35 | import io.netty.channel.ChannelInitializer; 36 | import io.netty.channel.epoll.Epoll; 37 | import io.netty.channel.kqueue.KQueue; 38 | import io.netty.channel.socket.SocketChannel; 39 | import io.netty.handler.codec.http.websocketx.WebSocketDecoderConfig; 40 | import io.netty.handler.codec.http.websocketx.WebSocketHandshakeException; 41 | import io.netty.handler.codec.http2.DefaultHttp2RemoteFlowController; 42 | import io.netty.handler.codec.http2.Http2Connection; 43 | import io.netty.handler.codec.http2.Http2FrameCodec; 44 | import io.netty.handler.codec.http2.Http2FrameCodecBuilder; 45 | import io.netty.handler.codec.http2.UniformStreamByteDistributor; 46 | import io.netty.handler.ssl.OpenSsl; 47 | import io.netty.handler.ssl.SslContext; 48 | import io.netty.handler.ssl.SslHandler; 49 | import java.io.IOException; 50 | import org.slf4j.Logger; 51 | import org.slf4j.LoggerFactory; 52 | 53 | public class Main { 54 | private static final Logger logger = LoggerFactory.getLogger(Main.class); 55 | 56 | public static void main(String[] args) throws Exception { 57 | 58 | String host = System.getProperty("HOST", "localhost"); 59 | int port = Integer.parseInt(System.getProperty("PORT", "8088")); 60 | String keyStoreFile = System.getProperty("KEYSTORE", "localhost.p12"); 61 | String keyStorePassword = System.getProperty("KEYSTORE_PASS", "localhost"); 62 | boolean isNativeTransport = 63 | Boolean.parseBoolean(System.getProperty("NATIVE_TRANSPORT", "true")); 64 | int flowControlWindowSize = 65 | Integer.parseInt(System.getProperty("FLOW_CONTROL_WINDOW", "100000")); 66 | boolean isOpensslAvailable = OpenSsl.isAvailable(); 67 | boolean isEpollAvailable = Epoll.isAvailable(); 68 | boolean isKqueueAvailable = KQueue.isAvailable(); 69 | 70 | logger.info("\n==> http2 websocket callbacks codec perf test server\n"); 71 | logger.info("\n==> bind address: {}:{}", host, port); 72 | logger.info("\n==> flow control window size: {}", flowControlWindowSize); 73 | logger.info("\n==> native transport: {}", isNativeTransport); 74 | logger.info("\n==> epoll available: {}", isEpollAvailable); 75 | logger.info("\n==> kqueue available: {}", isKqueueAvailable); 76 | logger.info("\n==> openssl available: {}", isOpensslAvailable); 77 | 78 | Transport transport = Transport.get(isNativeTransport); 79 | 80 | SslContext sslContext = Security.serverSslContext(keyStoreFile, keyStorePassword); 81 | 82 | ServerBootstrap bootstrap = new ServerBootstrap(); 83 | Channel server = 84 | bootstrap 85 | .group(transport.eventLoopGroup()) 86 | .channel(transport.serverChannel()) 87 | .childHandler(new ConnectionAcceptor(flowControlWindowSize, sslContext)) 88 | .bind(host, port) 89 | .sync() 90 | .channel(); 91 | logger.info("\n==> Server is listening on {}:{}", host, port); 92 | server.closeFuture().sync(); 93 | } 94 | 95 | private static class ConnectionAcceptor extends ChannelInitializer { 96 | private final int flowControlWindowSize; 97 | private final SslContext sslContext; 98 | 99 | ConnectionAcceptor(int flowControlWindowSize, SslContext sslContext) { 100 | this.flowControlWindowSize = flowControlWindowSize; 101 | this.sslContext = sslContext; 102 | } 103 | 104 | @Override 105 | protected void initChannel(SocketChannel ch) { 106 | SslHandler sslHandler = sslContext.newHandler(ch.alloc()); 107 | 108 | Http2FrameCodecBuilder http2Builder = 109 | Http2WebSocketServerBuilder.configureHttp2Server(Http2FrameCodecBuilder.forServer()); 110 | http2Builder.initialSettings().initialWindowSize(flowControlWindowSize); 111 | Http2FrameCodec http2FrameCodec = http2Builder.build(); 112 | Http2Connection connection = http2FrameCodec.connection(); 113 | connection 114 | .remote() 115 | .flowController( 116 | new DefaultHttp2RemoteFlowController( 117 | connection, new UniformStreamByteDistributor(connection))); 118 | 119 | WebSocketsCallbacksHandler webSocketsCallbacksHandler = 120 | new WebSocketsCallbacksHandler(new EchoWebSocketHandler()); 121 | 122 | WebSocketDecoderConfig decoderConfig = 123 | WebSocketDecoderConfig.newBuilder() 124 | .maxFramePayloadLength(65_535) 125 | .expectMaskedFrames(false) 126 | .allowMaskMismatch(true) 127 | .allowExtensions(false) 128 | .withUTF8Validator(false) 129 | .build(); 130 | 131 | Http2WebSocketServerHandler http2webSocketHandler = 132 | Http2WebSocketServerBuilder.create() 133 | .codec(WebSocketCallbacksCodec.instance()) 134 | .assumeSingleWebSocketPerConnection(true) 135 | .compression(false) 136 | .decoderConfig(decoderConfig) 137 | .acceptor( 138 | (ctx, path, subprotocols, request, response) -> { 139 | if ("/echo".equals(path) && subprotocols.isEmpty()) { 140 | return ctx.executor().newSucceededFuture(webSocketsCallbacksHandler); 141 | } 142 | return ctx.executor() 143 | .newFailedFuture( 144 | new WebSocketHandshakeException( 145 | String.format( 146 | "path not found: %s, subprotocols: %s", path, subprotocols))); 147 | }) 148 | .build(); 149 | 150 | ExceptionHandler exceptionHandler = new ExceptionHandler(); 151 | 152 | ch.pipeline().addLast(sslHandler, http2FrameCodec, http2webSocketHandler, exceptionHandler); 153 | } 154 | } 155 | 156 | private static class ExceptionHandler extends ChannelInboundHandlerAdapter { 157 | @Override 158 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { 159 | if (cause instanceof IOException) { 160 | return; 161 | } 162 | logger.error("Unexpected connection error", cause); 163 | ctx.close(); 164 | } 165 | } 166 | 167 | private static class EchoWebSocketHandler 168 | implements WebSocketCallbacksHandler, WebSocketFrameListener { 169 | private WebSocketFrameFactory webSocketFrameFactory; 170 | 171 | @Override 172 | public WebSocketFrameListener exchange( 173 | ChannelHandlerContext ctx, WebSocketFrameFactory webSocketFrameFactory) { 174 | this.webSocketFrameFactory = webSocketFrameFactory; 175 | return this; 176 | } 177 | 178 | @Override 179 | public void onChannelRead( 180 | ChannelHandlerContext ctx, boolean finalFragment, int rsv, int opcode, ByteBuf payload) { 181 | if (opcode != WebSocketProtocol.OPCODE_BINARY) { 182 | payload.release(); 183 | return; 184 | } 185 | WebSocketFrameFactory frameFactory = webSocketFrameFactory; 186 | ByteBuf frame = frameFactory.createBinaryFrame(ctx.alloc(), payload.readableBytes()); 187 | frame.writeBytes(payload); 188 | frameFactory.mask(frame); 189 | payload.release(); 190 | ctx.write(frame); 191 | } 192 | 193 | @Override 194 | public void onChannelReadComplete(ChannelHandlerContext ctx) { 195 | ctx.flush(); 196 | } 197 | 198 | @Override 199 | public void onExceptionCaught(ChannelHandlerContext ctx, Throwable cause) { 200 | if (cause instanceof IOException) { 201 | return; 202 | } 203 | logger.info("Unexpected websocket error", cause); 204 | ctx.close(); 205 | } 206 | } 207 | 208 | @Sharable 209 | private static class WebSocketsCallbacksHandler extends ChannelInboundHandlerAdapter { 210 | final WebSocketCallbacksHandler webSocketHandler; 211 | 212 | WebSocketsCallbacksHandler(WebSocketCallbacksHandler webSocketHandler) { 213 | this.webSocketHandler = webSocketHandler; 214 | } 215 | 216 | @Override 217 | public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { 218 | if (evt instanceof Http2WebSocketEvent.Http2WebSocketHandshakeSuccessEvent) { 219 | 220 | WebSocketCallbacksHandler.exchange(ctx, webSocketHandler); 221 | ctx.pipeline().remove(this); 222 | } 223 | super.userEventTriggered(ctx, evt); 224 | } 225 | 226 | @Override 227 | public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { 228 | logger.info("Received {} message on callbacks handler", msg); 229 | super.channelRead(ctx, msg); 230 | } 231 | 232 | @Override 233 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { 234 | if (cause instanceof IOException) { 235 | return; 236 | } 237 | logger.info("Unexpected websocket error", cause); 238 | ctx.close(); 239 | } 240 | } 241 | } 242 | -------------------------------------------------------------------------------- /netty-websocket-http2-perftest/src/main/java/com/jauntsdn/netty/handler/codec/http2/websocketx/perftest/messagecodec/server/Main.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2020 - present Maksym Ostroverkhov. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.jauntsdn.netty.handler.codec.http2.websocketx.perftest.messagecodec.server; 18 | 19 | import com.jauntsdn.netty.handler.codec.http2.websocketx.Http2WebSocketServerBuilder; 20 | import com.jauntsdn.netty.handler.codec.http2.websocketx.Http2WebSocketServerHandler; 21 | import com.jauntsdn.netty.handler.codec.http2.websocketx.perftest.Security; 22 | import com.jauntsdn.netty.handler.codec.http2.websocketx.perftest.Transport; 23 | import io.netty.bootstrap.ServerBootstrap; 24 | import io.netty.channel.Channel; 25 | import io.netty.channel.ChannelHandler.Sharable; 26 | import io.netty.channel.ChannelHandlerContext; 27 | import io.netty.channel.ChannelInboundHandlerAdapter; 28 | import io.netty.channel.ChannelInitializer; 29 | import io.netty.channel.epoll.Epoll; 30 | import io.netty.channel.kqueue.KQueue; 31 | import io.netty.channel.socket.SocketChannel; 32 | import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame; 33 | import io.netty.handler.codec.http.websocketx.WebSocketHandshakeException; 34 | import io.netty.handler.codec.http2.DefaultHttp2RemoteFlowController; 35 | import io.netty.handler.codec.http2.Http2Connection; 36 | import io.netty.handler.codec.http2.Http2FrameCodec; 37 | import io.netty.handler.codec.http2.Http2FrameCodecBuilder; 38 | import io.netty.handler.codec.http2.UniformStreamByteDistributor; 39 | import io.netty.handler.ssl.OpenSsl; 40 | import io.netty.handler.ssl.SslContext; 41 | import io.netty.handler.ssl.SslHandler; 42 | import io.netty.util.ReferenceCountUtil; 43 | import java.io.IOException; 44 | import org.slf4j.Logger; 45 | import org.slf4j.LoggerFactory; 46 | 47 | public class Main { 48 | private static final Logger logger = LoggerFactory.getLogger(Main.class); 49 | 50 | public static void main(String[] args) throws Exception { 51 | 52 | String host = System.getProperty("HOST", "localhost"); 53 | int port = Integer.parseInt(System.getProperty("PORT", "8088")); 54 | String keyStoreFile = System.getProperty("KEYSTORE", "localhost.p12"); 55 | String keyStorePassword = System.getProperty("KEYSTORE_PASS", "localhost"); 56 | boolean isNativeTransport = 57 | Boolean.parseBoolean(System.getProperty("NATIVE_TRANSPORT", "true")); 58 | int flowControlWindowSize = 59 | Integer.parseInt(System.getProperty("FLOW_CONTROL_WINDOW", "100000")); 60 | boolean isOpensslAvailable = OpenSsl.isAvailable(); 61 | boolean isEpollAvailable = Epoll.isAvailable(); 62 | boolean isKqueueAvailable = KQueue.isAvailable(); 63 | 64 | logger.info("\n==> http2 websocket load test server\n"); 65 | logger.info("\n==> bind address: {}:{}", host, port); 66 | logger.info("\n==> flow control window size: {}", flowControlWindowSize); 67 | logger.info("\n==> native transport: {}", isNativeTransport); 68 | logger.info("\n==> epoll available: {}", isEpollAvailable); 69 | logger.info("\n==> kqueue available: {}", isKqueueAvailable); 70 | logger.info("\n==> openssl available: {}", isOpensslAvailable); 71 | 72 | Transport transport = Transport.get(isNativeTransport); 73 | 74 | SslContext sslContext = Security.serverSslContext(keyStoreFile, keyStorePassword); 75 | 76 | ServerBootstrap bootstrap = new ServerBootstrap(); 77 | Channel server = 78 | bootstrap 79 | .group(transport.eventLoopGroup()) 80 | .channel(transport.serverChannel()) 81 | .childHandler(new ConnectionAcceptor(flowControlWindowSize, sslContext)) 82 | .bind(host, port) 83 | .sync() 84 | .channel(); 85 | logger.info("\n==> Server is listening on {}:{}", host, port); 86 | server.closeFuture().sync(); 87 | } 88 | 89 | private static class ConnectionAcceptor extends ChannelInitializer { 90 | private final int flowControlWindowSize; 91 | private final SslContext sslContext; 92 | 93 | ConnectionAcceptor(int flowControlWindowSize, SslContext sslContext) { 94 | this.flowControlWindowSize = flowControlWindowSize; 95 | this.sslContext = sslContext; 96 | } 97 | 98 | @Override 99 | protected void initChannel(SocketChannel ch) { 100 | SslHandler sslHandler = sslContext.newHandler(ch.alloc()); 101 | 102 | Http2FrameCodecBuilder http2Builder = 103 | Http2WebSocketServerBuilder.configureHttp2Server(Http2FrameCodecBuilder.forServer()); 104 | http2Builder.initialSettings().initialWindowSize(flowControlWindowSize); 105 | Http2FrameCodec http2FrameCodec = http2Builder.build(); 106 | Http2Connection connection = http2FrameCodec.connection(); 107 | connection 108 | .remote() 109 | .flowController( 110 | new DefaultHttp2RemoteFlowController( 111 | connection, new UniformStreamByteDistributor(connection))); 112 | 113 | EchoWebSocketHandler echoWebSocketHandler = new EchoWebSocketHandler(); 114 | Http2WebSocketServerHandler http2webSocketHandler = 115 | Http2WebSocketServerBuilder.create() 116 | .assumeSingleWebSocketPerConnection(true) 117 | .acceptor( 118 | (ctx, path, subprotocols, request, response) -> { 119 | if ("/echo".equals(path) && subprotocols.isEmpty()) { 120 | return ctx.executor().newSucceededFuture(echoWebSocketHandler); 121 | } 122 | return ctx.executor() 123 | .newFailedFuture( 124 | new WebSocketHandshakeException( 125 | String.format( 126 | "path not found: %s, subprotocols: %s", path, subprotocols))); 127 | }) 128 | .build(); 129 | 130 | ExceptionHandler exceptionHandler = new ExceptionHandler(); 131 | 132 | ch.pipeline().addLast(sslHandler, http2FrameCodec, http2webSocketHandler, exceptionHandler); 133 | } 134 | } 135 | 136 | private static class ExceptionHandler extends ChannelInboundHandlerAdapter { 137 | @Override 138 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { 139 | if (cause instanceof IOException) { 140 | return; 141 | } 142 | logger.error("Unexpected connection error", cause); 143 | ctx.close(); 144 | } 145 | } 146 | 147 | @Sharable 148 | private static class EchoWebSocketHandler extends ChannelInboundHandlerAdapter { 149 | 150 | @Override 151 | public void channelRead(ChannelHandlerContext ctx, Object msg) { 152 | if (!(msg instanceof BinaryWebSocketFrame)) { 153 | ReferenceCountUtil.safeRelease(msg); 154 | return; 155 | } 156 | ctx.write(msg); 157 | } 158 | 159 | @Override 160 | public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { 161 | ctx.flush(); 162 | super.channelReadComplete(ctx); 163 | } 164 | 165 | @Override 166 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { 167 | if (cause instanceof IOException) { 168 | return; 169 | } 170 | logger.info("Unexpected websocket error", cause); 171 | ctx.close(); 172 | } 173 | } 174 | } 175 | -------------------------------------------------------------------------------- /netty-websocket-http2-perftest/src/main/resources/localhost.p12: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jauntsdn/netty-websocket-http2/175e23f9f177d410f670748c453f600c2a3d311e/netty-websocket-http2-perftest/src/main/resources/localhost.p12 -------------------------------------------------------------------------------- /netty-websocket-http2-perftest/src/main/resources/logback.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | %date{HH:mm:ss.SSS} %-10thread %-42logger %msg%n 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /netty-websocket-http2/build.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2020 - present Maksym Ostroverkhov. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | plugins { 18 | id "java-library" 19 | id "maven-publish" 20 | id "signing" 21 | } 22 | 23 | description = "Netty based implementation of rfc8441 - bootstrapping websockets with http/2" 24 | 25 | dependencies { 26 | api "io.netty:netty-codec-http2" 27 | implementation "org.slf4j:slf4j-api" 28 | compileOnly "com.google.code.findbugs:jsr305" 29 | 30 | testImplementation "org.assertj:assertj-core" 31 | testImplementation "org.junit.jupiter:junit-jupiter-api" 32 | testImplementation "org.junit.jupiter:junit-jupiter-params" 33 | testImplementation project(":netty-websocket-http2-callbacks-codec") 34 | 35 | testRuntimeOnly "org.junit.jupiter:junit-jupiter-engine" 36 | testRuntimeOnly "ch.qos.logback:logback-classic" 37 | testRuntimeOnly "io.netty:netty-tcnative-classes" 38 | testRuntimeOnly "io.netty:netty-tcnative-boringssl-static::${osdetector.classifier}" 39 | } 40 | 41 | dependencyLocking { 42 | lockAllConfigurations() 43 | } 44 | 45 | tasks.named("jar") { 46 | manifest { 47 | attributes("Automatic-Module-Name": "com.jauntsdn.netty.websocket.http2") 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /netty-websocket-http2/gradle.lockfile: -------------------------------------------------------------------------------- 1 | # This is a Gradle generated file for dependency locking. 2 | # Manual edits can break the build and are not advised. 3 | # This file is expected to be part of source control. 4 | ch.qos.logback:logback-classic:1.2.13=testRuntimeClasspath 5 | ch.qos.logback:logback-core:1.2.13=testRuntimeClasspath 6 | com.google.code.findbugs:jsr305:3.0.2=compileClasspath,googleJavaFormat1.6 7 | com.google.errorprone:error_prone_annotations:2.0.18=googleJavaFormat1.6 8 | com.google.errorprone:javac-shaded:9+181-r4173-1=googleJavaFormat1.6 9 | com.google.googlejavaformat:google-java-format:1.6=googleJavaFormat1.6 10 | com.google.guava:guava:22.0=googleJavaFormat1.6 11 | com.google.j2objc:j2objc-annotations:1.1=googleJavaFormat1.6 12 | com.jauntsdn.netty:netty-websocket-http1:1.3.0=testCompileClasspath,testRuntimeClasspath 13 | io.netty:netty-buffer:4.1.119.Final=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath 14 | io.netty:netty-codec-http2:4.1.119.Final=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath 15 | io.netty:netty-codec-http:4.1.119.Final=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath 16 | io.netty:netty-codec:4.1.119.Final=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath 17 | io.netty:netty-common:4.1.119.Final=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath 18 | io.netty:netty-handler:4.1.119.Final=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath 19 | io.netty:netty-resolver:4.1.119.Final=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath 20 | io.netty:netty-tcnative-boringssl-static:2.0.70.Final=testRuntimeClasspath 21 | io.netty:netty-tcnative-classes:2.0.70.Final=testRuntimeClasspath 22 | io.netty:netty-transport-native-unix-common:4.1.119.Final=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath 23 | io.netty:netty-transport:4.1.119.Final=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath 24 | net.bytebuddy:byte-buddy:1.15.11=testCompileClasspath,testRuntimeClasspath 25 | org.apiguardian:apiguardian-api:1.1.2=testCompileClasspath 26 | org.assertj:assertj-core:3.27.3=testCompileClasspath,testRuntimeClasspath 27 | org.codehaus.mojo:animal-sniffer-annotations:1.14=googleJavaFormat1.6 28 | org.junit.jupiter:junit-jupiter-api:5.11.4=testCompileClasspath,testRuntimeClasspath 29 | org.junit.jupiter:junit-jupiter-engine:5.11.4=testRuntimeClasspath 30 | org.junit.jupiter:junit-jupiter-params:5.11.4=testCompileClasspath,testRuntimeClasspath 31 | org.junit.platform:junit-platform-commons:1.11.4=testCompileClasspath,testRuntimeClasspath 32 | org.junit.platform:junit-platform-engine:1.11.4=testRuntimeClasspath 33 | org.junit:junit-bom:5.11.4=testCompileClasspath,testRuntimeClasspath 34 | org.opentest4j:opentest4j:1.3.0=testCompileClasspath,testRuntimeClasspath 35 | org.slf4j:slf4j-api:1.7.36=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath 36 | empty=annotationProcessor,testAnnotationProcessor 37 | -------------------------------------------------------------------------------- /netty-websocket-http2/src/main/java/com/jauntsdn/netty/handler/codec/http2/websocketx/Http1WebSocketCodec.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 - present Maksym Ostroverkhov. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.jauntsdn.netty.handler.codec.http2.websocketx; 18 | 19 | import io.netty.handler.codec.http.websocketx.WebSocket13FrameDecoder; 20 | import io.netty.handler.codec.http.websocketx.WebSocket13FrameEncoder; 21 | import io.netty.handler.codec.http.websocketx.WebSocketDecoderConfig; 22 | import io.netty.handler.codec.http.websocketx.WebSocketFrameDecoder; 23 | import io.netty.handler.codec.http.websocketx.WebSocketFrameEncoder; 24 | 25 | public interface Http1WebSocketCodec { 26 | 27 | WebSocketFrameEncoder encoder(boolean maskPayload); 28 | 29 | WebSocketFrameDecoder decoder(WebSocketDecoderConfig config); 30 | 31 | default WebSocketFrameDecoder decoder(boolean maskPayload, WebSocketDecoderConfig config) { 32 | return null; 33 | } 34 | 35 | void validate(boolean maskPayload, WebSocketDecoderConfig config); 36 | 37 | Http1WebSocketCodec DEFAULT = 38 | new Http1WebSocketCodec() { 39 | @Override 40 | public WebSocketFrameEncoder encoder(boolean maskPayload) { 41 | return new WebSocket13FrameEncoder(maskPayload); 42 | } 43 | 44 | @Override 45 | public WebSocketFrameDecoder decoder(WebSocketDecoderConfig config) { 46 | return new WebSocket13FrameDecoder(config); 47 | } 48 | 49 | @Override 50 | public void validate(boolean maskPayload, WebSocketDecoderConfig config) {} 51 | }; 52 | } 53 | -------------------------------------------------------------------------------- /netty-websocket-http2/src/main/java/com/jauntsdn/netty/handler/codec/http2/websocketx/Http2WebSocket.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2020 - present Maksym Ostroverkhov. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.jauntsdn.netty.handler.codec.http2.websocketx; 18 | 19 | import io.netty.buffer.ByteBuf; 20 | import io.netty.channel.ChannelHandlerContext; 21 | import io.netty.handler.codec.http2.Http2Flags; 22 | import io.netty.handler.codec.http2.Http2FrameListener; 23 | import io.netty.handler.codec.http2.Http2Headers; 24 | import io.netty.handler.codec.http2.Http2Settings; 25 | 26 | interface Http2WebSocket extends Http2FrameListener { 27 | 28 | /*get rid of checked throws Http2Exception */ 29 | @Override 30 | void onGoAwayRead(ChannelHandlerContext ctx, int lastStreamId, long errorCode, ByteBuf debugData); 31 | 32 | void trySetWritable(); 33 | 34 | void fireExceptionCaught(Throwable t); 35 | 36 | void streamClosed(); 37 | 38 | void closeForcibly(); 39 | 40 | Http2WebSocket CLOSED = 41 | new Http2WebSocket() { 42 | @Override 43 | public void onGoAwayRead( 44 | ChannelHandlerContext ctx, int lastStreamId, long errorCode, ByteBuf debugData) {} 45 | 46 | @Override 47 | public void onWindowUpdateRead( 48 | ChannelHandlerContext ctx, int streamId, int windowSizeIncrement) {} 49 | 50 | @Override 51 | public void streamClosed() {} 52 | 53 | @Override 54 | public void trySetWritable() {} 55 | 56 | @Override 57 | public void fireExceptionCaught(Throwable t) {} 58 | 59 | @Override 60 | public void closeForcibly() {} 61 | 62 | @Override 63 | public int onDataRead( 64 | ChannelHandlerContext ctx, 65 | int streamId, 66 | ByteBuf data, 67 | int padding, 68 | boolean endOfStream) { 69 | int processed = data.readableBytes() + padding; 70 | data.release(); 71 | return processed; 72 | } 73 | 74 | @Override 75 | public void onUnknownFrame( 76 | ChannelHandlerContext ctx, 77 | byte frameType, 78 | int streamId, 79 | Http2Flags flags, 80 | ByteBuf payload) { 81 | payload.release(); 82 | } 83 | 84 | @Override 85 | public void onHeadersRead( 86 | ChannelHandlerContext ctx, 87 | int streamId, 88 | Http2Headers headers, 89 | int padding, 90 | boolean endOfStream) {} 91 | 92 | @Override 93 | public void onHeadersRead( 94 | ChannelHandlerContext ctx, 95 | int streamId, 96 | Http2Headers headers, 97 | int streamDependency, 98 | short weight, 99 | boolean exclusive, 100 | int padding, 101 | boolean endOfStream) {} 102 | 103 | @Override 104 | public void onPriorityRead( 105 | ChannelHandlerContext ctx, 106 | int streamId, 107 | int streamDependency, 108 | short weight, 109 | boolean exclusive) {} 110 | 111 | @Override 112 | public void onRstStreamRead(ChannelHandlerContext ctx, int streamId, long errorCode) {} 113 | 114 | @Override 115 | public void onSettingsAckRead(ChannelHandlerContext ctx) {} 116 | 117 | @Override 118 | public void onSettingsRead(ChannelHandlerContext ctx, Http2Settings settings) {} 119 | 120 | @Override 121 | public void onPingRead(ChannelHandlerContext ctx, long data) {} 122 | 123 | @Override 124 | public void onPingAckRead(ChannelHandlerContext ctx, long data) {} 125 | 126 | @Override 127 | public void onPushPromiseRead( 128 | ChannelHandlerContext ctx, 129 | int streamId, 130 | int promisedStreamId, 131 | Http2Headers headers, 132 | int padding) {} 133 | }; 134 | } 135 | -------------------------------------------------------------------------------- /netty-websocket-http2/src/main/java/com/jauntsdn/netty/handler/codec/http2/websocketx/Http2WebSocketAcceptor.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2020 - present Maksym Ostroverkhov. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.jauntsdn.netty.handler.codec.http2.websocketx; 18 | 19 | import io.netty.channel.ChannelHandler; 20 | import io.netty.channel.ChannelHandlerContext; 21 | import io.netty.handler.codec.http2.Http2Headers; 22 | import io.netty.util.concurrent.Future; 23 | import java.util.List; 24 | import java.util.Objects; 25 | 26 | /** Accepts valid websocket-over-http2 request, optionally modifies request and response headers */ 27 | public interface Http2WebSocketAcceptor { 28 | 29 | /** 30 | * @param ctx ChannelHandlerContext of connection channel. Intended for creating acceptor result 31 | * with context.executor().newFailedFuture(Throwable), 32 | * context.executor().newSucceededFuture(ChannelHandler) 33 | * @param path websocket path 34 | * @param subprotocols requested websocket subprotocols. Accepted subprotocol must be set on 35 | * response headers, e.g. with {@link Subprotocol#accept(String, Http2Headers)} 36 | * @param request request headers 37 | * @param response response headers 38 | * @return Succeeded future for accepted request, failed for rejected request. It is an error to 39 | * return non completed future 40 | */ 41 | Future accept( 42 | ChannelHandlerContext ctx, 43 | String path, 44 | List subprotocols, 45 | Http2Headers request, 46 | Http2Headers response); 47 | 48 | final class Subprotocol { 49 | private Subprotocol() {} 50 | 51 | public static void accept(String subprotocol, Http2Headers response) { 52 | Objects.requireNonNull(subprotocol, "subprotocol"); 53 | Objects.requireNonNull(response, "response"); 54 | if (subprotocol.isEmpty()) { 55 | return; 56 | } 57 | response.set(Http2WebSocketProtocol.HEADER_WEBSOCKET_SUBPROTOCOL_NAME, subprotocol); 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /netty-websocket-http2/src/main/java/com/jauntsdn/netty/handler/codec/http2/websocketx/Http2WebSocketChannelFutureListener.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2020 - present Maksym Ostroverkhov. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.jauntsdn.netty.handler.codec.http2.websocketx; 18 | 19 | import io.netty.channel.Channel; 20 | import io.netty.channel.ChannelFuture; 21 | import io.netty.util.concurrent.GenericFutureListener; 22 | 23 | /** 24 | * ChannelFuture listener that gracefully closes websocket by sending empty DATA frame with 25 | * END_STREAM flag set. 26 | */ 27 | public final class Http2WebSocketChannelFutureListener 28 | implements GenericFutureListener { 29 | public static final Http2WebSocketChannelFutureListener CLOSE = 30 | new Http2WebSocketChannelFutureListener(); 31 | 32 | private Http2WebSocketChannelFutureListener() {} 33 | 34 | @Override 35 | public void operationComplete(ChannelFuture future) { 36 | Channel channel = future.channel(); 37 | Throwable cause = future.cause(); 38 | if (cause != null) { 39 | Http2WebSocketEvent.fireFrameWriteError(channel, cause); 40 | } 41 | channel 42 | .pipeline() 43 | .fireUserEventTriggered(Http2WebSocketEvent.Http2WebSocketLocalCloseEvent.INSTANCE); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /netty-websocket-http2/src/main/java/com/jauntsdn/netty/handler/codec/http2/websocketx/Http2WebSocketClientBuilder.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2020 - present Maksym Ostroverkhov. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.jauntsdn.netty.handler.codec.http2.websocketx; 18 | 19 | import io.netty.handler.codec.http.websocketx.WebSocketDecoderConfig; 20 | import io.netty.handler.codec.http.websocketx.extensions.compression.PerMessageDeflateClientExtensionHandshaker; 21 | import java.util.Objects; 22 | 23 | /** Builder for {@link Http2WebSocketClientHandler} */ 24 | public final class Http2WebSocketClientBuilder { 25 | private static final short DEFAULT_STREAM_WEIGHT = 16; 26 | 27 | private Http1WebSocketCodec webSocketCodec = Http1WebSocketCodec.DEFAULT; 28 | private WebSocketDecoderConfig webSocketDecoderConfig; 29 | private PerMessageDeflateClientExtensionHandshaker perMessageDeflateClientExtensionHandshaker; 30 | private long handshakeTimeoutMillis = 15_000; 31 | private short streamWeight; 32 | private long closedWebSocketRemoveTimeoutMillis = 30_000; 33 | private boolean isSingleWebSocketPerConnection; 34 | private boolean isMaskPayload = true; 35 | private boolean isNomaskingExtension; 36 | 37 | Http2WebSocketClientBuilder() {} 38 | 39 | /** @return new {@link Http2WebSocketClientBuilder} instance */ 40 | public static Http2WebSocketClientBuilder create() { 41 | return new Http2WebSocketClientBuilder(); 42 | } 43 | 44 | /** 45 | * @param webSocketCodec factory for websocket1 encoder/decoder used for protocol processing. Must 46 | * be non-null 47 | * @return this {@link Http2WebSocketClientBuilder} instance 48 | */ 49 | public Http2WebSocketClientBuilder codec(Http1WebSocketCodec webSocketCodec) { 50 | this.webSocketCodec = Objects.requireNonNull(webSocketCodec, "webSocketCodec"); 51 | return this; 52 | } 53 | 54 | /** 55 | * @param webSocketDecoderConfig websocket decoder configuration. Must be non-null 56 | * @return this {@link Http2WebSocketClientBuilder} instance 57 | */ 58 | public Http2WebSocketClientBuilder decoderConfig(WebSocketDecoderConfig webSocketDecoderConfig) { 59 | this.webSocketDecoderConfig = 60 | Objects.requireNonNull(webSocketDecoderConfig, "webSocketDecoderConfig"); 61 | return this; 62 | } 63 | 64 | /** 65 | * @param maskPayload enables frame payload masking 66 | * @return this {@link Http2WebSocketClientBuilder} instance 67 | */ 68 | public Http2WebSocketClientBuilder maskPayload(boolean maskPayload) { 69 | this.isMaskPayload = maskPayload; 70 | return this; 71 | } 72 | 73 | /** 74 | * @param handshakeTimeoutMillis websocket handshake timeout. Must be positive 75 | * @return this {@link Http2WebSocketClientBuilder} instance 76 | */ 77 | public Http2WebSocketClientBuilder handshakeTimeoutMillis(long handshakeTimeoutMillis) { 78 | this.handshakeTimeoutMillis = 79 | Http2WebSocketProtocol.requirePositive(handshakeTimeoutMillis, "handshakeTimeoutMillis"); 80 | return this; 81 | } 82 | 83 | /** 84 | * @param closedWebSocketRemoveTimeoutMillis delay until websockets handler forgets closed 85 | * websocket. Necessary to gracefully handle incoming http2 frames racing with outgoing stream 86 | * termination frame. 87 | * @return this {@link Http2WebSocketClientBuilder} instance 88 | */ 89 | public Http2WebSocketClientBuilder closedWebSocketRemoveTimeoutMillis( 90 | long closedWebSocketRemoveTimeoutMillis) { 91 | this.closedWebSocketRemoveTimeoutMillis = 92 | Http2WebSocketProtocol.requirePositive( 93 | closedWebSocketRemoveTimeoutMillis, "closedWebSocketRemoveTimeoutMillis"); 94 | return this; 95 | } 96 | 97 | /** 98 | * @param isCompressionEnabled enables permessage-deflate compression with default configuration 99 | * @return this {@link Http2WebSocketClientBuilder} instance 100 | */ 101 | public Http2WebSocketClientBuilder compression(boolean isCompressionEnabled) { 102 | if (isCompressionEnabled) { 103 | if (perMessageDeflateClientExtensionHandshaker == null) { 104 | perMessageDeflateClientExtensionHandshaker = 105 | new PerMessageDeflateClientExtensionHandshaker(); 106 | } 107 | } else { 108 | perMessageDeflateClientExtensionHandshaker = null; 109 | } 110 | return this; 111 | } 112 | 113 | /** 114 | * Enables permessage-deflate compression with extended configuration. Parameters are described in 115 | * netty's PerMessageDeflateClientExtensionHandshaker 116 | * 117 | * @param compressionLevel sets compression level. Range is [0; 9], default is 6 118 | * @param allowClientWindowSize allows server to customize the client's inflater window size, 119 | * default is false 120 | * @param requestedServerWindowSize requested server window size if server inflater is 121 | * customizable 122 | * @param allowClientNoContext allows server to activate client_no_context_takeover, default is 123 | * false 124 | * @param requestedServerNoContext whether client needs to activate server_no_context_takeover if 125 | * server is compatible, default is false. 126 | * @return this {@link Http2WebSocketClientBuilder} instance 127 | */ 128 | public Http2WebSocketClientBuilder compression( 129 | int compressionLevel, 130 | boolean allowClientWindowSize, 131 | int requestedServerWindowSize, 132 | boolean allowClientNoContext, 133 | boolean requestedServerNoContext) { 134 | perMessageDeflateClientExtensionHandshaker = 135 | new PerMessageDeflateClientExtensionHandshaker( 136 | compressionLevel, 137 | allowClientWindowSize, 138 | requestedServerWindowSize, 139 | allowClientNoContext, 140 | requestedServerNoContext); 141 | return this; 142 | } 143 | 144 | /** 145 | * @param isNomaskingExtension enables "no-masking" extension draft. 147 | * Takes precedence over masking related configuration. 148 | * @return this {@link Http2WebSocketClientBuilder} instance 149 | */ 150 | public Http2WebSocketClientBuilder nomaskingExtension(boolean isNomaskingExtension) { 151 | this.isNomaskingExtension = isNomaskingExtension; 152 | return this; 153 | } 154 | 155 | /** 156 | * @param weight sets websocket http2 stream weight. Must belong to [1; 256] range 157 | * @return this {@link Http2WebSocketClientBuilder} instance 158 | */ 159 | public Http2WebSocketClientBuilder streamWeight(int weight) { 160 | this.streamWeight = Http2WebSocketProtocol.requireRange(weight, 1, 256, "streamWeight"); 161 | return this; 162 | } 163 | 164 | /** 165 | * @param isSingleWebSocketPerConnection optimize for at most 1 websocket per connection 166 | * @return this {@link Http2WebSocketClientBuilder} instance 167 | */ 168 | public Http2WebSocketClientBuilder assumeSingleWebSocketPerConnection( 169 | boolean isSingleWebSocketPerConnection) { 170 | this.isSingleWebSocketPerConnection = isSingleWebSocketPerConnection; 171 | return this; 172 | } 173 | 174 | /** @return new {@link Http2WebSocketClientHandler} instance */ 175 | public Http2WebSocketClientHandler build() { 176 | PerMessageDeflateClientExtensionHandshaker compressionHandshaker = 177 | perMessageDeflateClientExtensionHandshaker; 178 | boolean hasCompression = compressionHandshaker != null; 179 | WebSocketDecoderConfig config = webSocketDecoderConfig; 180 | if (config == null) { 181 | config = 182 | WebSocketDecoderConfig.newBuilder() 183 | /*align with the spec and strictness of some browsers*/ 184 | .expectMaskedFrames(false) 185 | .allowMaskMismatch(false) 186 | .allowExtensions(hasCompression) 187 | .build(); 188 | } else { 189 | boolean isAllowExtensions = config.allowExtensions(); 190 | if (!isAllowExtensions && hasCompression) { 191 | config = config.toBuilder().allowExtensions(true).build(); 192 | } 193 | } 194 | Http1WebSocketCodec codec = webSocketCodec; 195 | boolean maskPayload = isMaskPayload; 196 | codec.validate(maskPayload, config); 197 | 198 | short weight = streamWeight; 199 | if (weight == 0) { 200 | weight = DEFAULT_STREAM_WEIGHT; 201 | } 202 | 203 | return new Http2WebSocketClientHandler( 204 | codec, 205 | config, 206 | maskPayload, 207 | isNomaskingExtension, 208 | weight, 209 | handshakeTimeoutMillis, 210 | closedWebSocketRemoveTimeoutMillis, 211 | compressionHandshaker, 212 | isSingleWebSocketPerConnection); 213 | } 214 | } 215 | -------------------------------------------------------------------------------- /netty-websocket-http2/src/main/java/com/jauntsdn/netty/handler/codec/http2/websocketx/Http2WebSocketClientHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2020 - present Maksym Ostroverkhov. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.jauntsdn.netty.handler.codec.http2.websocketx; 18 | 19 | import io.netty.channel.ChannelHandlerContext; 20 | import io.netty.channel.EventLoop; 21 | import io.netty.handler.codec.http.websocketx.WebSocketDecoderConfig; 22 | import io.netty.handler.codec.http.websocketx.extensions.compression.PerMessageDeflateClientExtensionHandshaker; 23 | import io.netty.handler.codec.http2.Http2Connection; 24 | import io.netty.handler.codec.http2.Http2Exception; 25 | import io.netty.handler.codec.http2.Http2Headers; 26 | import io.netty.handler.codec.http2.Http2LocalFlowController; 27 | import io.netty.handler.codec.http2.Http2Settings; 28 | import io.netty.handler.ssl.SslHandler; 29 | import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; 30 | import javax.annotation.Nullable; 31 | 32 | /** 33 | * Provides client-side support for websocket-over-http2. Creates sub channel for http2 stream of 34 | * successfully handshaked websocket. Subchannel is compatible with http1 websocket handlers. Should 35 | * be used in tandem with {@link Http2WebSocketClientHandshaker} 36 | */ 37 | public final class Http2WebSocketClientHandler extends Http2WebSocketChannelHandler { 38 | private static final AtomicReferenceFieldUpdater< 39 | Http2WebSocketClientHandler, Http2WebSocketClientHandshaker> 40 | HANDSHAKER = 41 | AtomicReferenceFieldUpdater.newUpdater( 42 | Http2WebSocketClientHandler.class, 43 | Http2WebSocketClientHandshaker.class, 44 | "handshaker"); 45 | 46 | private final long handshakeTimeoutMillis; 47 | private final PerMessageDeflateClientExtensionHandshaker compressionHandshaker; 48 | private final short streamWeight; 49 | 50 | private CharSequence scheme; 51 | private Boolean supportsWebSocket; 52 | private boolean supportsWebSocketCalled; 53 | private volatile Http2Connection.Endpoint streamIdFactory; 54 | private volatile Http2WebSocketClientHandshaker handshaker; 55 | 56 | Http2WebSocketClientHandler( 57 | Http1WebSocketCodec webSocketCodec, 58 | WebSocketDecoderConfig webSocketDecoderConfig, 59 | boolean isEncoderMaskPayload, 60 | boolean isNomaskingExtension, 61 | short streamWeight, 62 | long handshakeTimeoutMillis, 63 | long closedWebSocketRemoveTimeoutMillis, 64 | @Nullable PerMessageDeflateClientExtensionHandshaker compressionHandshaker, 65 | boolean isSingleWebSocketPerConnection) { 66 | super( 67 | webSocketCodec, 68 | webSocketDecoderConfig, 69 | isEncoderMaskPayload, 70 | isNomaskingExtension, 71 | closedWebSocketRemoveTimeoutMillis, 72 | isSingleWebSocketPerConnection); 73 | this.streamWeight = streamWeight; 74 | this.handshakeTimeoutMillis = handshakeTimeoutMillis; 75 | this.compressionHandshaker = compressionHandshaker; 76 | } 77 | 78 | @Override 79 | public void handlerAdded(ChannelHandlerContext ctx) throws Exception { 80 | super.handlerAdded(ctx); 81 | this.scheme = 82 | ctx.pipeline().get(SslHandler.class) != null 83 | ? Http2WebSocketProtocol.SCHEME_HTTPS 84 | : Http2WebSocketProtocol.SCHEME_HTTP; 85 | this.streamIdFactory = http2Handler.connection().local(); 86 | } 87 | 88 | @Override 89 | public void channelActive(ChannelHandlerContext ctx) throws Exception { 90 | super.channelActive(ctx); 91 | /*for non-tls connections netty's client http2 handler does not flush after http2 preface is written*/ 92 | if (scheme.equals(Http2WebSocketProtocol.SCHEME_HTTP)) { 93 | ctx.flush(); 94 | } 95 | } 96 | 97 | @Override 98 | public void onSettingsRead(ChannelHandlerContext ctx, Http2Settings settings) 99 | throws Http2Exception { 100 | if (supportsWebSocket != null) { 101 | super.onSettingsRead(ctx, settings); 102 | return; 103 | } 104 | Long extendedConnectEnabled = 105 | settings.get(Http2WebSocketProtocol.SETTINGS_ENABLE_CONNECT_PROTOCOL); 106 | boolean supports = 107 | supportsWebSocket = extendedConnectEnabled != null && extendedConnectEnabled == 1; 108 | Http2WebSocketEvent.fireWebSocketSupported(webSocketsParent.context().channel(), supports); 109 | Http2WebSocketClientHandshaker listener = HANDSHAKER.get(this); 110 | if (listener != null) { 111 | supportsWebSocketCalled = true; 112 | listener.onSupportsWebSocket(supports); 113 | } 114 | super.onSettingsRead(ctx, settings); 115 | } 116 | 117 | @Override 118 | public void onHeadersRead( 119 | ChannelHandlerContext ctx, 120 | int streamId, 121 | Http2Headers headers, 122 | int padding, 123 | boolean endOfStream) 124 | throws Http2Exception { 125 | boolean proceed = handshakeWebSocket(streamId, headers, endOfStream); 126 | if (proceed) { 127 | next().onHeadersRead(ctx, streamId, headers, padding, endOfStream); 128 | } 129 | } 130 | 131 | @Override 132 | public void onHeadersRead( 133 | ChannelHandlerContext ctx, 134 | int streamId, 135 | Http2Headers headers, 136 | int streamDependency, 137 | short weight, 138 | boolean exclusive, 139 | int padding, 140 | boolean endOfStream) 141 | throws Http2Exception { 142 | boolean proceed = handshakeWebSocket(streamId, headers, endOfStream); 143 | if (proceed) { 144 | next() 145 | .onHeadersRead( 146 | ctx, streamId, headers, streamDependency, weight, exclusive, padding, endOfStream); 147 | } 148 | } 149 | 150 | Http2WebSocketClientHandshaker handShaker() { 151 | Http2WebSocketClientHandshaker h = HANDSHAKER.get(this); 152 | if (h != null) { 153 | return h; 154 | } 155 | Http2Connection.Endpoint streamIdFactory = this.streamIdFactory; 156 | if (streamIdFactory == null) { 157 | throw new IllegalStateException( 158 | "webSocket handshaker cant be created before channel is registered"); 159 | } 160 | boolean nomaskingExtension = 161 | isNomaskingExtension && ctx.pipeline().get(SslHandler.class) != null; 162 | 163 | Http2WebSocketClientHandshaker handShaker = 164 | new Http2WebSocketClientHandshaker( 165 | webSocketsParent, 166 | streamIdFactory, 167 | config, 168 | isEncoderMaskPayload, 169 | nomaskingExtension, 170 | streamWeight, 171 | scheme, 172 | handshakeTimeoutMillis, 173 | webSocketCodec, 174 | compressionHandshaker); 175 | 176 | if (HANDSHAKER.compareAndSet(this, null, handShaker)) { 177 | EventLoop el = ctx.channel().eventLoop(); 178 | if (el.inEventLoop()) { 179 | onSupportsWebSocket(handShaker); 180 | } else { 181 | el.execute(() -> onSupportsWebSocket(handShaker)); 182 | } 183 | return handShaker; 184 | } 185 | return HANDSHAKER.get(this); 186 | } 187 | 188 | private boolean handshakeWebSocket( 189 | int streamId, Http2Headers responseHeaders, boolean endOfStream) { 190 | Http2WebSocket webSocket = webSocketRegistry.get(streamId); 191 | if (webSocket != null) { 192 | if (!Http2WebSocketProtocol.Validator.isValid(responseHeaders)) { 193 | handShaker().reject(streamId, webSocket, responseHeaders, endOfStream); 194 | } else { 195 | handShaker().handshake(webSocket, responseHeaders, endOfStream); 196 | } 197 | return false; 198 | } 199 | return true; 200 | } 201 | 202 | private void onSupportsWebSocket(Http2WebSocketClientHandshaker handshaker) { 203 | if (supportsWebSocketCalled) { 204 | return; 205 | } 206 | Boolean supports = supportsWebSocket; 207 | if (supports != null) { 208 | handshaker.onSupportsWebSocket(supports); 209 | } 210 | } 211 | } 212 | -------------------------------------------------------------------------------- /netty-websocket-http2/src/main/java/com/jauntsdn/netty/handler/codec/http2/websocketx/Http2WebSocketHandshakeOnlyServerHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2020 - present Maksym Ostroverkhov. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.jauntsdn.netty.handler.codec.http2.websocketx; 18 | 19 | import io.netty.channel.ChannelFuture; 20 | import io.netty.channel.ChannelHandlerContext; 21 | import io.netty.handler.codec.http2.Http2Error; 22 | import io.netty.handler.codec.http2.Http2Exception; 23 | import io.netty.handler.codec.http2.Http2Headers; 24 | import io.netty.util.concurrent.GenericFutureListener; 25 | import org.slf4j.Logger; 26 | import org.slf4j.LoggerFactory; 27 | 28 | /** 29 | * Provides server-side support for websocket-over-http2. Verifies websocket-over-http2 request 30 | * validity. Invalid websocket requests are rejected by sending RST frame, valid websocket http2 31 | * stream frames are passed down the pipeline. Valid websocket stream request headers are modified 32 | * as follows: :method=POST, x-protocol=websocket. Intended for proxies/intermidiaries that do not 33 | * process websocket byte streams, but only route respective http2 streams - hence is not compatible 34 | * with http1 websocket handlers. http1 websocket handlers support is provided by complementary 35 | * {@link Http2WebSocketServerHandler} 36 | */ 37 | public final class Http2WebSocketHandshakeOnlyServerHandler extends Http2WebSocketHandler 38 | implements GenericFutureListener { 39 | private static final Logger logger = 40 | LoggerFactory.getLogger(Http2WebSocketHandshakeOnlyServerHandler.class); 41 | 42 | Http2WebSocketHandshakeOnlyServerHandler() {} 43 | 44 | @Override 45 | public void onHeadersRead( 46 | ChannelHandlerContext ctx, 47 | int streamId, 48 | Http2Headers headers, 49 | int padding, 50 | boolean endOfStream) 51 | throws Http2Exception { 52 | if (handshake(headers, endOfStream)) { 53 | super.onHeadersRead(ctx, streamId, headers, padding, endOfStream); 54 | } else { 55 | reject(ctx, streamId, headers, endOfStream); 56 | } 57 | } 58 | 59 | @Override 60 | public void onHeadersRead( 61 | ChannelHandlerContext ctx, 62 | int streamId, 63 | Http2Headers headers, 64 | int streamDependency, 65 | short weight, 66 | boolean exclusive, 67 | int padding, 68 | boolean endOfStream) 69 | throws Http2Exception { 70 | if (handshake(headers, endOfStream)) { 71 | super.onHeadersRead( 72 | ctx, streamId, headers, streamDependency, weight, exclusive, padding, endOfStream); 73 | } else { 74 | reject(ctx, streamId, headers, endOfStream); 75 | } 76 | } 77 | 78 | /*RST_STREAM frame write*/ 79 | @Override 80 | public void operationComplete(ChannelFuture future) { 81 | Throwable cause = future.cause(); 82 | if (cause != null) { 83 | Http2WebSocketEvent.fireFrameWriteError(future.channel(), cause); 84 | } 85 | } 86 | 87 | private boolean handshake(Http2Headers headers, boolean endOfStream) { 88 | if (Http2WebSocketProtocol.isExtendedConnect(headers)) { 89 | boolean isValid = Http2WebSocketProtocol.Validator.WebSocket.isValid(headers, endOfStream); 90 | if (isValid) { 91 | Http2WebSocketServerHandshaker.handshakeOnlyWebSocket(headers); 92 | } 93 | return isValid; 94 | } 95 | return Http2WebSocketProtocol.Validator.Http.isValid(headers, endOfStream); 96 | } 97 | 98 | private void reject( 99 | ChannelHandlerContext ctx, int streamId, Http2Headers headers, boolean endOfStream) { 100 | Http2WebSocketEvent.fireHandshakeValidationStartAndError( 101 | ctx.channel(), streamId, headers.set(endOfStreamName(), endOfStreamValue(endOfStream))); 102 | http2Handler 103 | .encoder() 104 | .writeRstStream(ctx, streamId, Http2Error.PROTOCOL_ERROR.code(), ctx.newPromise()) 105 | .addListener(this); 106 | ctx.flush(); 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /netty-websocket-http2/src/main/java/com/jauntsdn/netty/handler/codec/http2/websocketx/Http2WebSocketPathNotFoundException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 - present Maksym Ostroverkhov. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.jauntsdn.netty.handler.codec.http2.websocketx; 18 | 19 | import io.netty.handler.codec.http.websocketx.WebSocketHandshakeException; 20 | 21 | public final class Http2WebSocketPathNotFoundException extends WebSocketHandshakeException { 22 | public Http2WebSocketPathNotFoundException(String message) { 23 | super(message); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /netty-websocket-http2/src/main/java/com/jauntsdn/netty/handler/codec/http2/websocketx/Http2WebSocketServerBuilder.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2020 - present Maksym Ostroverkhov. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.jauntsdn.netty.handler.codec.http2.websocketx; 18 | 19 | import io.netty.handler.codec.http.websocketx.WebSocketDecoderConfig; 20 | import io.netty.handler.codec.http.websocketx.extensions.compression.PerMessageDeflateServerExtensionHandshaker; 21 | import io.netty.handler.codec.http2.Http2ConnectionHandlerBuilder; 22 | import io.netty.handler.codec.http2.Http2FrameCodecBuilder; 23 | import java.util.Objects; 24 | import org.slf4j.Logger; 25 | import org.slf4j.LoggerFactory; 26 | 27 | /** Builder for {@link Http2WebSocketServerHandler} */ 28 | public final class Http2WebSocketServerBuilder { 29 | private static final Logger logger = LoggerFactory.getLogger(Http2WebSocketServerBuilder.class); 30 | private static final boolean MASK_PAYLOAD = false; 31 | 32 | private static final Http2WebSocketAcceptor REJECT_REQUESTS_ACCEPTOR = 33 | (context, path, subprotocols, request, response) -> 34 | context 35 | .executor() 36 | .newFailedFuture( 37 | new Http2WebSocketPathNotFoundException( 38 | Http2WebSocketProtocol.MSG_HANDSHAKE_PATH_NOT_FOUND 39 | + path 40 | + Http2WebSocketProtocol.MSG_HANDSHAKE_PATH_NOT_FOUND_SUBPROTOCOLS 41 | + subprotocols)); 42 | 43 | private Http1WebSocketCodec webSocketCodec = Http1WebSocketCodec.DEFAULT; 44 | private WebSocketDecoderConfig webSocketDecoderConfig; 45 | 46 | private boolean isNomaskingExtension; 47 | private PerMessageDeflateServerExtensionHandshaker perMessageDeflateServerExtensionHandshaker; 48 | private long closedWebSocketRemoveTimeoutMillis = 30_000; 49 | private boolean isSingleWebSocketPerConnection; 50 | private Http2WebSocketAcceptor acceptor = REJECT_REQUESTS_ACCEPTOR; 51 | 52 | Http2WebSocketServerBuilder() {} 53 | 54 | /** 55 | * Builds handshake-only {@link Http2WebSocketHandshakeOnlyServerHandler}. 56 | * 57 | * @return new {@link Http2WebSocketHandshakeOnlyServerHandler} instance 58 | */ 59 | public static Http2WebSocketHandshakeOnlyServerHandler buildHandshakeOnly() { 60 | return new Http2WebSocketHandshakeOnlyServerHandler(); 61 | } 62 | 63 | /** @return new {@link Http2WebSocketServerBuilder} instance */ 64 | public static Http2WebSocketServerBuilder create() { 65 | return new Http2WebSocketServerBuilder(); 66 | } 67 | 68 | /** 69 | * Utility method for configuring Http2FrameCodecBuilder with websocket-over-http2 support 70 | * 71 | * @param http2Builder {@link Http2FrameCodecBuilder} instance 72 | * @return same {@link Http2FrameCodecBuilder} instance 73 | */ 74 | public static Http2FrameCodecBuilder configureHttp2Server(Http2FrameCodecBuilder http2Builder) { 75 | Objects.requireNonNull(http2Builder, "http2Builder") 76 | .initialSettings() 77 | .put(Http2WebSocketProtocol.SETTINGS_ENABLE_CONNECT_PROTOCOL, (Long) 1L); 78 | return http2Builder.validateHeaders(false); 79 | } 80 | 81 | /** 82 | * Utility method for configuring Http2ConnectionHandlerBuilder with websocket-over-http2 support 83 | * 84 | * @param http2Builder {@link Http2ConnectionHandlerBuilder} instance 85 | * @return same {@link Http2ConnectionHandlerBuilder} instance 86 | */ 87 | public static Http2ConnectionHandlerBuilder configureHttp2Server( 88 | Http2ConnectionHandlerBuilder http2Builder) { 89 | Objects.requireNonNull(http2Builder, "http2Builder") 90 | .initialSettings() 91 | .put(Http2WebSocketProtocol.SETTINGS_ENABLE_CONNECT_PROTOCOL, (Long) 1L); 92 | return http2Builder.validateHeaders(false); 93 | } 94 | 95 | /** 96 | * @param webSocketCodec factory for websocket1 encoder/decoder used for protocol processing. Must 97 | * be non-null 98 | * @return this {@link Http2WebSocketClientBuilder} instance 99 | */ 100 | public Http2WebSocketServerBuilder codec(Http1WebSocketCodec webSocketCodec) { 101 | this.webSocketCodec = Objects.requireNonNull(webSocketCodec, "webSocketCodec"); 102 | return this; 103 | } 104 | 105 | /** 106 | * @param webSocketDecoderConfig websocket decoder configuration. Must be non-null 107 | * @return this {@link Http2WebSocketServerBuilder} instance 108 | */ 109 | public Http2WebSocketServerBuilder decoderConfig(WebSocketDecoderConfig webSocketDecoderConfig) { 110 | this.webSocketDecoderConfig = 111 | Objects.requireNonNull(webSocketDecoderConfig, "webSocketDecoderConfig"); 112 | return this; 113 | } 114 | 115 | /** 116 | * @param closedWebSocketRemoveTimeoutMillis delay until websockets handler forgets closed 117 | * websocket. Necessary to gracefully handle incoming http2 frames racing with outgoing stream 118 | * termination frame. 119 | * @return this {@link Http2WebSocketServerBuilder} instance 120 | */ 121 | public Http2WebSocketServerBuilder closedWebSocketRemoveTimeout( 122 | long closedWebSocketRemoveTimeoutMillis) { 123 | this.closedWebSocketRemoveTimeoutMillis = 124 | Http2WebSocketProtocol.requirePositive( 125 | closedWebSocketRemoveTimeoutMillis, "closedWebSocketRemoveTimeoutMillis"); 126 | return this; 127 | } 128 | 129 | /** 130 | * @param isCompressionEnabled enables permessage-deflate compression with default configuration 131 | * @return this {@link Http2WebSocketServerBuilder} instance 132 | */ 133 | public Http2WebSocketServerBuilder compression(boolean isCompressionEnabled) { 134 | if (isCompressionEnabled) { 135 | if (perMessageDeflateServerExtensionHandshaker == null) { 136 | perMessageDeflateServerExtensionHandshaker = 137 | new PerMessageDeflateServerExtensionHandshaker(); 138 | } 139 | } else { 140 | perMessageDeflateServerExtensionHandshaker = null; 141 | } 142 | return this; 143 | } 144 | 145 | /** 146 | * Enables permessage-deflate compression with extended configuration. Parameters are described in 147 | * netty's PerMessageDeflateServerExtensionHandshaker 148 | * 149 | * @param compressionLevel sets compression level. Range is [0; 9], default is 6 150 | * @param allowServerWindowSize allows client to customize the server's inflater window size, 151 | * default is false 152 | * @param preferredClientWindowSize preferred client window size if client inflater is 153 | * customizable 154 | * @param allowServerNoContext allows client to activate server_no_context_takeover, default is 155 | * false 156 | * @param preferredClientNoContext whether server prefers to activate client_no_context_takeover 157 | * if client is compatible, default is false 158 | * @return this {@link Http2WebSocketServerBuilder} instance 159 | */ 160 | public Http2WebSocketServerBuilder compression( 161 | int compressionLevel, 162 | boolean allowServerWindowSize, 163 | int preferredClientWindowSize, 164 | boolean allowServerNoContext, 165 | boolean preferredClientNoContext) { 166 | perMessageDeflateServerExtensionHandshaker = 167 | new PerMessageDeflateServerExtensionHandshaker( 168 | compressionLevel, 169 | allowServerWindowSize, 170 | preferredClientWindowSize, 171 | allowServerNoContext, 172 | preferredClientNoContext); 173 | return this; 174 | } 175 | 176 | /** 177 | * @param isNomaskingExtension enables "no-masking" extension draft. 179 | * Takes precedence over masking related configuration. 180 | * @return this {@link Http2WebSocketServerBuilder} instance 181 | */ 182 | public Http2WebSocketServerBuilder nomaskingExtension(boolean isNomaskingExtension) { 183 | this.isNomaskingExtension = isNomaskingExtension; 184 | return this; 185 | } 186 | 187 | /** 188 | * Sets http1 websocket request acceptor 189 | * 190 | * @param acceptor websocket request acceptor. Must be non-null. 191 | * @return this {@link Http2WebSocketServerBuilder} instance 192 | */ 193 | public Http2WebSocketServerBuilder acceptor(Http2WebSocketAcceptor acceptor) { 194 | this.acceptor = Objects.requireNonNull(acceptor, "acceptor"); 195 | return this; 196 | } 197 | 198 | /** 199 | * @param isSingleWebSocketPerConnection optimize for at most 1 websocket per connection 200 | * @return this {@link Http2WebSocketServerBuilder} instance 201 | */ 202 | public Http2WebSocketServerBuilder assumeSingleWebSocketPerConnection( 203 | boolean isSingleWebSocketPerConnection) { 204 | this.isSingleWebSocketPerConnection = isSingleWebSocketPerConnection; 205 | return this; 206 | } 207 | 208 | /** 209 | * Builds subchannel based {@link Http2WebSocketServerHandler} compatible with http1 websocket 210 | * handlers. 211 | * 212 | * @return new {@link Http2WebSocketServerHandler} instance 213 | */ 214 | public Http2WebSocketServerHandler build() { 215 | boolean hasCompression = perMessageDeflateServerExtensionHandshaker != null; 216 | WebSocketDecoderConfig config = webSocketDecoderConfig; 217 | if (config == null) { 218 | config = 219 | WebSocketDecoderConfig.newBuilder() 220 | /*align with the spec and strictness of some browsers*/ 221 | .expectMaskedFrames(true) 222 | .allowMaskMismatch(false) 223 | .allowExtensions(hasCompression) 224 | .build(); 225 | } else { 226 | boolean isAllowExtensions = config.allowExtensions(); 227 | if (!isAllowExtensions && hasCompression) { 228 | config = config.toBuilder().allowExtensions(true).build(); 229 | } 230 | } 231 | Http1WebSocketCodec codec = webSocketCodec; 232 | codec.validate(MASK_PAYLOAD, config); 233 | 234 | return new Http2WebSocketServerHandler( 235 | codec, 236 | config, 237 | MASK_PAYLOAD, 238 | isNomaskingExtension, 239 | closedWebSocketRemoveTimeoutMillis, 240 | perMessageDeflateServerExtensionHandshaker, 241 | acceptor, 242 | isSingleWebSocketPerConnection); 243 | } 244 | } 245 | -------------------------------------------------------------------------------- /netty-websocket-http2/src/main/java/com/jauntsdn/netty/handler/codec/http2/websocketx/Http2WebSocketServerHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2020 - present Maksym Ostroverkhov. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.jauntsdn.netty.handler.codec.http2.websocketx; 18 | 19 | import io.netty.channel.ChannelHandlerContext; 20 | import io.netty.handler.codec.http.websocketx.WebSocketDecoderConfig; 21 | import io.netty.handler.codec.http.websocketx.extensions.compression.PerMessageDeflateServerExtensionHandshaker; 22 | import io.netty.handler.codec.http2.Http2Exception; 23 | import io.netty.handler.codec.http2.Http2Headers; 24 | import io.netty.handler.ssl.SslHandler; 25 | import javax.annotation.Nullable; 26 | 27 | /** 28 | * Provides server-side support for websocket-over-http2. Creates sub channel for http2 stream of 29 | * successfully handshaked websocket. Subchannel is compatible with http1 websocket handlers. 30 | */ 31 | public final class Http2WebSocketServerHandler extends Http2WebSocketChannelHandler { 32 | private final PerMessageDeflateServerExtensionHandshaker compressionHandshaker; 33 | private final Http2WebSocketAcceptor http2WebSocketAcceptor; 34 | 35 | private Http2WebSocketServerHandshaker handshaker; 36 | 37 | Http2WebSocketServerHandler( 38 | Http1WebSocketCodec webSocketCodec, 39 | WebSocketDecoderConfig webSocketDecoderConfig, 40 | boolean isEncoderMaskPayload, 41 | boolean nomaskingExtension, 42 | long closedWebSocketRemoveTimeoutMillis, 43 | @Nullable PerMessageDeflateServerExtensionHandshaker compressionHandshaker, 44 | Http2WebSocketAcceptor http2WebSocketAcceptor, 45 | boolean isSingleWebSocketPerConnection) { 46 | super( 47 | webSocketCodec, 48 | webSocketDecoderConfig, 49 | isEncoderMaskPayload, 50 | nomaskingExtension, 51 | closedWebSocketRemoveTimeoutMillis, 52 | isSingleWebSocketPerConnection); 53 | this.compressionHandshaker = compressionHandshaker; 54 | this.http2WebSocketAcceptor = http2WebSocketAcceptor; 55 | } 56 | 57 | @Override 58 | public void handlerAdded(ChannelHandlerContext ctx) throws Exception { 59 | super.handlerAdded(ctx); 60 | boolean nomaskingExtension = 61 | isNomaskingExtension && ctx.pipeline().get(SslHandler.class) != null; 62 | this.handshaker = 63 | new Http2WebSocketServerHandshaker( 64 | webSocketsParent, 65 | config, 66 | isEncoderMaskPayload, 67 | nomaskingExtension, 68 | http2WebSocketAcceptor, 69 | webSocketCodec, 70 | compressionHandshaker); 71 | } 72 | 73 | @Override 74 | public void onHeadersRead( 75 | ChannelHandlerContext ctx, 76 | final int streamId, 77 | Http2Headers headers, 78 | int padding, 79 | boolean endOfStream) 80 | throws Http2Exception { 81 | boolean proceed = handshakeWebSocket(streamId, headers, endOfStream); 82 | if (proceed) { 83 | next().onHeadersRead(ctx, streamId, headers, padding, endOfStream); 84 | } 85 | } 86 | 87 | @Override 88 | public void onHeadersRead( 89 | ChannelHandlerContext ctx, 90 | int streamId, 91 | Http2Headers headers, 92 | int streamDependency, 93 | short weight, 94 | boolean exclusive, 95 | int padding, 96 | boolean endOfStream) 97 | throws Http2Exception { 98 | boolean proceed = handshakeWebSocket(streamId, headers, endOfStream); 99 | if (proceed) { 100 | next() 101 | .onHeadersRead( 102 | ctx, streamId, headers, streamDependency, weight, exclusive, padding, endOfStream); 103 | } 104 | } 105 | 106 | private boolean handshakeWebSocket(int streamId, Http2Headers headers, boolean endOfStream) { 107 | if (Http2WebSocketProtocol.isExtendedConnect(headers)) { 108 | if (!Http2WebSocketProtocol.Validator.WebSocket.isValid(headers, endOfStream)) { 109 | handshaker.reject(streamId, headers, endOfStream); 110 | } else { 111 | handshaker.handshake(streamId, headers, endOfStream); 112 | } 113 | return false; 114 | } 115 | if (!Http2WebSocketProtocol.Validator.Http.isValid(headers, endOfStream)) { 116 | handshaker.reject(streamId, headers, endOfStream); 117 | return false; 118 | } 119 | return true; 120 | } 121 | } 122 | -------------------------------------------------------------------------------- /netty-websocket-http2/src/main/java/com/jauntsdn/netty/handler/codec/http2/websocketx/WebSocketEvent.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 - present Maksym Ostroverkhov. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.jauntsdn.netty.handler.codec.http2.websocketx; 18 | 19 | import io.netty.handler.codec.Headers; 20 | import javax.annotation.Nullable; 21 | 22 | /** Base type for transport agnostic websocket lifecycle events */ 23 | public abstract class WebSocketEvent extends Http2WebSocketEvent.Http2WebSocketLifecycleEvent { 24 | 25 | WebSocketEvent( 26 | Http2WebSocketEvent.Type type, 27 | int id, 28 | String authority, 29 | String path, 30 | String subprotocols, 31 | long timestampNanos) { 32 | super(type, id, authority, path, subprotocols, timestampNanos); 33 | } 34 | 35 | /** websocket handshake start event */ 36 | public static class WebSocketHandshakeStartEvent extends WebSocketEvent { 37 | private final Headers requestHeaders; 38 | 39 | WebSocketHandshakeStartEvent( 40 | int id, 41 | String authority, 42 | String path, 43 | String subprotocol, 44 | long timestampNanos, 45 | Headers requestHeaders) { 46 | super(Type.HANDSHAKE_START, id, authority, path, subprotocol, timestampNanos); 47 | this.requestHeaders = requestHeaders; 48 | } 49 | 50 | /** @return websocket request headers */ 51 | public Headers requestHeaders() { 52 | return requestHeaders; 53 | } 54 | } 55 | 56 | /** websocket handshake error event */ 57 | public static class WebSocketHandshakeErrorEvent extends WebSocketEvent { 58 | private final Headers responseHeaders; 59 | private final String errorName; 60 | private final String errorMessage; 61 | private final Throwable error; 62 | 63 | WebSocketHandshakeErrorEvent( 64 | int id, 65 | String authority, 66 | String path, 67 | String subprotocols, 68 | long timestampNanos, 69 | Headers responseHeaders, 70 | Throwable error) { 71 | this(id, authority, path, subprotocols, timestampNanos, responseHeaders, error, null, null); 72 | } 73 | 74 | WebSocketHandshakeErrorEvent( 75 | int id, 76 | String authority, 77 | String path, 78 | String subprotocols, 79 | long timestampNanos, 80 | Headers responseHeaders, 81 | String errorName, 82 | String errorMessage) { 83 | this( 84 | id, 85 | authority, 86 | path, 87 | subprotocols, 88 | timestampNanos, 89 | responseHeaders, 90 | null, 91 | errorName, 92 | errorMessage); 93 | } 94 | 95 | private WebSocketHandshakeErrorEvent( 96 | int id, 97 | String authority, 98 | String path, 99 | String subprotocols, 100 | long timestampNanos, 101 | Headers responseHeaders, 102 | Throwable error, 103 | String errorName, 104 | String errorMessage) { 105 | super(Type.HANDSHAKE_ERROR, id, authority, path, subprotocols, timestampNanos); 106 | this.responseHeaders = responseHeaders; 107 | this.errorName = errorName; 108 | this.errorMessage = errorMessage; 109 | this.error = error; 110 | } 111 | 112 | /** @return response headers of failed websocket handshake */ 113 | public Headers responseHeaders() { 114 | return responseHeaders; 115 | } 116 | 117 | /** 118 | * @return exception associated with failed websocket handshake. May be null, in this case 119 | * {@link #errorName()} and {@link #errorMessage()} contain error details. 120 | */ 121 | @Nullable 122 | public Throwable error() { 123 | return error; 124 | } 125 | 126 | /** 127 | * @return name of error associated with failed websocket handshake. May be null, in this case 128 | * {@link #error()} contains respective exception 129 | */ 130 | public String errorName() { 131 | return errorName; 132 | } 133 | 134 | /** 135 | * @return message of error associated with failed websocket handshake. May be null, in this 136 | * case {@link #error()} contains respective exception 137 | */ 138 | public String errorMessage() { 139 | return errorMessage; 140 | } 141 | } 142 | 143 | /** websocket handshake success event */ 144 | public static class WebSocketHandshakeSuccessEvent extends WebSocketEvent { 145 | private final String subprotocol; 146 | private final Headers responseHeaders; 147 | 148 | WebSocketHandshakeSuccessEvent( 149 | int id, 150 | String authority, 151 | String path, 152 | String subprotocols, 153 | String subprotocol, 154 | long timestampNanos, 155 | Headers responseHeaders) { 156 | super(Type.HANDSHAKE_SUCCESS, id, authority, path, subprotocols, timestampNanos); 157 | this.subprotocol = subprotocol; 158 | this.responseHeaders = responseHeaders; 159 | } 160 | 161 | public String subprotocol() { 162 | return subprotocol; 163 | } 164 | 165 | /** @return response headers of succeeded websocket handshake */ 166 | public Headers responseHeaders() { 167 | return responseHeaders; 168 | } 169 | } 170 | } 171 | -------------------------------------------------------------------------------- /netty-websocket-http2/src/test/java/com/jauntsdn/netty/handler/codec/http2/websocketx/AbstractTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2020 - present Maksym Ostroverkhov. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.jauntsdn.netty.handler.codec.http2.websocketx; 18 | 19 | import com.jauntsdn.netty.handler.codec.http2.websocketx.Http2WebSocketEvent.Http2WebSocketSupportedEvent; 20 | import io.netty.bootstrap.Bootstrap; 21 | import io.netty.bootstrap.ServerBootstrap; 22 | import io.netty.channel.ChannelFuture; 23 | import io.netty.channel.ChannelHandler; 24 | import io.netty.channel.ChannelHandlerContext; 25 | import io.netty.channel.ChannelInboundHandlerAdapter; 26 | import io.netty.channel.ChannelInitializer; 27 | import io.netty.channel.ChannelPromise; 28 | import io.netty.channel.nio.NioEventLoopGroup; 29 | import io.netty.channel.socket.SocketChannel; 30 | import io.netty.channel.socket.nio.NioServerSocketChannel; 31 | import io.netty.channel.socket.nio.NioSocketChannel; 32 | import io.netty.handler.codec.http.websocketx.WebSocketHandshakeException; 33 | import io.netty.handler.codec.http2.Http2Headers; 34 | import io.netty.handler.codec.http2.Http2SecurityUtil; 35 | import io.netty.handler.ssl.ApplicationProtocolConfig; 36 | import io.netty.handler.ssl.ApplicationProtocolNames; 37 | import io.netty.handler.ssl.SslContext; 38 | import io.netty.handler.ssl.SslContextBuilder; 39 | import io.netty.handler.ssl.SslProvider; 40 | import io.netty.handler.ssl.SupportedCipherSuiteFilter; 41 | import io.netty.handler.ssl.util.InsecureTrustManagerFactory; 42 | import io.netty.util.concurrent.Future; 43 | import java.io.InputStream; 44 | import java.net.SocketAddress; 45 | import java.security.KeyStore; 46 | import java.util.ArrayList; 47 | import java.util.List; 48 | import java.util.function.Consumer; 49 | import javax.net.ssl.KeyManagerFactory; 50 | import javax.net.ssl.SSLException; 51 | 52 | abstract class AbstractTest { 53 | 54 | static ChannelFuture createClient( 55 | SocketAddress address, Consumer pipelineConfigurer) { 56 | return new Bootstrap() 57 | .group(new NioEventLoopGroup()) 58 | .channel(NioSocketChannel.class) 59 | .handler( 60 | new ChannelInitializer() { 61 | @Override 62 | protected void initChannel(SocketChannel ch) { 63 | pipelineConfigurer.accept(ch); 64 | } 65 | }) 66 | .connect(address); 67 | } 68 | 69 | static ChannelFuture createServer(Consumer pipelineConfigurer) { 70 | return new ServerBootstrap() 71 | .group(new NioEventLoopGroup()) 72 | .channel(NioServerSocketChannel.class) 73 | .childHandler( 74 | new ChannelInitializer() { 75 | 76 | @Override 77 | protected void initChannel(SocketChannel ch) { 78 | pipelineConfigurer.accept(ch); 79 | } 80 | }) 81 | .bind("localhost", 0); 82 | } 83 | 84 | static SslContext serverSslContext() throws Exception { 85 | return serverSslContext("localhost.p12", "localhost"); 86 | } 87 | 88 | static SslContext serverSslContext(String keystoreFile, String keystorePassword) 89 | throws Exception { 90 | SslProvider sslProvider = sslProvider(); 91 | KeyStore keyStore = KeyStore.getInstance("PKCS12"); 92 | InputStream keystoreStream = 93 | AbstractTest.class.getClassLoader().getResourceAsStream(keystoreFile); 94 | char[] keystorePasswordArray = keystorePassword.toCharArray(); 95 | keyStore.load(keystoreStream, keystorePasswordArray); 96 | 97 | KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509"); 98 | keyManagerFactory.init(keyStore, keystorePasswordArray); 99 | 100 | return SslContextBuilder.forServer(keyManagerFactory) 101 | .protocols("TLSv1.3") 102 | .sslProvider(sslProvider) 103 | .applicationProtocolConfig(alpnConfig()) 104 | .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE) 105 | .build(); 106 | } 107 | 108 | static SslContext clientSslContext() throws SSLException { 109 | return SslContextBuilder.forClient() 110 | .protocols("TLSv1.3") 111 | .sslProvider(sslProvider()) 112 | .applicationProtocolConfig(alpnConfig()) 113 | .trustManager(InsecureTrustManagerFactory.INSTANCE) 114 | .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE) 115 | .build(); 116 | } 117 | 118 | static ApplicationProtocolConfig alpnConfig() { 119 | return new ApplicationProtocolConfig( 120 | ApplicationProtocolConfig.Protocol.ALPN, 121 | ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE, 122 | ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT, 123 | ApplicationProtocolNames.HTTP_2); 124 | } 125 | 126 | static SslProvider sslProvider() { 127 | return SslProvider.OPENSSL_REFCNT; 128 | } 129 | 130 | static class WebsocketEventsHandler extends ChannelInboundHandlerAdapter { 131 | private final int orderedEventsCount; 132 | private final List orderedEvents = new ArrayList<>(); 133 | private Http2WebSocketEvent webSocketSupportedEvent; 134 | private volatile ChannelPromise orderedEventsReceived; 135 | 136 | public WebsocketEventsHandler(int orderedEventsCount) { 137 | this.orderedEventsCount = orderedEventsCount; 138 | } 139 | 140 | @Override 141 | public void handlerAdded(ChannelHandlerContext ctx) throws Exception { 142 | orderedEventsReceived = ctx.newPromise(); 143 | super.handlerAdded(ctx); 144 | } 145 | 146 | @Override 147 | public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { 148 | if (evt instanceof Http2WebSocketEvent) { 149 | /*may occur in any order relative to other events so accounted separately*/ 150 | if (evt instanceof Http2WebSocketSupportedEvent) { 151 | webSocketSupportedEvent = (Http2WebSocketEvent) evt; 152 | return; 153 | } 154 | orderedEvents.add((Http2WebSocketEvent) evt); 155 | if (orderedEvents.size() == orderedEventsCount) { 156 | orderedEventsReceived.setSuccess(); 157 | } 158 | } 159 | super.userEventTriggered(ctx, evt); 160 | } 161 | 162 | ChannelFuture eventsReceived() { 163 | return orderedEventsReceived; 164 | } 165 | 166 | public List events() { 167 | return orderedEvents; 168 | } 169 | 170 | public Http2WebSocketEvent webSocketSupportedEvent() { 171 | return webSocketSupportedEvent; 172 | } 173 | } 174 | 175 | static final class PathAcceptor implements Http2WebSocketAcceptor { 176 | private final String path; 177 | private final ChannelHandler webSocketHandler; 178 | 179 | PathAcceptor(String path, ChannelHandler webSocketHandler) { 180 | this.path = path; 181 | this.webSocketHandler = webSocketHandler; 182 | } 183 | 184 | @Override 185 | public Future accept( 186 | ChannelHandlerContext ctx, 187 | String path, 188 | List subprotocols, 189 | Http2Headers request, 190 | Http2Headers response) { 191 | if (subprotocols.isEmpty() && path.equals(this.path)) { 192 | return ctx.executor().newSucceededFuture(webSocketHandler); 193 | } 194 | return ctx.executor() 195 | .newFailedFuture( 196 | new WebSocketHandshakeException( 197 | String.format("Path not found: %s , subprotocols: %s", path, subprotocols))); 198 | } 199 | } 200 | 201 | static final class PathSubprotocolAcceptor implements Http2WebSocketAcceptor { 202 | private final ChannelHandler webSocketHandler; 203 | private final String path; 204 | private final String subprotocol; 205 | private final boolean acceptSubprotocol; 206 | 207 | public PathSubprotocolAcceptor( 208 | String path, String subprotocol, ChannelHandler webSocketHandler) { 209 | this(path, subprotocol, webSocketHandler, true); 210 | } 211 | 212 | public PathSubprotocolAcceptor( 213 | String path, 214 | String subprotocol, 215 | ChannelHandler webSocketHandler, 216 | boolean acceptSubprotocol) { 217 | this.path = path; 218 | this.subprotocol = subprotocol; 219 | this.webSocketHandler = webSocketHandler; 220 | this.acceptSubprotocol = acceptSubprotocol; 221 | } 222 | 223 | @Override 224 | public Future accept( 225 | ChannelHandlerContext ctx, 226 | String path, 227 | List subprotocols, 228 | Http2Headers request, 229 | Http2Headers response) { 230 | String subprotocol = this.subprotocol; 231 | if (path.equals(this.path) && subprotocols.contains(subprotocol)) { 232 | if (acceptSubprotocol) { 233 | Subprotocol.accept(subprotocol, response); 234 | } 235 | return ctx.executor().newSucceededFuture(webSocketHandler); 236 | } 237 | return ctx.executor() 238 | .newFailedFuture( 239 | new Http2WebSocketPathNotFoundException( 240 | String.format("Path not found: %s , subprotocols: %s", path, subprotocols))); 241 | } 242 | } 243 | } 244 | -------------------------------------------------------------------------------- /netty-websocket-http2/src/test/java/com/jauntsdn/netty/handler/codec/http2/websocketx/HeadersValidatorTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2020 - present Maksym Ostroverkhov. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.jauntsdn.netty.handler.codec.http2.websocketx; 18 | 19 | import io.netty.handler.codec.http2.DefaultHttp2Headers; 20 | import io.netty.handler.codec.http2.Http2Headers; 21 | import io.netty.util.AsciiString; 22 | import org.assertj.core.api.Assertions; 23 | import org.junit.jupiter.api.Test; 24 | 25 | public class HeadersValidatorTest { 26 | 27 | @Test 28 | void webSocketRequest() { 29 | Assertions.assertThat( 30 | Http2WebSocketProtocol.Validator.WebSocket.isValid( 31 | validWebSocketRequestHeaders(), false)) 32 | .isTrue(); 33 | } 34 | 35 | @Test 36 | void webSocketRequestWithEndStream() { 37 | Assertions.assertThat( 38 | Http2WebSocketProtocol.Validator.WebSocket.isValid( 39 | validWebSocketRequestHeaders(), true)) 40 | .isFalse(); 41 | } 42 | 43 | @Test 44 | void webSocketRequestWithEmptyScheme() { 45 | Assertions.assertThat( 46 | Http2WebSocketProtocol.Validator.WebSocket.isValid( 47 | validWebSocketRequestHeaders().scheme(asciiString("")), false)) 48 | .isFalse(); 49 | } 50 | 51 | @Test 52 | void webSocketRequestWithNonHttpScheme() { 53 | Assertions.assertThat( 54 | Http2WebSocketProtocol.Validator.WebSocket.isValid( 55 | validWebSocketRequestHeaders().scheme(asciiString("ftp")), false)) 56 | .isFalse(); 57 | } 58 | 59 | @Test 60 | void webSocketRequestWithEmptyAuthority() { 61 | Assertions.assertThat( 62 | Http2WebSocketProtocol.Validator.WebSocket.isValid( 63 | validWebSocketRequestHeaders().authority(asciiString("")), false)) 64 | .isFalse(); 65 | } 66 | 67 | @Test 68 | void webSocketRequestWithSubcomponentAuthority() { 69 | Assertions.assertThat( 70 | Http2WebSocketProtocol.Validator.WebSocket.isValid( 71 | validWebSocketRequestHeaders().authority(asciiString("test@localhost")), false)) 72 | .isFalse(); 73 | } 74 | 75 | @Test 76 | void webSocketRequestWithEmptyPath() { 77 | Assertions.assertThat( 78 | Http2WebSocketProtocol.Validator.WebSocket.isValid( 79 | validWebSocketRequestHeaders().path(asciiString("")), false)) 80 | .isFalse(); 81 | } 82 | 83 | @Test 84 | void webSocketRequestWithInvalidPseudoHeader() { 85 | Assertions.assertThat( 86 | Http2WebSocketProtocol.Validator.WebSocket.isValid( 87 | validWebSocketRequestHeaders().add(asciiString(":status"), asciiString("200")), 88 | false)) 89 | .isFalse(); 90 | } 91 | 92 | @Test 93 | void webSocketRequestWithInvalidHeader() { 94 | Assertions.assertThat( 95 | Http2WebSocketProtocol.Validator.WebSocket.isValid( 96 | validWebSocketRequestHeaders() 97 | .add(asciiString("connection"), asciiString("keep-alive")), 98 | false)) 99 | .isFalse(); 100 | } 101 | 102 | @Test 103 | void webSocketRequestWithInvalidTeHeader() { 104 | Assertions.assertThat( 105 | Http2WebSocketProtocol.Validator.WebSocket.isValid( 106 | validWebSocketRequestHeaders().add(asciiString("te"), asciiString("gzip")), false)) 107 | .isFalse(); 108 | } 109 | 110 | @Test 111 | void webSocketRequestWithValidTeHeader() { 112 | Assertions.assertThat( 113 | Http2WebSocketProtocol.Validator.WebSocket.isValid( 114 | validWebSocketRequestHeaders().add(asciiString("te"), asciiString("trailers")), 115 | false)) 116 | .isTrue(); 117 | } 118 | 119 | @Test 120 | void webSocketResponse() { 121 | Assertions.assertThat(Http2WebSocketProtocol.Validator.isValid(validResponseHeaders())) 122 | .isTrue(); 123 | } 124 | 125 | @Test 126 | void webSocketResponseWithEmptyStatus() { 127 | Assertions.assertThat( 128 | Http2WebSocketProtocol.Validator.isValid( 129 | validResponseHeaders().status(asciiString("")))) 130 | .isFalse(); 131 | } 132 | 133 | @Test 134 | void webSocketResponseWithoutStatus() { 135 | Http2Headers headers = validResponseHeaders(); 136 | headers.remove(asciiString(":status")); 137 | 138 | Assertions.assertThat(Http2WebSocketProtocol.Validator.isValid(headers)).isFalse(); 139 | } 140 | 141 | @Test 142 | void webSocketResponseAdditionalPseudoHeader() { 143 | Assertions.assertThat( 144 | Http2WebSocketProtocol.Validator.isValid(validResponseHeaders().path(asciiString("/")))) 145 | .isFalse(); 146 | } 147 | 148 | @Test 149 | void webSocketResponseUnexpectedPseudoHeader() { 150 | Http2Headers headers = validResponseHeaders(); 151 | headers.remove(asciiString(":status")); 152 | headers.path(asciiString("/")); 153 | Assertions.assertThat(Http2WebSocketProtocol.Validator.isValid(headers)).isFalse(); 154 | } 155 | 156 | @Test 157 | void httpRequest() { 158 | Assertions.assertThat( 159 | Http2WebSocketProtocol.Validator.Http.isValid(validHttpRequestHeaders(), false)) 160 | .isTrue(); 161 | Assertions.assertThat( 162 | Http2WebSocketProtocol.Validator.Http.isValid(validHttpRequestHeaders(), true)) 163 | .isTrue(); 164 | } 165 | 166 | @Test 167 | void httpRequestWithEmptyAuthority() { 168 | Assertions.assertThat( 169 | Http2WebSocketProtocol.Validator.Http.isValid( 170 | validHttpRequestHeaders().authority(asciiString("")), false)) 171 | .isFalse(); 172 | } 173 | 174 | @Test 175 | void httpRequestWithSubcomponentAuthority() { 176 | Assertions.assertThat( 177 | Http2WebSocketProtocol.Validator.Http.isValid( 178 | validHttpRequestHeaders().authority(asciiString("test@localhost")), false)) 179 | .isFalse(); 180 | } 181 | 182 | @Test 183 | void httpRequestWithEmptyMethod() { 184 | Assertions.assertThat( 185 | Http2WebSocketProtocol.Validator.Http.isValid( 186 | validHttpRequestHeaders().method(asciiString("")), false)) 187 | .isFalse(); 188 | } 189 | 190 | @Test 191 | void httpRequestWithEmptyScheme() { 192 | Assertions.assertThat( 193 | Http2WebSocketProtocol.Validator.Http.isValid( 194 | validHttpRequestHeaders().scheme(asciiString("")), false)) 195 | .isFalse(); 196 | } 197 | 198 | @Test 199 | void httpRequestWithConnectMethod() { 200 | Assertions.assertThat( 201 | Http2WebSocketProtocol.Validator.Http.isValid( 202 | validHttpRequestHeaders().method(asciiString("connect")), false)) 203 | .isFalse(); 204 | 205 | Assertions.assertThat( 206 | Http2WebSocketProtocol.Validator.Http.isValid( 207 | validHttpRequestHeaders() 208 | .method(asciiString("connect")) 209 | .scheme(asciiString("")) 210 | .path(asciiString("")), 211 | false)) 212 | .isTrue(); 213 | } 214 | 215 | @Test 216 | void httpRequestWithEmptyPath() { 217 | Assertions.assertThat( 218 | Http2WebSocketProtocol.Validator.Http.isValid( 219 | validHttpRequestHeaders().path(asciiString("")), false)) 220 | .isFalse(); 221 | } 222 | 223 | @Test 224 | void nonHttpRequestWithEmptyPath() { 225 | Assertions.assertThat( 226 | Http2WebSocketProtocol.Validator.Http.isValid( 227 | validHttpRequestHeaders().scheme(asciiString("ftp")).path(asciiString("")), false)) 228 | .isTrue(); 229 | } 230 | 231 | @Test 232 | void httpRequestWithInvalidPseudoHeader() { 233 | Assertions.assertThat( 234 | Http2WebSocketProtocol.Validator.Http.isValid( 235 | validHttpRequestHeaders().add(asciiString(":status"), asciiString("200")), false)) 236 | .isFalse(); 237 | } 238 | 239 | @Test 240 | void httpRequestWithInvalidHeader() { 241 | Assertions.assertThat( 242 | Http2WebSocketProtocol.Validator.Http.isValid( 243 | validHttpRequestHeaders().set(asciiString("connection"), asciiString("keep-alive")), 244 | false)) 245 | .isFalse(); 246 | } 247 | 248 | @Test 249 | void httpRequestWithInvalidTeHeader() { 250 | Assertions.assertThat( 251 | Http2WebSocketProtocol.Validator.Http.isValid( 252 | validHttpRequestHeaders().set(asciiString("te"), asciiString("gzip")), false)) 253 | .isFalse(); 254 | } 255 | 256 | @Test 257 | void httpRequestWithValidTeHeader() { 258 | Assertions.assertThat( 259 | Http2WebSocketProtocol.Validator.Http.isValid( 260 | validHttpRequestHeaders().set(asciiString("te"), asciiString("trailers")), false)) 261 | .isTrue(); 262 | } 263 | 264 | private static CharSequence asciiString(String s) { 265 | return AsciiString.of(s); 266 | } 267 | 268 | private static Http2Headers validWebSocketRequestHeaders() { 269 | return new DefaultHttp2Headers(false) 270 | .method(asciiString("connect")) 271 | .set(asciiString(":protocol"), asciiString("websocket")) 272 | .scheme(asciiString("https")) 273 | .authority(asciiString("localhost")) 274 | .path(asciiString("/")); 275 | } 276 | 277 | private static Http2Headers validHttpRequestHeaders() { 278 | return new DefaultHttp2Headers(false) 279 | .method(asciiString("get")) 280 | .scheme(asciiString("https")) 281 | .authority(asciiString("localhost")) 282 | .path(asciiString("/")); 283 | } 284 | 285 | private static Http2Headers validResponseHeaders() { 286 | return new DefaultHttp2Headers(false) 287 | .status(asciiString("200")) 288 | .set(asciiString("user-agent"), asciiString("test")); 289 | } 290 | } 291 | -------------------------------------------------------------------------------- /netty-websocket-http2/src/test/resources/localhost.p12: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jauntsdn/netty-websocket-http2/175e23f9f177d410f670748c453f600c2a3d311e/netty-websocket-http2/src/test/resources/localhost.p12 -------------------------------------------------------------------------------- /netty-websocket-multiprotocol/build.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2020 - present Maksym Ostroverkhov. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | plugins { 18 | id "java-library" 19 | id "maven-publish" 20 | id "signing" 21 | } 22 | 23 | description = "Netty support for multiprotocol websockets: http1, http2" 24 | 25 | dependencies { 26 | api project(":netty-websocket-http2") 27 | implementation "org.slf4j:slf4j-api" 28 | compileOnly project(":netty-websocket-http2-callbacks-codec") 29 | compileOnly "com.google.code.findbugs:jsr305" 30 | 31 | testImplementation "org.assertj:assertj-core" 32 | testImplementation "org.junit.jupiter:junit-jupiter-api" 33 | testImplementation "org.junit.jupiter:junit-jupiter-params" 34 | testImplementation project(":netty-websocket-http2-callbacks-codec") 35 | 36 | testRuntimeOnly "org.junit.jupiter:junit-jupiter-engine" 37 | testRuntimeOnly "ch.qos.logback:logback-classic" 38 | testRuntimeOnly "io.netty:netty-tcnative-classes" 39 | testRuntimeOnly "io.netty:netty-tcnative-boringssl-static::${osdetector.classifier}" 40 | } 41 | 42 | dependencyLocking { 43 | lockAllConfigurations() 44 | } 45 | 46 | tasks.named("jar") { 47 | manifest { 48 | attributes("Automatic-Module-Name": "com.jauntsdn.netty.websocket.multiprotocol") 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /netty-websocket-multiprotocol/gradle.lockfile: -------------------------------------------------------------------------------- 1 | # This is a Gradle generated file for dependency locking. 2 | # Manual edits can break the build and are not advised. 3 | # This file is expected to be part of source control. 4 | ch.qos.logback:logback-classic:1.2.13=testRuntimeClasspath 5 | ch.qos.logback:logback-core:1.2.13=testRuntimeClasspath 6 | com.google.code.findbugs:jsr305:3.0.2=compileClasspath,googleJavaFormat1.6 7 | com.google.errorprone:error_prone_annotations:2.0.18=googleJavaFormat1.6 8 | com.google.errorprone:javac-shaded:9+181-r4173-1=googleJavaFormat1.6 9 | com.google.googlejavaformat:google-java-format:1.6=googleJavaFormat1.6 10 | com.google.guava:guava:22.0=googleJavaFormat1.6 11 | com.google.j2objc:j2objc-annotations:1.1=googleJavaFormat1.6 12 | com.jauntsdn.netty:netty-websocket-http1:1.3.0=compileClasspath,testCompileClasspath,testRuntimeClasspath 13 | io.netty:netty-buffer:4.1.119.Final=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath 14 | io.netty:netty-codec-http2:4.1.119.Final=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath 15 | io.netty:netty-codec-http:4.1.119.Final=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath 16 | io.netty:netty-codec:4.1.119.Final=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath 17 | io.netty:netty-common:4.1.119.Final=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath 18 | io.netty:netty-handler:4.1.119.Final=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath 19 | io.netty:netty-resolver:4.1.119.Final=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath 20 | io.netty:netty-tcnative-boringssl-static:2.0.70.Final=testRuntimeClasspath 21 | io.netty:netty-tcnative-classes:2.0.70.Final=testRuntimeClasspath 22 | io.netty:netty-transport-native-unix-common:4.1.119.Final=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath 23 | io.netty:netty-transport:4.1.119.Final=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath 24 | net.bytebuddy:byte-buddy:1.15.11=testCompileClasspath,testRuntimeClasspath 25 | org.apiguardian:apiguardian-api:1.1.2=testCompileClasspath 26 | org.assertj:assertj-core:3.27.3=testCompileClasspath,testRuntimeClasspath 27 | org.codehaus.mojo:animal-sniffer-annotations:1.14=googleJavaFormat1.6 28 | org.junit.jupiter:junit-jupiter-api:5.11.4=testCompileClasspath,testRuntimeClasspath 29 | org.junit.jupiter:junit-jupiter-engine:5.11.4=testRuntimeClasspath 30 | org.junit.jupiter:junit-jupiter-params:5.11.4=testCompileClasspath,testRuntimeClasspath 31 | org.junit.platform:junit-platform-commons:1.11.4=testCompileClasspath,testRuntimeClasspath 32 | org.junit.platform:junit-platform-engine:1.11.4=testRuntimeClasspath 33 | org.junit:junit-bom:5.11.4=testCompileClasspath,testRuntimeClasspath 34 | org.opentest4j:opentest4j:1.3.0=testCompileClasspath,testRuntimeClasspath 35 | org.slf4j:slf4j-api:1.7.36=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath 36 | empty=annotationProcessor,testAnnotationProcessor 37 | -------------------------------------------------------------------------------- /netty-websocket-multiprotocol/src/main/java/com/jauntsdn/netty/handler/codec/websocketx/multiprotocol/MultiprotocolWebSocketServerBuilder.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 - present Maksym Ostroverkhov. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.jauntsdn.netty.handler.codec.websocketx.multiprotocol; 18 | 19 | import com.jauntsdn.netty.handler.codec.http2.websocketx.Http1WebSocketCodec; 20 | import com.jauntsdn.netty.handler.codec.http2.websocketx.WebSocketCallbacksCodec; 21 | import io.netty.channel.ChannelHandler; 22 | import io.netty.handler.codec.http.HttpDecoderConfig; 23 | import io.netty.handler.codec.http.websocketx.WebSocketDecoderConfig; 24 | import java.util.Objects; 25 | import org.slf4j.Logger; 26 | import org.slf4j.LoggerFactory; 27 | 28 | /** Builder for {@link MultiProtocolWebSocketServerHandler} */ 29 | public final class MultiprotocolWebSocketServerBuilder { 30 | private static final Logger logger = 31 | LoggerFactory.getLogger(MultiprotocolWebSocketServerBuilder.class); 32 | private static final boolean MASK_PAYLOAD = false; 33 | 34 | private String path = "/"; 35 | private String subprotocols; 36 | private WebSocketDecoderConfig webSocketDecoderConfig; 37 | private Http1WebSocketCodec webSocketCodec = Http1WebSocketCodec.DEFAULT; 38 | 39 | private MultiProtocolWebSocketServerHandler.CompressionConfig compression; 40 | private ChannelHandler handler; 41 | private HttpDecoderConfig http1Config; 42 | private MultiProtocolWebSocketServerHandler.Http2Config http2Config; 43 | private long handshakeTimeoutMillis = 10_000; 44 | private boolean isNomaskingExtension; 45 | 46 | MultiprotocolWebSocketServerBuilder() {} 47 | 48 | /** @return new {@link MultiprotocolWebSocketServerBuilder} instance */ 49 | public static MultiprotocolWebSocketServerBuilder create() { 50 | return new MultiprotocolWebSocketServerBuilder(); 51 | } 52 | 53 | /** 54 | * Configures this handler with netty's default codec for websockets processing 55 | * 56 | * @return this {@link MultiProtocolWebSocketServerHandler} instance 57 | */ 58 | public MultiprotocolWebSocketServerBuilder defaultCodec() { 59 | webSocketCodec = Http1WebSocketCodec.DEFAULT; 60 | return this; 61 | } 62 | 63 | /** 64 | * Configures this handler with jauntsdn/netty-websocket-http1 websocket codec offering 65 | * significantly higher throughput and lower per-frame heap allocation rate. 66 | * 67 | * @return this {@link MultiProtocolWebSocketServerHandler} instance 68 | */ 69 | public MultiprotocolWebSocketServerBuilder callbacksCodec() { 70 | try { 71 | webSocketCodec = WebSocketCallbacksCodec.instance(); 72 | } catch (NoClassDefFoundError e) { 73 | throw new IllegalArgumentException("websocket-http1 callbacks codec is not available", e); 74 | } 75 | return this; 76 | } 77 | 78 | /** 79 | * @param path websocket path, must start with / 80 | * @return this {@link MultiprotocolWebSocketServerBuilder} instance 81 | */ 82 | public MultiprotocolWebSocketServerBuilder path(String path) { 83 | Objects.requireNonNull(path, "path"); 84 | if (!path.startsWith("/")) { 85 | throw new IllegalArgumentException("path must be started with /"); 86 | } 87 | this.path = path; 88 | return this; 89 | } 90 | 91 | /** 92 | * @param subprotocols comma separated list of supported subprotocols 93 | * @return this {@link MultiprotocolWebSocketServerBuilder} instance 94 | */ 95 | public MultiprotocolWebSocketServerBuilder subprotocols(String subprotocols) { 96 | this.subprotocols = Objects.requireNonNull(subprotocols, "subprotocols"); 97 | return this; 98 | } 99 | 100 | /** 101 | * @param handshakeTimeoutMillis websocket handshake timeout, millis 102 | * @return this {@link MultiprotocolWebSocketServerBuilder} instance 103 | */ 104 | public MultiprotocolWebSocketServerBuilder handshakeTimeout(long handshakeTimeoutMillis) { 105 | this.handshakeTimeoutMillis = 106 | MultiProtocolWebSocketServerHandler.requirePositive( 107 | handshakeTimeoutMillis, "handshakeTimeoutMillis"); 108 | return this; 109 | } 110 | 111 | /** 112 | * @param webSocketDecoderConfig websocket decoder configuration. Must be non-null 113 | * @return this {@link MultiprotocolWebSocketServerBuilder} instance 114 | */ 115 | public MultiprotocolWebSocketServerBuilder decoderConfig( 116 | WebSocketDecoderConfig webSocketDecoderConfig) { 117 | this.webSocketDecoderConfig = 118 | Objects.requireNonNull(webSocketDecoderConfig, "webSocketDecoderConfig"); 119 | return this; 120 | } 121 | 122 | /** 123 | * @param http1Config http1 codec configuration options 124 | * @return this {@link MultiprotocolWebSocketServerBuilder} instance 125 | */ 126 | public MultiprotocolWebSocketServerBuilder http1Config(HttpDecoderConfig http1Config) { 127 | this.http1Config = Objects.requireNonNull(http1Config, "http1Config"); 128 | return this; 129 | } 130 | 131 | /** 132 | * @param http2Config http2 codec configuration options 133 | * @return this {@link MultiprotocolWebSocketServerBuilder} instance 134 | */ 135 | public MultiprotocolWebSocketServerBuilder http2Config( 136 | MultiProtocolWebSocketServerHandler.Http2Config http2Config) { 137 | this.http2Config = Objects.requireNonNull(http2Config, "http2Config"); 138 | return this; 139 | } 140 | 141 | /** 142 | * @param isCompressionEnabled enables permessage-deflate compression with default configuration 143 | * @return this {@link MultiprotocolWebSocketServerBuilder} instance 144 | */ 145 | public MultiprotocolWebSocketServerBuilder compression(boolean isCompressionEnabled) { 146 | if (isCompressionEnabled) { 147 | compression = new MultiProtocolWebSocketServerHandler.CompressionConfig(); 148 | } else { 149 | compression = null; 150 | } 151 | return this; 152 | } 153 | 154 | /** 155 | * Enables permessage-deflate compression with extended configuration. Parameters are described in 156 | * netty's PerMessageDeflateServerExtensionHandshaker 157 | * 158 | * @param compressionLevel sets compression level. Range is [0; 9], default is 6 159 | * @param allowServerWindowSize allows client to customize the server's inflater window size, 160 | * default is false 161 | * @param preferredClientWindowSize preferred client window size if client inflater is 162 | * customizable 163 | * @param allowServerNoContext allows client to activate server_no_context_takeover, default is 164 | * false 165 | * @param preferredClientNoContext whether server prefers to activate client_no_context_takeover 166 | * if client is compatible, default is false 167 | * @return this {@link MultiprotocolWebSocketServerBuilder} instance 168 | */ 169 | public MultiprotocolWebSocketServerBuilder compression( 170 | int compressionLevel, 171 | boolean allowServerWindowSize, 172 | int preferredClientWindowSize, 173 | boolean allowServerNoContext, 174 | boolean preferredClientNoContext) { 175 | compression = 176 | new MultiProtocolWebSocketServerHandler.CompressionConfig( 177 | compressionLevel, 178 | allowServerWindowSize, 179 | preferredClientWindowSize, 180 | allowServerNoContext, 181 | preferredClientNoContext); 182 | return this; 183 | } 184 | 185 | /** 186 | * @param isNomaskingExtension enables "no-masking" extension draft. 188 | * Takes precedence over masking related configuration. 189 | * @return this {@link MultiprotocolWebSocketServerBuilder} instance 190 | */ 191 | public MultiprotocolWebSocketServerBuilder nomaskingExtension(boolean isNomaskingExtension) { 192 | this.isNomaskingExtension = isNomaskingExtension; 193 | return this; 194 | } 195 | 196 | /** 197 | * @param channelHandler websocket channel handler. Must be non-null. 198 | * @return this {@link MultiprotocolWebSocketServerBuilder} instance 199 | */ 200 | public MultiprotocolWebSocketServerBuilder handler(ChannelHandler channelHandler) { 201 | this.handler = Objects.requireNonNull(channelHandler, "channelHandler"); 202 | return this; 203 | } 204 | 205 | /** @return new {@link MultiProtocolWebSocketServerHandler} instance */ 206 | public MultiProtocolWebSocketServerHandler build() { 207 | ChannelHandler webSocketHandler = handler; 208 | boolean hasCompression = compression != null; 209 | WebSocketDecoderConfig wsConfig = webSocketDecoderConfig; 210 | HttpDecoderConfig h1Config = http1Config; 211 | MultiProtocolWebSocketServerHandler.Http2Config h2Config = http2Config; 212 | Http1WebSocketCodec codec = webSocketCodec; 213 | 214 | if (wsConfig == null) { 215 | if (codec == WebSocketCallbacksCodec.DEFAULT) { 216 | wsConfig = 217 | WebSocketDecoderConfig.newBuilder() 218 | /*align with the spec and strictness of some browsers*/ 219 | .expectMaskedFrames(true) 220 | .allowMaskMismatch(false) 221 | .allowExtensions(hasCompression) 222 | .build(); 223 | } else { 224 | wsConfig = 225 | WebSocketDecoderConfig.newBuilder() 226 | .expectMaskedFrames(true) 227 | .allowMaskMismatch(true) 228 | .withUTF8Validator(false) 229 | .maxFramePayloadLength(65535) 230 | .allowExtensions(hasCompression) 231 | .build(); 232 | } 233 | } else { 234 | boolean isAllowExtensions = wsConfig.allowExtensions(); 235 | if (!isAllowExtensions && hasCompression) { 236 | wsConfig = wsConfig.toBuilder().allowExtensions(true).build(); 237 | } 238 | } 239 | codec.validate(MASK_PAYLOAD, wsConfig); 240 | 241 | return new MultiProtocolWebSocketServerHandler( 242 | codec, 243 | wsConfig, 244 | h1Config, 245 | h2Config, 246 | compression, 247 | isNomaskingExtension, 248 | path, 249 | subprotocols, 250 | handshakeTimeoutMillis, 251 | webSocketHandler); 252 | } 253 | } 254 | -------------------------------------------------------------------------------- /netty-websocket-multiprotocol/src/test/java/com/jauntsdn/netty/handler/codec/websocketx/multiprotocol/Security.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 - present Maksym Ostroverkhov. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.jauntsdn.netty.handler.codec.websocketx.multiprotocol; 18 | 19 | import io.netty.handler.codec.http2.Http2SecurityUtil; 20 | import io.netty.handler.ssl.ApplicationProtocolConfig; 21 | import io.netty.handler.ssl.ApplicationProtocolNames; 22 | import io.netty.handler.ssl.OpenSsl; 23 | import io.netty.handler.ssl.SslContext; 24 | import io.netty.handler.ssl.SslContextBuilder; 25 | import io.netty.handler.ssl.SslProvider; 26 | import io.netty.handler.ssl.SupportedCipherSuiteFilter; 27 | import io.netty.handler.ssl.util.InsecureTrustManagerFactory; 28 | import java.io.InputStream; 29 | import java.security.KeyStore; 30 | import javax.net.ssl.KeyManagerFactory; 31 | import javax.net.ssl.SSLException; 32 | 33 | public final class Security { 34 | 35 | public static SslContext serverSslContext(String keystoreFile, String keystorePassword) 36 | throws Exception { 37 | 38 | KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509"); 39 | SslProvider sslProvider = sslProvider(); 40 | KeyStore keyStore = KeyStore.getInstance("PKCS12"); 41 | 42 | InputStream keystoreStream = Security.class.getClassLoader().getResourceAsStream(keystoreFile); 43 | char[] keystorePasswordArray = keystorePassword.toCharArray(); 44 | keyStore.load(keystoreStream, keystorePasswordArray); 45 | keyManagerFactory.init(keyStore, keystorePasswordArray); 46 | 47 | return SslContextBuilder.forServer(keyManagerFactory) 48 | .protocols("TLSv1.3") 49 | .sslProvider(sslProvider) 50 | .applicationProtocolConfig(alpnConfigHttp2()) 51 | .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE) 52 | .build(); 53 | } 54 | 55 | public static SslContext clientLocalSslContextHttp2() throws SSLException { 56 | return clientSslContextBuilder().trustManager(InsecureTrustManagerFactory.INSTANCE).build(); 57 | } 58 | 59 | public static SslContext clientLocalSslContextHttp1() throws SSLException { 60 | return clientSslContextBuilder() 61 | .trustManager(InsecureTrustManagerFactory.INSTANCE) 62 | .applicationProtocolConfig(alpnConfigHttp1()) 63 | .build(); 64 | } 65 | 66 | public static SslContext clientSslContextHttp2() throws SSLException { 67 | return clientSslContextBuilder().build(); 68 | } 69 | 70 | private static SslContextBuilder clientSslContextBuilder() throws SSLException { 71 | return SslContextBuilder.forClient() 72 | .protocols("TLSv1.3") 73 | .sslProvider(sslProvider()) 74 | .applicationProtocolConfig(alpnConfigHttp2()) 75 | .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE); 76 | } 77 | 78 | private static ApplicationProtocolConfig alpnConfigHttp2() { 79 | return new ApplicationProtocolConfig( 80 | ApplicationProtocolConfig.Protocol.ALPN, 81 | ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE, 82 | ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT, 83 | ApplicationProtocolNames.HTTP_2); 84 | } 85 | 86 | private static ApplicationProtocolConfig alpnConfigHttp1() { 87 | return new ApplicationProtocolConfig( 88 | ApplicationProtocolConfig.Protocol.ALPN, 89 | ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE, 90 | ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT, 91 | ApplicationProtocolNames.HTTP_1_1); 92 | } 93 | 94 | private static SslProvider sslProvider() { 95 | final SslProvider sslProvider; 96 | if (OpenSsl.isAvailable()) { 97 | sslProvider = SslProvider.OPENSSL_REFCNT; 98 | } else { 99 | sslProvider = SslProvider.JDK; 100 | } 101 | return sslProvider; 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /netty-websocket-multiprotocol/src/test/resources/localhost.p12: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jauntsdn/netty-websocket-http2/175e23f9f177d410f670748c453f600c2a3d311e/netty-websocket-multiprotocol/src/test/resources/localhost.p12 -------------------------------------------------------------------------------- /netty-websocket-multiprotocol/src/test/resources/logback.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | %date{HH:mm:ss.SSS} %-10thread %-42logger %msg%n 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /perf_client.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | ./gradlew netty-websocket-http2-perftest:runClientMessages -------------------------------------------------------------------------------- /perf_client_bulk.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | ./gradlew netty-websocket-http2-perftest:runClientBulk -------------------------------------------------------------------------------- /perf_client_bulk_run.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | cd netty-websocket-http2-perftest/build/install/netty-websocket-http2-perftest/bin && ./netty-websocket-http2-perftest-bulk-client -------------------------------------------------------------------------------- /perf_client_callbacks.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | ./gradlew netty-websocket-http2-perftest:runClientCallbacks -------------------------------------------------------------------------------- /perf_client_callbacks_run.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | cd netty-websocket-http2-perftest/build/install/netty-websocket-http2-perftest/bin && ./netty-websocket-http2-perftest-callbacks-client -------------------------------------------------------------------------------- /perf_client_run.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | cd netty-websocket-http2-perftest/build/install/netty-websocket-http2-perftest/bin && ./netty-websocket-http2-perftest-messages-client -------------------------------------------------------------------------------- /perf_server.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | ./gradlew netty-websocket-http2-perftest:runServerMessages -------------------------------------------------------------------------------- /perf_server_bulk.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | ./gradlew netty-websocket-http2-perftest:runServerBulk -------------------------------------------------------------------------------- /perf_server_bulk_run.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | export NETTY_WEBSOCKET_HTTP2_PERFTEST_BULK_SERVER_OPTS='--add-exports java.base/sun.security.x509=ALL-UNNAMED' 4 | 5 | cd netty-websocket-http2-perftest/build/install/netty-websocket-http2-perftest/bin && ./netty-websocket-http2-perftest-bulk-server -------------------------------------------------------------------------------- /perf_server_callbacks.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | ./gradlew netty-websocket-http2-perftest:runServerCallbacks -------------------------------------------------------------------------------- /perf_server_callbacks_run.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | export NETTY_WEBSOCKET_HTTP2_PERFTEST_CALLBACKS_SERVER_OPTS='--add-exports java.base/sun.security.x509=ALL-UNNAMED' 4 | 5 | cd netty-websocket-http2-perftest/build/install/netty-websocket-http2-perftest/bin && ./netty-websocket-http2-perftest-callbacks-server -------------------------------------------------------------------------------- /perf_server_run.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | cd netty-websocket-http2-perftest/build/install/netty-websocket-http2-perftest/bin && ./netty-websocket-http2-perftest-messages-server -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2020-present the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | pluginManagement { 18 | plugins { 19 | id "com.github.sherter.google-java-format" version "${googleJavaFormatPluginVersion}" 20 | id "io.spring.dependency-management" version "${dependencyManagementPluginVersion}" 21 | id "com.palantir.git-version" version "${gitPluginVersion}" 22 | id "com.google.osdetector" version "${osDetectorPluginVersion}" 23 | id "com.github.ben-manes.versions" version "${versionsPluginVersion}" 24 | } 25 | } 26 | 27 | rootProject.name = "netty-websocket-http2-parent" 28 | include "netty-websocket-http2" 29 | include "netty-websocket-http2-callbacks-codec" 30 | include "netty-websocket-multiprotocol" 31 | include "netty-websocket-http2-example" 32 | include "netty-websocket-http2-perftest" 33 | 34 | --------------------------------------------------------------------------------