1
0
Fork 0
mirror of https://github.com/jnunemaker/httparty synced 2023-03-27 23:23:07 -04:00
httparty/spec/support/ssl_test_server.rb

81 lines
1.9 KiB
Ruby
Raw Normal View History

require 'openssl'
require 'socket'
require 'thread'
# NOTE: This code is garbage. It probably has deadlocks, it might leak
# threads, and otherwise cause problems in a real system. It's really only
# intended for testing HTTParty.
class SSLTestServer
attr_accessor :ctx # SSLContext object
attr_reader :port
def initialize(options = {})
2012-04-15 22:51:39 -04:00
@ctx = OpenSSL::SSL::SSLContext.new
@ctx.cert = OpenSSL::X509::Certificate.new(options[:cert])
@ctx.key = OpenSSL::PKey::RSA.new(options[:rsa_key])
@ctx.verify_mode = OpenSSL::SSL::VERIFY_NONE # Don't verify client certificate
2012-04-15 22:51:39 -04:00
@port = options[:port] || 0
@thread = nil
@stopping_mutex = Mutex.new
@stopping = false
end
def start
@raw_server = TCPServer.new(@port)
2012-04-15 22:51:39 -04:00
if @port == 0
2015-04-18 08:38:40 -04:00
@port = Socket.getnameinfo(@raw_server.getsockname, Socket::NI_NUMERICHOST | Socket::NI_NUMERICSERV)[1].to_i
end
2012-04-15 22:51:39 -04:00
@ssl_server = OpenSSL::SSL::SSLServer.new(@raw_server, @ctx)
2012-04-15 22:51:39 -04:00
2015-04-17 20:00:52 -04:00
@stopping_mutex.synchronize {
return if @stopping
2015-04-17 20:00:52 -04:00
@thread = Thread.new { thread_main }
}
2012-04-15 22:51:39 -04:00
nil
end
def stop
2015-04-17 20:00:52 -04:00
@stopping_mutex.synchronize {
return if @stopping
@stopping = true
}
@thread.join
end
private
2015-04-18 07:44:56 -04:00
def thread_main
until @stopping_mutex.synchronize { @stopping }
(rr, _, _) = select([@ssl_server.to_io], nil, nil, 0.1)
2012-04-15 22:51:39 -04:00
2015-04-18 07:44:56 -04:00
next unless rr && rr.include?(@ssl_server.to_io)
2012-04-15 22:51:39 -04:00
2015-04-18 07:44:56 -04:00
socket = @ssl_server.accept
2012-04-15 22:51:39 -04:00
2015-04-18 07:44:56 -04:00
Thread.new {
header = []
2012-04-15 22:51:39 -04:00
2015-04-18 07:44:56 -04:00
until (line = socket.readline).rstrip.empty?
header << line
end
2015-04-18 07:44:56 -04:00
response = <<EOF
HTTP/1.1 200 OK
Connection: close
Content-Type: application/json; charset=UTF-8
{"success":true}
EOF
2012-04-15 22:51:39 -04:00
2015-04-18 07:44:56 -04:00
socket.write(response.gsub(/\r\n/n, "\n").gsub(/\n/n, "\r\n"))
socket.close
}
end
2015-04-18 07:44:56 -04:00
@ssl_server.close
end
end