Skip to content

Commit

Permalink
add server binding
Browse files Browse the repository at this point in the history
  • Loading branch information
sergot committed Jul 25, 2014
1 parent a1724c0 commit d60a5f5
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 4 deletions.
22 changes: 18 additions & 4 deletions lib/IO/Socket/SSL.pm6
Expand Up @@ -7,8 +7,10 @@ use libclient;

sub client_connect(Str, int32) returns int32 { * }
sub client_disconnect(int32) { * }
sub server_init(int32, int32, Str) returns int32 { * }
trait_mod:<is>(&client_connect, :native(libclient::library));
trait_mod:<is>(&client_disconnect, :native(libclient::library));
trait_mod:<is>(&server_init, :native(libclient::library));

sub v4-split($uri) {
$uri.split(':', 2);
Expand All @@ -23,6 +25,7 @@ has Str $.host;
has Int $.port = 80;
has Str $.localhost;
has Int $.localport;
has Str $.certfile;
has Bool $.listen;
#has $.family = PIO::PF_INET;
#has $.proto = PIO::PROTO_TCP;
Expand Down Expand Up @@ -78,10 +81,21 @@ method !initialize {
}
}
elsif $!localhost && $!localport {
# server stuff TODO
$!ssl = OpenSSL.new;
$!ssl.set-fd($!fd);
$!ssl.set-accept-state;
my int32 $listen = $!listen.Int // 0;
$!fd = server_init($!localport, $listen, $!certfile);
if $!fd > 0 {
$!ssl = OpenSSL.new;
$!ssl.set-fd($!fd);
$!ssl.set-accept-state;

die "No certificate file given" unless $!certfile;
$!ssl.use-certificate-file($!certfile);
$!ssl.use-privatekey-file($!certfile);
$!ssl.check-private-key;
}
else {
die "Failed to " ~ ($!fd == -1 ?? "bind" !! "listen");
}
}
self;
}
Expand Down
24 changes: 24 additions & 0 deletions src/libclient.c
Expand Up @@ -40,6 +40,30 @@ int client_connect(char *hostname, int port) {
return handle;
}

int server_init(int port, int if_listen, char *cert) {
struct addrinfo hints, *res;
int handle;
char PORT[6]; // max port number is 65535 + \0
snprintf(PORT, 6, "%d", port);

memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;

getaddrinfo(NULL, PORT, &hints, &res);

handle = socket(res->ai_family, res->ai_socktype, res->ai_protocol);

if( bind(handle, res->ai_addr, res->ai_addrlen) != 0 )
return -1;

if( if_listen && (listen(handle, 10) != 0) )
return 0;

return handle;
}

void client_disconnect(int fd) {
close(fd);
}

0 comments on commit d60a5f5

Please sign in to comment.