Skip to content

Instantly share code, notes, and snippets.

@apeiros
Created January 29, 2012 19:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save apeiros/1700240 to your computer and use it in GitHub Desktop.
Save apeiros/1700240 to your computer and use it in GitHub Desktop.
HTTPS echo server, using only OpenSSL and TCPServer
# use the following commands to create key.pem & cert.pem
# openssl genrsa -out key.pem
# openssl req -new -x509 -key key.pem -out cert.pem -days 1095
# open your browser and use
# https://127.0.0.1:8080/
require 'socket'
require 'openssl'
require 'cgi'
server = TCPServer.new('0.0.0.0', 8080)
ssl_context = OpenSSL::SSL::SSLContext.new()
ssl_context.cert = OpenSSL::X509::Certificate.new(File.open("cert.pem"))
ssl_context.key = OpenSSL::PKey::RSA.new(File.open("key.pem"))
ssl_server = OpenSSL::SSL::SSLServer.new(server, ssl_context)
while client = ssl_server.accept
puts "Got connection from #{client.peeraddr.inspect}"
data = ""
data << client.read_nonblock(8192) until data.include?("\r\n\r\n")
header_length = data[/.*?\r\n\r\n/m].bytesize
content_length = data[/^Content-Length: *(\d+)/, 1]
if content_length then
total_length = header_length+Integer(content_length, 10)
data << client.read_nonblock(8192) until data.bytesize >= total_length
end
html = "<html><body><pre>#{CGI.escapeHTML(data)}</pre></body></html>"
client.write("HTTP/1.0 200 OK\r\n")
client.write("Content-Type: text/html\r\n")
client.write("Content-Length: #{html.bytesize}\r\n")
client.write("Location: /\r\n")
client.write("\r\n")
client.write(html)
client.close
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment