-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathecho_https_server
More file actions
executable file
·57 lines (46 loc) · 1.34 KB
/
echo_https_server
File metadata and controls
executable file
·57 lines (46 loc) · 1.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#!/usr/bin/ruby
# Inspired by https://stackoverflow.com/a/5873796/188760
require "socket"
require "openssl"
require "thread"
raise "Usage: #$0 <port> <certificate path> <key path> <ca cert path>" if ARGV.size != 4
port, cert_path, key_path, ca_cert_path = ARGV
port = Integer(port)
server = TCPServer.new(port)
ssl_context = OpenSSL::SSL::SSLContext.new
ssl_context.add_certificate(
File.open(cert_path) { |f| OpenSSL::X509::Certificate.new(f) },
File.open(key_path) { |f| OpenSSL::PKey::RSA.new(f) },
[File.open(ca_cert_path) { |f| OpenSSL::X509::Certificate.new(f) }],
)
ssl_server = OpenSSL::SSL::SSLServer.new(server, ssl_context)
puts "Listening on port #{port}"
loop do
connection = ssl_server.accept
Thread.new do
begin
response = ""
loop do
raw_line = connection.gets
break unless raw_line
line = raw_line.chomp
break if line.empty?
STDOUT.puts(line)
response << raw_line
end
full_response = [
"HTTP/1.1 200 OK",
"Content-type: text/plain",
"Content-length: #{response.size}",
"",
response
].join("\n")
STDOUT.puts(full_response)
connection.write(full_response)
connection.close
rescue => e
STDERR.puts("#{e.message} (#{e.class})")
STDERR.puts(e.backtrace.join("\n"))
end
end
end