Last active
October 31, 2015 02:53
-
-
Save ugexe/71d82eb4bb5653125bd8 to your computer and use it in GitHub Desktop.
Perl6 use IO::Socket::Async with OpenSSL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# edit this line: https://github.com/sergot/openssl/blob/master/lib/OpenSSL.pm6#L60 | |
# so its just `method set-socket($s)`, removing the type check | |
use IO::Socket::SSL; | |
class IO::Socket::Async::SSLow { | |
has $!socket; | |
has $!lock; | |
has $.host; | |
has $.port; | |
submethod BUILD(Str :$!host, Int :$!port = 80) { | |
$!lock = Lock.new; | |
$!socket = IO::Socket::Async.connect($!host, $!port).result; | |
} | |
method recv($bytes is copy, Bool :$bin) { | |
state @overflow; | |
# Can't seem to find a way around OpenSSL asking for a byte count | |
# that will be greater than the possible response to be read | |
# so we use 1 and pay for it in speed | |
$bytes = $bytes == Inf ?? 1 !! $bytes; | |
$!lock.protect({ | |
my @recv = $bytes == Inf ?? @overflow.splice(0,*) !! @overflow.splice(0,$bytes); | |
if @recv.elems < $bytes { | |
react { | |
whenever $!socket.bytes-supply -> $d { | |
for $d.contents -> $ord { | |
@recv.elems <= $bytes ?? @recv.append($ord) !! @overflow.append($ord); | |
} | |
done() if @recv.elems >= $bytes; | |
} | |
done() if @recv.elems >= $bytes; | |
} | |
} | |
my $return = ?$bin ?? buf8.new(@recv) !! buf8.new(@recv).decode | |
}); | |
} | |
method write(Blob $data) { | |
$!lock.protect({ | |
$!socket.write($data); | |
}); | |
} | |
} | |
# raw request | |
my $host = 'httpbin.org'; | |
my $port = 443; | |
my $request = buf8.new("GET / HTTP/1.1\r\nHost: $host\r\nConnection: close\r\n\r\n".ords); | |
my $client-socket = IO::Socket::Async::SSLow.new(:$host, :$port); | |
my $ssl-socket = IO::Socket::SSL.new(:$client-socket); | |
# Sync'd IO::Socket::Async | |
# $client-socket.write($request); | |
#say $client-socket.recv(20); | |
#say $client-socket.recv(20); | |
#say $client-socket.recv(20); | |
#say $client-socket.recv(20); | |
# Sync'd IO::Socket::Async with IO::Socket::SSL | |
$ssl-socket.write($request); | |
say $ssl-socket.recv(:bin).unpack("A*"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment