pax_global_header 0000666 0000000 0000000 00000000064 14777572271 0014535 g ustar 00root root 0000000 0000000 52 comment=99cdf0808c1411a9d5ef3497f9abe81f2b418b99
http-2-1.1.1/ 0000775 0000000 0000000 00000000000 14777572271 0012653 5 ustar 00root root 0000000 0000000 http-2-1.1.1/.github/ 0000775 0000000 0000000 00000000000 14777572271 0014213 5 ustar 00root root 0000000 0000000 http-2-1.1.1/.github/workflows/ 0000775 0000000 0000000 00000000000 14777572271 0016250 5 ustar 00root root 0000000 0000000 http-2-1.1.1/.github/workflows/ci.yml 0000664 0000000 0000000 00000003760 14777572271 0017374 0 ustar 00root root 0000000 0000000 name: CI
on:
pull_request:
branches:
- main
- master
env:
ruby_version: 3.4
jobs:
test:
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
ruby: [2.7 ,'3.0', 3.1, 3.2, 3.3, 3.4, jruby, truffleruby]
steps:
- uses: actions/checkout@v4
- name: Setup Ruby
uses: ruby/setup-ruby@v1
with:
ruby-version: ${{ matrix.ruby }}
bundler-cache: true
- name: Tests
env:
CI: 1
run: |
RUBY_VERSION=`ruby -e 'puts RUBY_VERSION'`
RUBY_PLATFORM=`ruby -e 'puts RUBY_PLATFORM'`
RUBY_ENGINE=`ruby -e 'puts RUBY_ENGINE'`
if [[ "$RUBY_ENGINE" = "ruby" ]] && [[ ${RUBY_VERSION:0:1} = "3" ]] && [[ ! $RUBYOPT =~ "jit" ]]; then
echo "running runtime type checking..."
export RUBYOPT="-rbundler/setup -rrbs/test/setup"
export RBS_TEST_RAISE="true"
export RBS_TEST_LOGLEVEL="error"
export RBS_TEST_OPT="-Isig -rbase64"
export RBS_TEST_TARGET="HTTP2*"
fi
bundle exec rake
- name: Upload coverage
uses: actions/upload-artifact@v4
with:
name: coverage-${{matrix.ruby}}
path: coverage/
include-hidden-files: true
coverage:
needs: test
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup Ruby
uses: ruby/setup-ruby@v1
with:
ruby-version: 3.3
bundler-cache: true
- name: Download coverage results
uses: actions/download-artifact@v4
with:
pattern: coverage-*
path: coverage
- name: coverage
env:
CI: 1
run: |
find coverage -name "*resultset.json" -exec sed -i 's?${{ github.workspace }}?'`pwd`'?' {} \;
bundle exec rake coverage:report
- uses: joshmfrankel/simplecov-check-action@main
with:
github_token: ${{ secrets.GITHUB_TOKEN }} http-2-1.1.1/.github/workflows/release.yml 0000664 0000000 0000000 00000001417 14777572271 0020416 0 ustar 00root root 0000000 0000000 name: Release
on:
pull_request:
types:
- closed
branches:
- main
paths:
- lib/http/2/version.rb
permissions:
contents: read
id-token: write
jobs:
release:
if: github.event.pull_request.merged == true
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up Ruby
uses: ruby/setup-ruby@v1
with:
bundler-cache: true
ruby-version: 3.4
- name: Publish to RubyGems
uses: rubygems/release-gem@v1
- name: Create GitHub release
run: |
tag_name="$(git describe --tags --abbrev=0)"
gh release create "${tag_name}" --verify-tag --draft --generate-notes pkg/*.gem
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} http-2-1.1.1/.gitignore 0000664 0000000 0000000 00000000032 14777572271 0014636 0 ustar 00root root 0000000 0000000 .idea/
Gemfile.lock
*.gem
http-2-1.1.1/.rubocop.yml 0000664 0000000 0000000 00000003236 14777572271 0015131 0 ustar 00root root 0000000 0000000 inherit_from: .rubocop_todo.yml
plugins:
- rubocop-performance
AllCops:
NewCops: enable
TargetRubyVersion: 2.7
DisplayCopNames: true
Exclude:
- 'bin/**'
- 'vendor/**/*'
- '**/huffman_statemachine.rb'
Layout/HeredocIndentation:
Exclude:
- 'lib/tasks/generate_huffman_table.rb'
- 'example/*'
Metrics/BlockLength:
Enabled: false
Metrics/PerceivedComplexity:
Enabled: false
Lint/EmptyWhen:
Enabled: false
Style/StringLiterals:
EnforcedStyle: double_quotes
Style/NumericPredicate:
Enabled: false
Gemspec/RequiredRubyVersion:
Enabled: false
Bundler/DuplicatedGem:
Enabled: false
Style/OptionalBooleanParameter:
Enabled: false
Style/ArgumentsForwarding:
Enabled: false
Lint/MissingSuper:
Exclude:
- 'lib/httpx/io/unix.rb'
Style/HashTransformValues:
Exclude:
- 'lib/httpx/plugins/digest_authentication.rb'
Lint/ConstantDefinitionInBlock:
Exclude:
- 'spec/**/*'
# TODO: remove this if min supported version of ruby is 2.3
Style/HashSyntax:
Enabled: false
Style/AndOr:
Enabled: false
Style/SafeNavigation:
Enabled: false
Naming/MethodParameterName:
Enabled: false
Naming/VariableNumber:
Exclude:
- example/server.rb
Layout/LineLength:
Max: 128
Style/HashEachMethods:
Enabled: true
Style/HashTransformKeys:
Enabled: true
Style/CommentAnnotation:
Enabled: false
Style/SlicingWithRange:
Enabled: false
Lint/SuppressedException:
Exclude:
- Rakefile
Lint/EmptyBlock:
Exclude:
- spec/*
Performance/CollectionLiteralInLoop:
Exclude:
- spec/*
Performance/MethodObjectAsBlock:
Enabled: false
Metrics/CollectionLiteralLength:
Exclude:
- lib/http/2/header/huffman.rb http-2-1.1.1/.rubocop_todo.yml 0000664 0000000 0000000 00000002041 14777572271 0016147 0 ustar 00root root 0000000 0000000 # This configuration was generated by
# `rubocop --auto-gen-config`
# on 2016-06-09 10:57:54 -0400 using RuboCop version 0.40.0.
# The point is for the user to remove these configuration records
# one by one as the offenses are removed from the code base.
# Note that changes in the inspected code, or installation of new
# versions of RuboCop, may require this file to be generated again.
# Offense count: 24
Metrics/AbcSize:
Max: 200
# Offense count: 16
Metrics/BlockNesting:
Max: 5
Exclude:
- "lib/http/2/connection.rb"
# Offense count: 5
# Configuration parameters: CountComments.
Metrics/ClassLength:
Enabled: false
Metrics/ModuleLength:
Enabled: false
# Offense count: 12
Metrics/CyclomaticComplexity:
Max: 60
# Offense count: 29
# Configuration parameters: CountComments.
Metrics/MethodLength:
Enabled: false
# Offense count: 1
# Configuration parameters: CountKeywordArgs.
Metrics/ParameterLists:
Max: 7
# Offense count: 10
Metrics/PerceivedComplexity:
Max: 50
# Offense count: 4
Style/Documentation:
Enabled: false
http-2-1.1.1/.simplecov 0000664 0000000 0000000 00000000412 14777572271 0014652 0 ustar 00root root 0000000 0000000 # frozen_string_literal: true
SimpleCov.start do
command_name "Spec"
add_filter "/.bundle/"
add_filter "/vendor/"
add_filter "/spec/"
add_filter "/lib/http/2/base64"
coverage_dir "coverage"
minimum_coverage(RUBY_ENGINE == "truffleruby" ? 85 : 90)
end
http-2-1.1.1/CHANGELOG.md 0000664 0000000 0000000 00000010062 14777572271 0014463 0 ustar 00root root 0000000 0000000 ## 1.1.1
### Bugfixes
* frame buffer was accidentally changing encoding before header packing, which raise invalid compatible encoding errors, due to usage of "String#". this was fixed by using internal `append_str´, which does not touch encoding, and calling `String.force_encoding` in case the buffer is a mutable string passed by the user.
* dup PING frame payload passed by the user; while not really resulting in invalid encoding, the change of the input string could surprise the caller, since this would be expected to be stored somewhere so the peer PING frame can be matched on receive.
### Improvements
Simplified `String#transition`, making sure it only does state machine transitions (the rest is handled outside of it).
## 1.1.0
Several changes which improved performance for the common cases. A few highlights:
* Opting into ruby 3.4 features when possible (such as `String#append_as_bytes` instead of `String#<<`)
* reducing string and array allocations on several places (connection management, frame generation, hpack header compression, etc)
* "streams recently closed" not having to regenerate the list when not necessary
## 1.0.2
### Improvements
* Freezing static tables (used for header huffman coding) correctly. This makes them shareable, which makes `http-2` usable across ractors.
* Moved buffer helpers from String refinements into mixins. Refinements impose a relevant performance penalty, unfortunately, despite its cleaner API.
## 1.0.1
### Improvements
* discard closed streams from the connection (reduces memory consumption).
### Bugfixes
* allow RST_STREAM frames to be ignored on closed streams.
* prevent already closed streams from being initialized again.
## 1.0.0
### Breaking changes
Set ruby 2.7 as the lowest supported ruby version.
There are no public API breaking changes.
### Improvements
* it passes the h2spec compliance suite.
* RBS signatures.
* ruby 3.3: Backporting required `base64` lib support (`base64` will no longer be in standard lib)
* Using the `:buffer` kwarg from `Array#pack` to reduce string allocations
* Using `#drop_while` enumerable function to drop timed out recently closed streams, which reduced the complexity of it from O(n) to O(log n), making a difference in a few benchmarks.
* optimization for header decompression of static headers.
* it was identified that traversing the static headers table for each incoming header was one of the bottlenecks, and it was O(n) for all cases where there was not an exact match. In order to circumvent this, an additional table derived from the static headers table with the header field as lookup key was created, which eliminated the main bottleneck (at the cost of roughly 1.5Kb extra).
* `HTTPX::Buffer` has been removed, and was replaced by `String` usage with an enhanced API via refinements.
* Using `String#byteslice` in significant chunks of the parsing process.
* Removed usage of `Time.now` and replaced it with monotonic time calculations.
* avoid needless header downcase calls.
* using class_eval instead of define_method for performant lookups.
* support for the ORIGIN frame.
### Bugfixes
* force-encode data payloads to ascii while creating DATA frames.
* fixed "string too short" error when reading headers with no value.
* fixed HTTP/2 trailers (particularly the case where an end-headers flag is sent before the data, and another after data, which also closes the stream, which is valid spec-wise).
* fixed comparison on callbacks when the returned value overwrite `eql?`.
* bugfix: fixed bookkeeping of recently-closed streams.
* bugfix: wrong window update accounting check causing random flow control errors.
* bugfix: allow stream to send empty end-stream DATA frame even if remote window is exhausted.
* fix: the connection window was being updated when receiving WINDOW_UPDATEs for a stream.
* bugfix: do not update connection remote window on SETTINGS frame (aka the Cloudfront issue).
* do not close stream when receiving frames from streams we've refused locally
### Chore
Removing `base64` library usage for ruby 3.3 or higher (as it's going to be removed from bundled gems).
http-2-1.1.1/Gemfile 0000664 0000000 0000000 00000001115 14777572271 0014144 0 ustar 00root root 0000000 0000000 # frozen_string_literal: true
source "https://rubygems.org"
gemspec
gem "rake", require: false
group :development do
gem "pry"
gem "pry-byebug", platform: :mri
if RUBY_VERSION >= "3.0.0"
gem "rubocop"
gem "rubocop-performance"
end
end
group :docs do
gem "yard"
end
group :test do
gem "rspec"
gem "simplecov", require: false
end
group :types do
platform :mri do
if RUBY_VERSION >= "3.0.0"
gem "rbs"
gem "steep"
gem "typeprof"
end
end
end
group :benchmark do
platform :mri do
gem "memory_profiler"
gem "singed"
end
end
http-2-1.1.1/LICENSE 0000664 0000000 0000000 00000002056 14777572271 0013663 0 ustar 00root root 0000000 0000000 MIT License
Copyright (c) 2013 Ilya Grigorik
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
http-2-1.1.1/README.md 0000664 0000000 0000000 00000025670 14777572271 0014144 0 ustar 00root root 0000000 0000000 # HTTP-2
[](http://rubygems.org/gems/http-2)
[](https://github.com/igrigorik/http-2)
Pure Ruby, framework and transport agnostic, implementation of HTTP/2 protocol and HPACK header compression with support for:
* [Binary framing](https://hpbn.co/http2/#binary-framing-layer) parsing and encoding
* [Stream multiplexing](https://hpbn.co/http2/#streams-messages-and-frames) and [prioritization](https://hpbn.co/http2/#stream-prioritization)
* Connection and stream [flow control](https://hpbn.co/http2/#flow-control)
* [Header compression](https://hpbn.co/http2/#header-compression) and [server push](https://hpbn.co/http2/#server-push)
* Connection and stream management
* And more... see [API docs](https://www.rubydoc.info/gems/http-2)
Protocol specifications:
* [Hypertext Transfer Protocol Version 2 (RFC 7540)](https://httpwg.github.io/specs/rfc7540.html)
* [HPACK: Header Compression for HTTP/2 (RFC 7541)](https://httpwg.github.io/specs/rfc7541.html)
## Getting started
```bash
$> gem install http-2
```
This implementation makes no assumptions as how the data is delivered: it could be a regular Ruby TCP socket, your custom eventloop, or whatever other transport you wish to use - e.g. ZeroMQ, [avian carriers](http://www.ietf.org/rfc/rfc1149.txt), etc.
Your code is responsible for feeding data into the parser, which performs all of the necessary HTTP/2 decoding, state management and the rest, and vice versa, the parser will emit bytes (encoded HTTP/2 frames) that you can then route to the destination. Roughly, this works as follows:
```ruby
require 'http/2'
socket = YourTransport.new
conn = HTTP2::Client.new
conn.on(:frame) {|bytes| socket << bytes }
while bytes = socket.read
conn << bytes
end
```
Checkout provided [client](example/client.rb) and [server](example/server.rb) implementations for basic examples.
### Connection lifecycle management
Depending on the role of the endpoint you must initialize either a [Client](lib/http/2/client.rb) or a [Server](lib/http/2/server.rb) object. Doing so picks the appropriate header compression / decompression algorithms and stream management logic. From there, you can subscribe to connection level events, or invoke appropriate APIs to allocate new streams and manage the lifecycle. For example:
```ruby
# - Server ---------------
server = HTTP2::Server.new
server.on(:stream) { |stream| ... } # process inbound stream
server.on(:frame) { |bytes| ... } # encoded HTTP/2 frames
server.ping { ... } # run liveness check, process pong response
server.goaway # send goaway frame to the client
# - Client ---------------
client = HTTP2::Client.new
client.on(:promise) { |stream| ... } # process push promise
stream = client.new_stream # allocate new stream
stream.headers({':method' => 'post', ...}, end_stream: false)
stream.data(payload, end_stream: true)
```
Events emitted by the connection object:
| :promise |
client role only, fires once for each new push promise |
| :stream |
server role only, fires once for each new client stream |
| :frame |
fires once for every encoded HTTP/2 frame that needs to be sent to the peer |
### Stream lifecycle management
A single HTTP/2 connection can [multiplex multiple streams](https://hpbn.co/http2/#request-and-response-multiplexing) in parallel: multiple requests and responses can be in flight simultaneously and stream data can be interleaved and prioritized. Further, the specification provides a well-defined lifecycle for each stream (see below).
The good news is, all of the stream management, and state transitions, and error checking is handled by the library. All you have to do is subscribe to appropriate events (marked with ":" prefix in diagram below) and provide your application logic to handle request and response processing.
```
+--------+
PP | | PP
,--------| idle |--------.
/ | | \
v +--------+ v
+----------+ | +----------+
| | | H | |
,---|:reserved | | |:reserved |---.
| | (local) | v | (remote) | |
| +----------+ +--------+ +----------+ |
| | :active | | :active | |
| | ,-------|:active |-------. | |
| | H / ES | | ES \ H | |
| v v +--------+ v v |
| +-----------+ | +-----------+ |
| |:half_close| | |:half_close| |
| | (remote) | | | (local) | |
| +-----------+ | +-----------+ |
| | v | |
| | ES/R +--------+ ES/R | |
| `----------->| |<-----------' |
| R | :close | R |
`-------------------->| |<--------------------'
+--------+
```
For sake of example, let's take a look at a simple server implementation:
```ruby
conn = HTTP2::Server.new
# emits new streams opened by the client
conn.on(:stream) do |stream|
stream.on(:active) { } # fires when stream transitions to open state
stream.on(:close) { } # stream is closed by client and server
stream.on(:headers) { |head| ... } # header callback
stream.on(:data) { |chunk| ... } # body payload callback
# fires when client terminates its request (i.e. request finished)
stream.on(:half_close) do
# ... generate_response
# send response
stream.headers({
":status" => 200,
"content-type" => "text/plain"
})
# split response between multiple DATA frames
stream.data(response_chunk, end_stream: false)
stream.data(last_chunk)
end
end
```
Events emitted by the [Stream object](lib/http/2/stream.rb):
| :reserved |
fires exactly once when a push stream is initialized |
| :active |
fires exactly once when the stream become active and is counted towards the open stream limit |
| :headers |
fires once for each received header block (multi-frame blocks are reassembled before emitting this event) |
| :data |
fires once for every DATA frame (no buffering) |
| :half_close |
fires exactly once when the opposing peer closes its end of connection (e.g. client indicating that request is finished, or server indicating that response is finished) |
| :close |
fires exactly once when both peers close the stream, or if the stream is reset |
| :priority |
fires once for each received priority update (server only) |
### Prioritization
Each HTTP/2 [stream has a priority value](https://hpbn.co/http2/#stream-prioritization) that can be sent when the new stream is initialized, and optionally reprioritized later:
```ruby
client = HTTP2::Client.new
default_priority_stream = client.new_stream
custom_priority_stream = client.new_stream(priority: 42)
# sometime later: change priority value
custom_priority_stream.reprioritize(32000) # emits PRIORITY frame
```
On the opposite side, the server can optimize its stream processing order or resource allocation by accessing the stream priority value (`stream.priority`).
### Flow control
Multiplexing multiple streams over the same TCP connection introduces contention for shared bandwidth resources. Stream priorities can help determine the relative order of delivery, but priorities alone are insufficient to control how the resource allocation is performed between multiple streams. To address this, HTTP/2 provides a simple mechanism for [stream and connection flow control](https://hpbn.co/http2/#flow-control).
Connection and stream flow control is handled by the library: all streams are initialized with the default window size (64KB), and send/receive window updates are automatically processed - i.e. window is decremented on outgoing data transfers, and incremented on receipt of window frames. Similarly, if the window is exceeded, then data frames are automatically buffered until window is updated.
The only thing left is for your application to specify the logic as to when to emit window updates:
```ruby
conn.buffered_amount # check amount of buffered data
conn.window # check current window size
conn.window_update(1024) # increment connection window by 1024 bytes
stream.buffered_amount # check amount of buffered data
stream.window # check current window size
stream.window_update(2048) # increment stream window by 2048 bytes
```
### Server push
An HTTP/2 server can [send multiple replies](https://hpbn.co/http2/#server-push) to a single client request. To do so, first it emits a "push promise" frame which contains the headers of the promised resource, followed by the response to the original request, as well as promised resource payloads (which may be interleaved). A simple example is in order:
```ruby
conn = HTTP2::Server.new
conn.on(:stream) do |stream|
stream.on(:headers) { |head| ... }
stream.on(:data) { |chunk| ... }
# fires when client terminates its request (i.e. request finished)
stream.on(:half_close) do
promise_header = { ':method' => 'GET',
':authority' => 'localhost',
':scheme' => 'https',
':path' => "/other_resource" }
# initiate server push stream
push_stream = nil
stream.promise(promise_header) do |push|
push.headers({...})
push_stream = push
end
# send response
stream.headers({
":status" => 200,
"content-type" => "text/plain"
})
# split response between multiple DATA frames
stream.data(response_chunk, end_stream: false)
stream.data(last_chunk)
# now send the previously promised data
push_stream.data(push_data)
end
end
```
When a new push promise stream is sent by the server, the client is notified via the `:promise` event:
```ruby
conn = HTTP2::Client.new
conn.on(:promise) do |push|
# process push stream
end
```
The client can cancel any given push stream (via `.close`), or disable server push entirely by sending the appropriate settings frame:
```ruby
client.settings(settings_enable_push: 0)
```
### Specs
To run specs:
```ruby
rake
```
### License
(MIT License) - Copyright (c) 2013-2019 Ilya Grigorik 
(MIT License) - Copyright (c) 2019 Tiago Cardoso 
http-2-1.1.1/Rakefile 0000664 0000000 0000000 00000005435 14777572271 0014327 0 ustar 00root root 0000000 0000000 # frozen_string_literal: true
require "English"
require "bundler/gem_tasks"
require "open3"
require_relative "tasks/generate_huffman_table"
RUBY_MAJOR_MINOR = RUBY_VERSION.split(".").first(2).join(".")
begin
require "rspec/core/rake_task"
RSpec::Core::RakeTask.new(:spec) do |t|
t.exclude_pattern = "./spec/hpack_test_spec.rb"
end
RSpec::Core::RakeTask.new(:hpack) do |t|
t.pattern = "./spec/hpack_test_spec.rb"
end
rescue LoadError
end
begin
require "rubocop/rake_task"
desc "Run rubocop"
RuboCop::RakeTask.new
rescue LoadError
end
begin
require "yard"
YARD::Rake::YardocTask.new
rescue LoadError
end
namespace :coverage do
desc "Aggregates coverage reports"
task :report do
return unless ENV.key?("CI")
require "simplecov"
puts Dir["coverage/**/.resultset.json"].inspect
SimpleCov.collate Dir["coverage/**/.resultset.json"]
end
end
desc "install h2spec"
task :h2spec_install do
platform = case RUBY_PLATFORM
when /darwin/
"h2spec_darwin_amd64.tar.gz"
when /cygwin|mswin|mingw|bccwin|wince|emx/
"h2spec_windows_amd64.zip"
else
"h2spec_linux_amd64.tar.gz"
end
# uri = "https://github.com/summerwind/h2spec/releases/download/v2.3.0/#{platform}"
tar_location = File.join(__dir__, "h2spec-releases", platform)
# require "net/http"
# File.open(tar_location, "wb") do |file|
# response = nil
# loop do
# uri = URI(uri)
# http = Net::HTTP.new(uri.host, uri.port)
# http.use_ssl = true
# # http.set_debug_output($stderr)
# response = http.get(uri.request_uri)
# break unless response.is_a?(Net::HTTPRedirection)
# uri = response["location"]
# end
# file.write(response.body)
# end
case RUBY_PLATFORM
when /cygwin|mswin|mingw|bccwin|wince|emx/
puts "Hi, you're on Windows, please unzip this file: #{tar_location}"
when /darwin/
system("gunzip -c #{tar_location} | tar -xvzf -")
else
system("tar -xvzf #{tar_location} h2spec")
end
# FileUtils.rm(tar_location)
end
desc "run h2spec"
task :h2spec do
h2spec = File.join(__dir__, "h2spec")
unless File.exist?(h2spec)
abort 'Please install h2spec first.\n' \
'Run "rake h2spec_install",\n' \
"Or Download the binary from https://github.com/summerwind/h2spec/releases"
end
server_pid = Process.spawn("ruby example/server.rb -p 9000", out: File::NULL)
sleep RUBY_ENGINE == "ruby" ? 5 : 20
system("#{h2spec} -p 9000 -o 2 --strict")
Process.kill("TERM", server_pid)
exit($CHILD_STATUS.exitstatus)
end
default_tasks = %i[spec]
default_tasks << :rubocop if defined?(RuboCop) && RUBY_ENGINE == "ruby"
default_tasks += %i[h2spec_install h2spec] if ENV.key?("CI")
task default: default_tasks
task all: %i[default hpack]
http-2-1.1.1/benchmarks/ 0000775 0000000 0000000 00000000000 14777572271 0014770 5 ustar 00root root 0000000 0000000 http-2-1.1.1/benchmarks/client_server.rb 0000664 0000000 0000000 00000010260 14777572271 0020160 0 ustar 00root root 0000000 0000000 # frozen_string_literal: true
require "uri"
require "http/2"
DEBUG = ENV.key?("DEBUG")
BENCHMARK = ENV.fetch("BENCH", "profile")
ITERATIONS = 5000
METHOD = "GET"
BODY = "bang"
URL = URI.parse(ARGV[0] || "http://localhost:8080/")
CLIENT = HTTP2::Client.new
SERVER = HTTP2::Server.new
CLIENT_BUFFER = "".b
SERVER_BUFFER = "".b
def log
return unless DEBUG
puts yield
end
log { "build client..." }
CLIENT.on(:frame) do |bytes|
log { "(client) sending bytes: #{bytes.size}" }
CLIENT_BUFFER << bytes
end
CLIENT.on(:frame_sent) do |frame|
log { "(client) Sent frame: #{frame.inspect}" }
end
CLIENT.on(:frame_received) do |frame|
log { "(client) Received frame: #{frame.inspect}" }
end
CLIENT.on(:altsvc) do |f|
log { "(client) received ALTSVC #{f}" }
end
log { "build server..." }
SERVER.on(:frame) do |bytes|
log { "(server) sending bytes: #{bytes.bytesize}" }
SERVER_BUFFER << bytes
end
SERVER.on(:frame_sent) do |frame|
log { "(server) Sent frame: #{frame.inspect}" }
end
SERVER.on(:frame_received) do |frame|
log { "(server) Received frame: #{frame.inspect}" }
end
SERVER.on(:goaway) do
log { "(server) goaway received" }
end
SERVER.on(:stream) do |stream|
req = {}
buffer = "".b
stream.on(:active) { log { "(server stream:#{stream.id}) client opened new stream" } }
stream.on(:close) { log { "(server stream:#{stream.id}) stream closed" } }
stream.on(:headers) do |h|
log { "(server stream:#{stream.id}) request headers: #{Hash[*h.flatten]}" }
end
stream.on(:data) do |d|
log { "(server stream:#{stream.id}) payload chunk: <<#{d}>>" }
buffer << d
end
stream.on(:half_close) do
log { "(server stream:#{stream.id}) client closed its end of the stream" }
response = nil
if req[":method"] == "POST"
log { "(server stream:#{stream.id}) Received POST request, payload: #{buffer}" }
response = "(server stream:#{stream.id}) Hello HTTP 2.0! POST payload: #{buffer}"
else
log { "Received GET request" }
response = "(server stream:#{stream.id}) Hello HTTP 2.0! GET request"
end
stream.headers(
{
":status" => "200",
"content-length" => response.bytesize.to_s,
"content-type" => "text/plain",
"x-stream-id" => "stream-#{stream.id}"
}, end_stream: false
)
# split response into multiple DATA frames
stream.data(response[0, 5], end_stream: false)
stream.data(response[5, -1] || "")
end
end
def send_request
stream = CLIENT.new_stream
stream.on(:close) do
log { "(client stream:#{stream.id}) stream closed" }
end
stream.on(:half_close) do
log { "(client stream:#{stream.id}) closing client-end of the stream" }
end
stream.on(:headers) do |h|
log { "(client stream:#{stream.id}) response headers: #{h}" }
end
stream.on(:data) do |d|
log { "(client stream:#{stream.id}) response data chunk: <<#{d}>>" }
end
stream.on(:altsvc) do |f|
log { "(client stream:#{stream.id}) received ALTSVC #{f}" }
end
head = {
":scheme" => URL.scheme,
":method" => METHOD,
":authority" => [URL.host, URL.port].join(":"),
":path" => URL.path,
"accept" => "*/*"
}
log { "Sending HTTP 2.0 request" }
if head[":method"] == "GET"
stream.headers(head, end_stream: true)
else
stream.headers(head, end_stream: false)
stream.data(BODY)
end
until CLIENT_BUFFER.empty? && SERVER_BUFFER.empty?
unless CLIENT_BUFFER.empty?
SERVER << CLIENT_BUFFER
CLIENT_BUFFER.clear
end
unless SERVER_BUFFER.empty?
CLIENT << SERVER_BUFFER
SERVER_BUFFER.clear
end
end
end
def benchmark(bench_type, &block)
return yield if DEBUG
case bench_type
when "profile"
require "singed"
Singed.output_directory = "tmp/"
flamegraph(&block)
when "memory"
require "memory_profiler"
MemoryProfiler.report(allow_files: ["lib/http/2"], &block).pretty_print
when "benchmark"
require "benchmark"
puts Benchmark.measure(&block)
end
end
GC.start
GC.disable
puts "warmup..."
ITERATIONS.times do
# start client stream
send_request
end
puts "bench!"
# Benchmark.bmbm do |x|
benchmark(BENCHMARK) do
ITERATIONS.times do
# start client stream
send_request
end
CLIENT.goaway
end
http-2-1.1.1/example/ 0000775 0000000 0000000 00000000000 14777572271 0014306 5 ustar 00root root 0000000 0000000 http-2-1.1.1/example/Gemfile 0000664 0000000 0000000 00000000123 14777572271 0015575 0 ustar 00root root 0000000 0000000 # frozen_string_literal: true
source "https://rubygems.org"
gem "http_parser.rb"
http-2-1.1.1/example/README.md 0000664 0000000 0000000 00000002212 14777572271 0015562 0 ustar 00root root 0000000 0000000 ## Interop
First, a quick test to ensure that we can talk to ourselves:
```bash
# Direct connection
$> ruby server.rb
$> ruby client.rb http://localhost:8080/ # GET
$> ruby client.rb http://localhost:8080/ -d 'some data' # POST
# Server push
$> ruby server.rb --push
$> ruby client.rb http://localhost:8080/ # GET
# TLS + NPN negotiation
$> ruby server.rb --secure
$> ruby client.rb https://localhost:8080/ # GET
$> ...
```
### [nghttp2](https://github.com/tatsuhiro-t/nghttp2) (HTTP/2.0 C Library)
Public test server: http://106.186.112.116 (Upgrade + Direct)
```bash
# Direct request (http-2 > nghttp2)
$> ruby client.rb http://106.186.112.116/
# TLS + NPN request (http-2 > nghttp2)
$> ruby client.rb https://106.186.112.116/
# Direct request (nghttp2 > http-2)
$> ruby server.rb
$> nghttp -vnu http://localhost:8080 # Direct request to Ruby server
```
### Twitter (Java server)
```bash
# NPN + GET request (http-2 > twitter)
$> ruby client.rb https://twitter.com/
```
For a complete list of current implementations, see [http2 wiki](https://github.com/http2/http2-spec/wiki/Implementations).
http-2-1.1.1/example/client.rb 0000664 0000000 0000000 00000005372 14777572271 0016120 0 ustar 00root root 0000000 0000000 # frozen_string_literal: true
require_relative "helper"
options = {}
OptionParser.new do |opts|
opts.banner = "Usage: client.rb [options]"
opts.on("-d", "--data [String]", "HTTP payload") do |v|
options[:payload] = v
end
end.parse!
uri = URI.parse(ARGV[0] || "http://localhost:8080/")
tcp = TCPSocket.new(uri.host, uri.port)
sock = nil
if uri.scheme == "https"
ctx = OpenSSL::SSL::SSLContext.new
ctx.verify_mode = OpenSSL::SSL::VERIFY_NONE
# For ALPN support, Ruby >= 2.3 and OpenSSL >= 1.0.2 are required
ctx.alpn_protocols = [DRAFT]
ctx.alpn_select_cb = lambda do |protocols|
puts "ALPN protocols supported by server: #{protocols}"
DRAFT if protocols.include? DRAFT
end
sock = OpenSSL::SSL::SSLSocket.new(tcp, ctx)
sock.sync_close = true
sock.hostname = uri.hostname
sock.connect
if sock.alpn_protocol != DRAFT
puts "Failed to negotiate #{DRAFT} via ALPN"
exit
end
else
sock = tcp
end
conn = HTTP2::Client.new
stream = conn.new_stream
log = Logger.new(stream.id)
conn.on(:frame) do |bytes|
# puts "Sending bytes: #{bytes.unpack("H*").first}"
sock.print bytes
sock.flush
end
conn.on(:frame_sent) do |frame|
puts "Sent frame: #{frame.inspect}"
end
conn.on(:frame_received) do |frame|
puts "Received frame: #{frame.inspect}"
end
conn.on(:promise) do |promise|
promise.on(:promise_headers) do |h|
log.info "promise request headers: #{h}"
end
promise.on(:headers) do |h|
log.info "promise headers: #{h}"
end
promise.on(:data) do |d|
log.info "promise data chunk: <<#{d.size}>>"
end
end
conn.on(:altsvc) do |f|
log.info "received ALTSVC #{f}"
end
stream.on(:close) do
log.info "stream closed"
conn.goaway
end
stream.on(:half_close) do
log.info "closing client-end of the stream"
end
stream.on(:headers) do |h|
log.info "response headers: #{h}"
end
stream.on(:data) do |d|
log.info "response data chunk: <<#{d}>>"
end
stream.on(:altsvc) do |f|
log.info "received ALTSVC #{f}"
end
head = {
":scheme" => uri.scheme,
":method" => (options[:payload].nil? ? "GET" : "POST"),
":authority" => [uri.host, uri.port].join(":"),
":path" => uri.path,
"accept" => "*/*"
}
puts "Sending HTTP 2.0 request"
if head[":method"] == "GET"
stream.headers(head, end_stream: true)
else
stream.headers(head, end_stream: false)
stream.data(options[:payload])
end
require "memory_profiler"
report = MemoryProfiler.report(allow_files: "http-2") do
while !sock.closed? && !sock.eof?
data = sock.read_nonblock(1024)
# puts "Received bytes: #{data.unpack("H*").first}"
begin
conn << data
rescue StandardError => e
puts "#{e.class} exception: #{e.message} - closing socket."
e.backtrace.each { |l| puts "\t#{l}" }
sock.close
end
end
end
report.pretty_print
http-2-1.1.1/example/helper.rb 0000664 0000000 0000000 00000001006 14777572271 0016107 0 ustar 00root root 0000000 0000000 # frozen_string_literal: true
$LOAD_PATH << "lib" << "../lib"
require "optparse"
require "socket"
require "openssl"
require "uri"
# This will enable coverage within the CI environment
if ENV.key?("CI")
require "simplecov"
SimpleCov.command_name "#{RUBY_ENGINE}-#{RUBY_VERSION}-h2spec"
SimpleCov.coverage_dir "coverage/#{RUBY_ENGINE}-#{RUBY_VERSION}-h2spec"
end
require "http/2"
DRAFT = "h2"
class Logger
def initialize(id)
@id = id
end
def info(msg)
puts "[Stream #{@id}]: #{msg}"
end
end
http-2-1.1.1/example/keys/ 0000775 0000000 0000000 00000000000 14777572271 0015261 5 ustar 00root root 0000000 0000000 http-2-1.1.1/example/keys/server.crt 0000664 0000000 0000000 00000002214 14777572271 0017300 0 ustar 00root root 0000000 0000000 -----BEGIN CERTIFICATE-----
MIIDLjCCAhYCCQDIZ/9hq/2pXjANBgkqhkiG9w0BAQUFADBZMQswCQYDVQQGEwJB
VTETMBEGA1UECBMKU29tZS1TdGF0ZTEhMB8GA1UEChMYSW50ZXJuZXQgV2lkZ2l0
cyBQdHkgTHRkMRIwEAYDVQQDEwlsb2NhbGhvc3QwHhcNMTYwNjA2MTk0MzI1WhcN
MTcwNjA2MTk0MzI1WjBZMQswCQYDVQQGEwJBVTETMBEGA1UECBMKU29tZS1TdGF0
ZTEhMB8GA1UEChMYSW50ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMRIwEAYDVQQDEwls
b2NhbGhvc3QwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCjFXrWqtRZ
EMOO/o6AxGbgDYMgg/7uxCFQJM5Z6C4II6D8V94FDyCd+J0LOK2hB+QUdFqpA1S9
6RW2MvIwdvRt03RJMgbfcUF0+w4ZItv2xrW9waCfCmLSRDZgcSATacEF6u9p2Vs+
o4J/cHacirSwjy4+m94CgkxtUFGtGcJaFqAZ6Cdj5WvQdJSiAI3x3gNC/UGA+5dL
sp8+vwWx+/TMc6nDBmoRW3GHeG/NApQSh01w3wDv0FmUaFQlA5WPya/Js+CyuYh1
miXbQJEjDnGGaJjnoyRAQpPrk72Jj+bnfOu9kxpzkuLJOsbaofRFkM+/Ar5U+bQz
uU0ErQ8Ih8MPAgMBAAEwDQYJKoZIhvcNAQEFBQADggEBACL8HkKjW8kWLlW4TE5K
EcfsBad2Ah5ugTocJ/pLnr/YEo8uD91gECDtsuFTXul9n2M7U5jJmzbHZ63cjyC3
lb1BxJxUL7aIyaL61IMMcIJMWhC9VGnFUshMDNVBhuRkKs/QvaMD5KefKN1E9I2M
mZ72Yww0VihYwNOu3MTn8gUuy9eU6k/gTYPY7PJVh18QmR+Fs2MaaPp+bDwxiqML
0o2I6+0ZsqM3vFtcUjxjRASV5s+JkM34pTWFwUOl7TZv1YsxCKSz4f0BXDImZEvU
rwqFdlELp5WOG9LJsrszDRbf1wbFUsG1XXZpIBiWo3d6pOiIyRKrak1vKViNfYvI
W30=
-----END CERTIFICATE-----
http-2-1.1.1/example/keys/server.key 0000664 0000000 0000000 00000003217 14777572271 0017304 0 ustar 00root root 0000000 0000000 -----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEAoxV61qrUWRDDjv6OgMRm4A2DIIP+7sQhUCTOWeguCCOg/Ffe
BQ8gnfidCzitoQfkFHRaqQNUvekVtjLyMHb0bdN0STIG33FBdPsOGSLb9sa1vcGg
nwpi0kQ2YHEgE2nBBervadlbPqOCf3B2nIq0sI8uPpveAoJMbVBRrRnCWhagGegn
Y+Vr0HSUogCN8d4DQv1BgPuXS7KfPr8Fsfv0zHOpwwZqEVtxh3hvzQKUEodNcN8A
79BZlGhUJQOVj8mvybPgsrmIdZol20CRIw5xhmiY56MkQEKT65O9iY/m53zrvZMa
c5LiyTrG2qH0RZDPvwK+VPm0M7lNBK0PCIfDDwIDAQABAoIBAQCZShphZsccRJ6c
bPdDX9iW5vyG9qsMgPwTGdWAOrXx3pN2PZ0pwjNVaRcsMgU6JHGlLEz/Kmtf6pQG
41I0bcuI48Yc+tHs+sadD1IMHHEHP3Yau8KfWyLSI129Pvf4Z2IQjuik5LJYaVbD
NNG4iMQYZS0Bmn6Oey0dXu62t0ywYa0qvbIDse/RmjTQSTipuvGg8/QEAeRGABv8
Nd4Esya0zuxk6hGaNp3hkjyRkeoC7RsBVJbFSnp6gSubPdXwrJyHfySKe9jvrDG3
Q/AzyHUh/6EODd5n66x0p6rq7oo9/PnLvZJY8jIGWG+aEp68RJyEgimrwll0rAWw
/buqijGRAoGBANimL8407fFirmct7BceavaeJfXPK5yWiOhVX0XlJ0phAFuaAxK3
5HVT7DD+KKV66g1jtS9FUVZGDiYFHlsdsYuHVYcRmr0h5rZr941obrDwNrM9Nf9C
0uehN5+n/FaeGoQLR3V4THoP3rlkYTlLpQnI5mKA19JukXnIiJM9ARUZAoGBAMC0
mcVsVuSKSFwURtQHHIufxL6SqC2kLTwIQ7exqejNYPCqCiif+ZWOmsTqbVGAGbMK
Ohak4oLwN5IGCl4jNQG+vWagREkx6OXSk5NYcfoNBrOm+0UoFRzoEA85s7Dy6PuD
tBucNZpt1sGauzkCSx7C8jj4ZlSwkv0XhBFfbTZnAoGBAK2wBjF+U6iq4YFM2rLq
KvzOa0Z3MdKXCOmiz//cKDTEMaI+heoyzZCWmIvqpzGLqirT3gUowH23Kk6m2eBY
nOdst0/S+Eha7nkfc9bFe8CUxHXMRAcCTs1ufYadCXtzw3RLCp4NtNpC8N+Wry9d
CtIeYz1jaCOHi0+kSoIobT65AoGAc6hxWkJp7ITqZQlucTdLdKmRheeztKEC3TMA
obGqDqWldww3SKarP431ahZhQjcmNYT/1DNmF7xhPe0OL+3llISMXJn4Ig4ogDdg
h2DgF3nV+eFQkfM6qLzHVrwFE0DXgI1NffzFV0hxSoW5tL+honbStkqv8EiCEBEb
HOovPCUCgYBpXuPARd2ycInAulVHijJmj2rmK7f41ZhVCWovYjcCWyeJyLIO7j+b
MBJZbmwpStJhEjW64nE2zZGWg2HCBbvZz5/SXIr3fp7qVXwpn1TvB/TJDf43t0oF
3caLgyQYoQCsVHKT3cU4s3wuog/DyHKh9FtRkcJrEy7h9Rrc+ModbA==
-----END RSA PRIVATE KEY-----
http-2-1.1.1/example/raw.rb 0000664 0000000 0000000 00000000421 14777572271 0015421 0 ustar 00root root 0000000 0000000 # frozen_string_literal: true
require "socket"
puts "Starting server on port 9000"
server = TCPServer.new(9000)
loop do
sock = server.accept
puts sock.readpartial(1024).inspect while !sock.closed? && !(begin
sock.eof?
rescue StandardError
true
end)
end
http-2-1.1.1/example/server.rb 0000664 0000000 0000000 00000007440 14777572271 0016146 0 ustar 00root root 0000000 0000000 # frozen_string_literal: true
require_relative "helper"
options = { port: 8080 }
OptionParser.new do |opts|
opts.banner = "Usage: server.rb [options]"
opts.on("-s", "--secure", "HTTPS mode") do |v|
options[:secure] = v
end
opts.on("-p", "--port [Integer]", "listen port") do |v|
options[:port] = v
end
opts.on("-u", "--push", "Push message") do |_v|
options[:push] = true
end
end.parse!
puts "Starting server on port #{options[:port]}"
server = TCPServer.new(options[:port])
if options[:secure]
ctx = OpenSSL::SSL::SSLContext.new
ctx.cert = OpenSSL::X509::Certificate.new(File.open("keys/server.crt"))
ctx.key = OpenSSL::PKey::RSA.new(File.open("keys/server.key"))
ctx.ssl_version = :TLSv1_2
ctx.options = OpenSSL::SSL::SSLContext::DEFAULT_PARAMS[:options]
ctx.ciphers = OpenSSL::SSL::SSLContext::DEFAULT_PARAMS[:ciphers]
ctx.alpn_protocols = ["h2"]
ctx.alpn_select_cb = lambda do |protocols|
raise "Protocol #{DRAFT} is required" if protocols.index(DRAFT).nil?
DRAFT
end
ctx.ecdh_curves = "P-256"
server = OpenSSL::SSL::SSLServer.new(server, ctx)
end
loop do
sock = server.accept
sock.setsockopt(:SOCKET, :RCVBUF, 2048)
puts "New TCP connection!"
conn = HTTP2::Server.new
conn.on(:frame) do |bytes|
# puts "Writing bytes: #{bytes.unpack("H*").first}"
sock.write(bytes) unless sock.closed?
end
conn.on(:frame_sent) do |frame|
puts "Sent frame: #{frame.inspect}"
end
conn.on(:frame_received) do |frame|
puts "Received frame: #{frame.inspect}"
end
conn.on(:goaway) do
Thread.start do
sleep(1)
sock.close
end
end
conn.on(:stream) do |stream|
log = Logger.new(stream.id)
req = {}
buffer = "".b
stream.on(:active) { log.info "client opened new stream" }
stream.on(:close) { log.info "stream closed" }
stream.on(:headers) do |h|
req = Hash[*h.flatten]
log.info "request headers: #{h}"
end
stream.on(:data) do |d|
log.info "payload chunk: <<#{d}>>"
buffer << d
end
stream.on(:half_close) do
log.info "client closed its end of the stream"
response = nil
if req[":method"] == "POST"
log.info "Received POST request, payload: #{buffer}"
response = "Hello HTTP 2.0! POST payload: #{buffer}"
else
log.info "Received GET request"
response = "Hello HTTP 2.0! GET request"
end
stream.headers({
":status" => "200",
"content-length" => response.bytesize.to_s,
"content-type" => "text/plain"
}, end_stream: false)
if options[:push]
push_streams = []
# send 10 promises
10.times do |i|
puts "sending push"
head = { ":method" => "GET",
":authority" => "localhost",
":scheme" => "https",
":path" => "/other_resource/#{i}" }
stream.promise(head) do |push|
push.headers({ ":status" => "200", "content-type" => "text/plain", "content-length" => "11" })
push_streams << push
end
end
end
# split response into multiple DATA frames
stream.data(response[0, 5], end_stream: false)
stream.data(response[5, -1] || "")
if options[:push]
push_streams.each_with_index do |push, i|
sleep 1
push.data("push_data #{i}")
end
end
end
end
while !sock.closed? && !(sock.eof? rescue true) # rubocop:disable Style/RescueModifier
# puts "Received bytes: #{data.unpack("H*").first}"
data = sock.readpartial(16_384)
begin
conn << data
rescue StandardError => e
puts "#{e.class} exception: #{e.message} - closing socket."
puts e.backtrace
sock.close
end
end
end
http-2-1.1.1/example/upgrade_client.rb 0000664 0000000 0000000 00000006144 14777572271 0017625 0 ustar 00root root 0000000 0000000 # frozen_string_literal: true
require_relative "helper"
require "http_parser"
OptionParser.new do |opts|
opts.banner = "Usage: upgrade_client.rb [options]"
end.parse!
uri = URI.parse(ARGV[0] || "http://localhost:8080/")
sock = TCPSocket.new(uri.host, uri.port)
conn = HTTP2::Client.new
def request_header_hash
Hash.new do |hash, key|
k = key.to_s.downcase
k.tr! "_", "-"
_, value = hash.find { |header_key, _| header_key.downcase == k }
hash[key] = value if value
end
end
conn.on(:frame) do |bytes|
sock.print bytes
sock.flush
end
conn.on(:frame_sent) do |frame|
puts "Sent frame: #{frame.inspect}"
end
conn.on(:frame_received) do |frame|
puts "Received frame: #{frame.inspect}"
end
# upgrader module
class UpgradeHandler
UPGRADE_REQUEST = <>"
end
stream.on(:altsvc) do |f|
log.info "received ALTSVC #{f}"
end
@conn.on(:promise) do |promise|
promise.on(:headers) do |h|
log.info "promise headers: #{h}"
end
promise.on(:data) do |d|
log.info "promise data chunk: <<#{d.size}>>"
end
end
@conn.on(:altsvc) do |f|
log.info "received ALTSVC #{f}"
end
end
end
uh = UpgradeHandler.new(conn, sock)
puts "Sending HTTP/1.1 upgrade request"
uh.request(uri)
while !sock.closed? && !sock.eof?
data = sock.read_nonblock(1024)
begin
if (!uh.parsing && !uh.complete) ||
(uh.parsing && !uh.complete)
uh << data
elsif uh.complete
conn << data
end
rescue StandardError => e
puts "#{e.class} exception: #{e.message} - closing socket."
e.backtrace.each { |l| puts "\t#{l}" }
conn.close
sock.close
end
end
http-2-1.1.1/example/upgrade_server.rb 0000664 0000000 0000000 00000011561 14777572271 0017654 0 ustar 00root root 0000000 0000000 # frozen_string_literal: true
require_relative "helper"
require "http_parser"
options = { port: 8080 }
OptionParser.new do |opts|
opts.banner = "Usage: server.rb [options]"
opts.on("-s", "--secure", "HTTPS mode") do |v|
options[:secure] = v
end
opts.on("-p", "--port [Integer]", "listen port") do |v|
options[:port] = v
end
end.parse!
puts "Starting server on port #{options[:port]}"
server = TCPServer.new(options[:port])
if options[:secure]
ctx = OpenSSL::SSL::SSLContext.new
ctx.cert = OpenSSL::X509::Certificate.new(File.open("keys/server.crt"))
ctx.key = OpenSSL::PKey::RSA.new(File.open("keys/server.key"))
ctx.npn_protocols = [DRAFT]
server = OpenSSL::SSL::SSLServer.new(server, ctx)
end
def request_header_hash
Hash.new do |hash, key|
k = key.to_s.downcase
k.tr! "_", "-"
_, value = hash.find { |header_key, _| header_key.downcase == k }
hash[key] = value if value
end
end
class UpgradeHandler
VALID_UPGRADE_METHODS = %w[GET OPTIONS].freeze
UPGRADE_RESPONSE = < "http",
":method" => @parser.http_method,
":authority" => headers["Host"],
":path" => @parser.request_url
}.merge(headers)
@conn.upgrade(settings, request, @body)
end
def complete!
@complete = true
end
def on_headers_complete(headers)
@headers.merge! headers
end
def on_body(chunk)
@body << chunk
end
def on_message_complete
raise unless VALID_UPGRADE_METHODS.include?(@parser.http_method)
@parsing = false
complete!
end
end
loop do
sock = server.accept
puts "New TCP connection!"
conn = HTTP2::Server.new
conn.on(:frame) do |bytes|
# puts "Writing bytes: #{bytes.unpack("H*").first}"
sock.write bytes
end
conn.on(:frame_sent) do |frame|
puts "Sent frame: #{frame.inspect}"
end
conn.on(:frame_received) do |frame|
puts "Received frame: #{frame.inspect}"
end
conn.on(:stream) do |stream|
log = Logger.new(stream.id)
req = request_header_hash
buffer = ""
stream.on(:active) { log.info "client opened new stream" }
stream.on(:close) do
log.info "stream closed"
end
stream.on(:headers) do |h|
req.merge! Hash[*h.flatten]
log.info "request headers: #{h}"
end
stream.on(:data) do |d|
log.info "payload chunk: <<#{d}>>"
buffer << d
end
stream.on(:half_close) do
log.info "client closed its end of the stream"
if req["Upgrade"]
log.info "Processing h2c Upgrade request: #{req}"
if req[":method"] != "OPTIONS" # Don't respond to OPTIONS...
response = "Hello h2c world!"
stream.headers({
":status" => "200",
"content-length" => response.bytesize.to_s,
"content-type" => "text/plain"
}, end_stream: false)
stream.data(response)
end
else
response = nil
if req[":method"] == "POST"
log.info "Received POST request, payload: #{buffer}"
response = "Hello HTTP 2.0! POST payload: #{buffer}"
else
log.info "Received GET request"
response = "Hello HTTP 2.0! GET request"
end
stream.headers({
":status" => "200",
"content-length" => response.bytesize.to_s,
"content-type" => "text/plain"
}, end_stream: false)
# split response into multiple DATA frames
stream.data(response.slice!(0, 5), end_stream: false)
stream.data(response)
end
end
end
uh = UpgradeHandler.new(conn, sock)
while !sock.closed? && !(sock.eof? rescue true) # rubocop:disable Style/RescueModifier
data = sock.readpartial(1024)
# puts "Received bytes: #{data.unpack("H*").first}"
begin
if !uh.parsing && !uh.complete
if data.start_with?(*UpgradeHandler::VALID_UPGRADE_METHODS)
uh << data
else
uh.complete!
conn << data
end
elsif uh.parsing && !uh.complete
uh << data
elsif uh.complete
conn << data
end
rescue StandardError => e
puts "Exception: #{e}, #{e.message} - closing socket."
puts e.backtrace.last(10).join("\n")
sock.close
end
end
end
# echo foo=bar | nghttp -d - -t 0 -vu http://127.0.0.1:8080/
# nghttp -vu http://127.0.0.1:8080/
http-2-1.1.1/h2spec-releases/ 0000775 0000000 0000000 00000000000 14777572271 0015640 5 ustar 00root root 0000000 0000000 http-2-1.1.1/h2spec-releases/h2spec_darwin_amd64.tar.gz 0000664 0000000 0000000 00020512720 14777572271 0022523 0 ustar 00root root 0000000 0000000 8_ |SU86%@*ڪ6B5^4բUP
RiEAZ>c28_gQfTdq邴JQAG}1*t;^^Ҵ8})y˽{gWzEْy̫Ə7q;jqث;n+^iɴw`Esf/T\f_\<{e㕃b%%=ɤ'vp :}"σ? f*șwGM7va% 3=pzE3+{M0_p+wEugf>nU奄/IΚtٮKOz
/߬Ye+YpV=^ͷ^jvKwŒy{O|}ݟsה2G{71`Ƈp4oI{U]c҉rs^$8տI"09.dq,{!~Pe%]Y8<)ICcUej~Vtg~[vxsʢcHLp^ՀvoC1-'x'8'm97M8Z]4XD?O[G=uysg͞3geBtSv!Mc:_dEkznw%9Xxj!_%_,b͗}₳cϝ3xXx^D@2:[Xoo 6/>?ݗG`:%Ƹ˖Y`Θ+yVn^Q暷hPoHxX1s^b/lKV.QuҲ-Ux)[.=2u#j7*^uU7V|cr͛U2YFǂIW}~,ۍ˗M)Tb֘+4
+omsu]awnsn˹5g͒{$w(z,Yp۔Q&
/3ISɖ\ɗIiJ
O{' ~rvf͕W&fʇ$V9w̺^)\M]Ú {: 4 x>ow r7Q
ZEPx 8'3,G2o1O#u?Ǡ
O!P||^ԟ?sDF'! $:;;N&I]!=4\[Z*Gܐ?,0[