Browse Source

[hl] added ssl connect support to AsyncSocket

ncannasse 1 month ago
parent
commit
63e4d5623e

+ 33 - 11
std/hl/_std/sys/net/AsyncSocket.hx

@@ -24,6 +24,7 @@ package sys.net;
 
 
 class AsyncSocket {
 class AsyncSocket {
 
 
+	var loop : haxe.EventLoop;
 	var stream : hl.uv.Stream;
 	var stream : hl.uv.Stream;
 	var tcp : hl.uv.Tcp;
 	var tcp : hl.uv.Tcp;
 	var recv : haxe.io.Bytes;
 	var recv : haxe.io.Bytes;
@@ -31,10 +32,7 @@ class AsyncSocket {
 
 
 	public function new( ?loop : haxe.EventLoop ) {
 	public function new( ?loop : haxe.EventLoop ) {
 		if( loop == null ) loop = haxe.EventLoop.current;
 		if( loop == null ) loop = haxe.EventLoop.current;
-		tcp = new hl.uv.Tcp(@:privateAccess loop.uvLoop);
-		@:privateAccess loop.wakeup();
-		stream = tcp;
-		recv = haxe.io.Bytes.alloc(0);
+		this.loop = loop;
 	}
 	}
 
 
 	public function close() {
 	public function close() {
@@ -50,9 +48,28 @@ class AsyncSocket {
 		stream.write(bytes,onWriteCallb,pos,len);
 		stream.write(bytes,onWriteCallb,pos,len);
 	}
 	}
 
 
-	public function connect(host:Host, port:Int) {
-		if( tcp == null ) throw new haxe.io.Eof();
-		tcp.connect(host,port,onConnectRaw);
+	function init(ssl) {
+		tcp = new hl.uv.Tcp(@:privateAccess loop.getUVLoop());
+		stream = tcp;
+		recv = haxe.io.Bytes.alloc(0);
+		@:privateAccess loop.wakeup();
+		if( ssl )
+			stream = new hl.uv.SSLStream(stream);
+	}
+
+	public function connect(host:Host, port:Int, ssl=false) {
+		if( tcp != null ) throw new haxe.io.Eof();
+		init(ssl);
+		tcp.connect(host,port,function(b) {
+			if( ssl )
+				Std.downcast(stream,hl.uv.SSLStream).handshake(function(err) {
+					if( err != null )
+						onSSLError(err);
+					onConnectRaw(err == null);
+				});
+			else
+				onConnectRaw(b);
+		});
 	}
 	}
 
 
 	function onConnectRaw(b : Bool) {
 	function onConnectRaw(b : Bool) {
@@ -82,8 +99,9 @@ class AsyncSocket {
 		tcp.listen(connections,() -> onConnect());
 		tcp.listen(connections,() -> onConnect());
 	}
 	}
 
 
-	public function bind(host:Host, port:Int) {
-		if( tcp == null ) throw new haxe.io.Eof();
+	public function bind(host:Host, port:Int, ?ssl : { hostname:String, key:sys.ssl.Key, cert:sys.ssl.Certificate } ) {
+		if( tcp != null ) throw new haxe.io.Eof();
+		init(ssl != null);
 		tcp.bind(host, port);
 		tcp.bind(host, port);
 	}
 	}
 
 
@@ -120,12 +138,16 @@ class AsyncSocket {
 		}
 		}
 	}
 	}
 
 
+	public dynamic function onSSLError( msg : String ) {
+		throw msg;
+	}
+
 	public function writeString( str : String ) {
 	public function writeString( str : String ) {
 		var buf = haxe.io.Bytes.ofString(str);
 		var buf = haxe.io.Bytes.ofString(str);
 		write(buf, 0, buf.length);
 		write(buf, 0, buf.length);
 	}
 	}
 
 
-	public static function startServer( host, port, onClient ) {
+	public static function startServer( host, port, ?ssl, onClient ) {
 		var s = new AsyncSocket();
 		var s = new AsyncSocket();
 		s.onDisconnect = function() {
 		s.onDisconnect = function() {
 			onClient(null);
 			onClient(null);
@@ -133,7 +155,7 @@ class AsyncSocket {
 		s.onConnect = function() {
 		s.onConnect = function() {
 			onClient(s.accept());
 			onClient(s.accept());
 		};
 		};
-		s.bind(new Host(host), port);
+		s.bind(new Host(host), port, ssl);
 		s.listen(1);
 		s.listen(1);
 		return s;
 		return s;
 	}
 	}

+ 2 - 0
std/hl/_std/sys/ssl/Context.hx

@@ -69,6 +69,8 @@ abstract Context(ContextPtr) {
 
 
 	public function setSocket(socket:sys.net.Socket.SocketHandle):Void {}
 	public function setSocket(socket:sys.net.Socket.SocketHandle):Void {}
 
 
+	public function setBio( ctx : Dynamic ) {}
+
 	public function setHostname(name:hl.Bytes):Void {}
 	public function setHostname(name:hl.Bytes):Void {}
 
 
 	@:hlNative("ssl", "ssl_new") static function ssl_new(conf:Config):ContextPtr {
 	@:hlNative("ssl", "ssl_new") static function ssl_new(conf:Config):ContextPtr {

+ 13 - 6
std/hl/_std/sys/ssl/Socket.hx

@@ -129,13 +129,8 @@ class Socket extends sys.net.Socket {
 		__s = sys.net.Socket.socket_new(false);
 		__s = sys.net.Socket.socket_new(false);
 		input = new SocketInput(this);
 		input = new SocketInput(this);
 		output = new SocketOutput(this);
 		output = new SocketOutput(this);
-		if (DEFAULT_VERIFY_CERT && DEFAULT_CA == null) {
-			try {
-				DEFAULT_CA = Certificate.loadDefaults();
-			} catch (e:Dynamic) {}
-		}
 		verifyCert = DEFAULT_VERIFY_CERT;
 		verifyCert = DEFAULT_VERIFY_CERT;
-		caCert = DEFAULT_CA;
+		caCert = getDefaultCA();
 	}
 	}
 
 
 	public override function connect(host:sys.net.Host, port:Int):Void {
 	public override function connect(host:sys.net.Host, port:Int):Void {
@@ -258,4 +253,16 @@ class Socket extends sys.net.Socket {
 
 
 		return conf;
 		return conf;
 	}
 	}
+
+	static function getDefaultCA() : Certificate {
+		if( !DEFAULT_VERIFY_CERT )
+			return null;
+		if (DEFAULT_CA == null) {
+			try {
+				DEFAULT_CA = Certificate.loadDefaults();
+			} catch (e:Dynamic) {}
+		}
+		return DEFAULT_CA;
+	}
+
 }
 }

+ 158 - 0
std/hl/uv/SSLStream.hx

@@ -0,0 +1,158 @@
+/*
+ * Copyright (C)2005-2019 Haxe Foundation
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ */
+
+package hl.uv;
+
+class SSLStream extends Stream {
+
+	var sub : Stream;
+	var ssl : sys.ssl.Context;
+	var conf : sys.ssl.Context.Config;
+	var bio : hl.NativeArray<Dynamic>;
+	var onWrite : Bool -> Void;
+	var onData : hl.Bytes -> Int -> Void;
+	var tmp = haxe.io.Bytes.alloc(0);
+	var inputBuffer = haxe.io.Bytes.alloc(65536);
+	var outputBuffer = haxe.io.Bytes.alloc(65536);
+	var inputLen : Int = 0;
+	var waitHandshake = true;
+
+	public function new(sub,?cert:sys.ssl.Certificate,?key:sys.ssl.Key) {
+		this.sub = sub;
+		super(sub.handle);
+		conf = new sys.ssl.Context.Config(cert != null);
+		if( cert != null )
+			conf.setCert(@:privateAccess cert.__x, @:privateAccess key.__k);
+		var verify = sys.ssl.Socket.DEFAULT_VERIFY_CERT;
+		var caCert = @:privateAccess sys.ssl.Socket.getDefaultCA();
+		conf.setCa(@:privateAccess caCert?.__x);
+		conf.setVerify(if( verify ) 1 else if ( verify == null) 2 else 0);
+		bio = new hl.NativeArray<Dynamic>(3);
+		bio[0] = this;
+		bio[1] = staticRead;
+		bio[2] = staticWrite;
+		ssl = new sys.ssl.Context(conf);
+		ssl.setBio(bio);
+	}
+
+	static function staticRead( s : SSLStream, buf : hl.Bytes, len : Int ) : Int {
+		var avail = s.inputLen;
+		if( avail == 0 )
+			return -2;
+		var size = len > avail ? avail : len;
+		buf.blit(0, s.inputBuffer, 0, size);
+		avail -= size;
+		if( avail > 0 ) s.inputBuffer.blit(0, s.inputBuffer, size, avail);
+		s.inputLen = avail;
+		return size;
+	}
+
+	static function staticWrite( s : SSLStream, buf : hl.Bytes, len : Int ) : Int {
+		var tmp = s.tmp;
+		@:privateAccess {
+			tmp.b = buf;
+			tmp.length = len;
+		};
+		s.sub.write(tmp,s.onWrite,0,len);
+		return len;
+	}
+
+	override function write(bytes:haxe.io.Bytes, ?onWrite:Bool->Void, pos = 0, len = -1) {
+		this.onWrite = onWrite;
+		var w = ssl.send(bytes,pos,len);
+		if( w < 0 )
+			onWrite(false);
+	}
+
+	override function readStartRaw(onData:hl.Bytes->Int->Void) {
+		this.onData = onData;
+	}
+
+	public function handshake( onHandShake : Null<String> -> Void ) {
+		ssl.handshake();
+		sub.readStartRaw(function(bytes:hl.Bytes,len:Int) {
+			if( len < 0 ) {
+				if( waitHandshake )
+					onHandShake("Connection closed");
+				else
+					onData(null,len);
+				return;
+			}
+			@:privateAccess {
+				tmp.b = bytes;
+				tmp.length = len;
+			};
+			var pos = 0;
+			while( len > 0 ) {
+				var max = inputBuffer.length - inputLen;
+				var size = len > max ? max : len;
+				inputBuffer.blit(inputLen, tmp, pos, size);
+				pos += size;
+				len -= size;
+				inputLen += size;
+				if( waitHandshake ) {
+					var r = try ssl.handshake() catch( e : Dynamic ) {
+						onHandShake(Std.string(e));
+						return;
+					}
+					if( r == 0 ) {
+						waitHandshake = false;
+						onHandShake(null);
+					} else if( r == -1 )
+						continue;
+					else {
+						onHandShake("Handshake error");
+						break;
+					}
+				}
+				var r = ssl.recv(outputBuffer, 0, outputBuffer.length);
+				if( r == -1 )
+					return;
+				if( onData == null ) {
+					// missing readStart. most likely an error, so let's discard data
+					continue;
+				}
+				onData(outputBuffer, r);
+			}
+		});
+	}
+
+	override function listen(n:Int, onConnect:Void->Void) {
+		sub.listen(n,function() {
+			throw "TODO:handshake";
+		});
+	}
+
+	override function close(?callb) {
+		sub.close(function() {
+			ssl.close();
+			conf.close();
+			bio = null;
+			sub = null;
+			ssl = null;
+			conf = null;
+			inputBuffer = outputBuffer = null;
+			if( callb != null ) callb();
+		});
+	}
+
+}

+ 12 - 5
std/sys/net/AsyncSocket.hx

@@ -48,8 +48,9 @@ class AsyncSocket {
 
 
 	/**
 	/**
 		Connect to the given server host/port. Will onConnect if connection successful and onDisconnect if connection fails or if a later disconnection occurs.
 		Connect to the given server host/port. Will onConnect if connection successful and onDisconnect if connection fails or if a later disconnection occurs.
+		If `ssl` is set, the socket will use SSL authentification and encryption. Certificate errors can generate an onSSLError callback.
 	**/
 	**/
-	public function connect(host:Host, port:Int) {
+	public function connect(host:Host, port:Int, ssl = false) {
 	}
 	}
 
 
 	/**
 	/**
@@ -62,7 +63,7 @@ class AsyncSocket {
 	/**
 	/**
 		Bind the socket to the given host/port so it can afterwards listen for connections there.
 		Bind the socket to the given host/port so it can afterwards listen for connections there.
 	**/
 	**/
-	public function bind(host:Host, port:Int) {
+	public function bind(host:Host, port:Int, ?ssl : { hostname : String, cert : sys.ssl.Certificate, key : sys.ssl.Key } ) {
 	}
 	}
 
 
 	/**
 	/**
@@ -96,7 +97,6 @@ class AsyncSocket {
 	public dynamic function onData( bytes : haxe.io.Bytes, pos : Int, len : Int ) {
 	public dynamic function onData( bytes : haxe.io.Bytes, pos : Int, len : Int ) {
 	}
 	}
 
 
-
 	/**
 	/**
 		Dispatched when some data is written. Error is true if the data could not be written succesfully. The default behavior is to silently close the socket when such error occurs.
 		Dispatched when some data is written. Error is true if the data could not be written succesfully. The default behavior is to silently close the socket when such error occurs.
 	**/
 	**/
@@ -106,6 +106,13 @@ class AsyncSocket {
 			close();
 			close();
 		}
 		}
 	}
 	}
+	
+	/**
+		Dispatched when a SSL error occurs. This can be when connecting to a host which fails to authentificate or when starting a server with invalid cert/key.
+		Authentification can be adjusted with `sys.ssl.Socket.DEFAULT_VERIFY_CERT`
+	**/
+	public dynamic function onSSLError( msg : String ) {
+	}
 
 
 	/**
 	/**
 		Similar to `write` but sends a whole string data.
 		Similar to `write` but sends a whole string data.
@@ -120,7 +127,7 @@ class AsyncSocket {
 		Start a server on given host/port and callback `onClient` everytime a client connects.
 		Start a server on given host/port and callback `onClient` everytime a client connects.
 		Will also call `onClient(null)` in the rare case where the server connection is lost.
 		Will also call `onClient(null)` in the rare case where the server connection is lost.
 	**/
 	**/
-	public static function startServer( host, port, onClient ) {
+	public static function startServer( host, port, ?ssl, onClient ) {
 		var s = new AsyncSocket();
 		var s = new AsyncSocket();
 		s.onDisconnect = function() {
 		s.onDisconnect = function() {
 			onClient(null);
 			onClient(null);
@@ -128,7 +135,7 @@ class AsyncSocket {
 		s.onConnect = function() {
 		s.onConnect = function() {
 			onClient(s.accept());
 			onClient(s.accept());
 		};
 		};
-		s.bind(new Host(host), port);
+		s.bind(new Host(host), port, ssl);
 		s.listen(1);
 		s.listen(1);
 		return s;
 		return s;
 	}
 	}

+ 21 - 0
tests/sys/src/net/TestAsyncSocket.hx

@@ -165,4 +165,25 @@ class TestAsyncSocket extends utest.Test {
 			haxe.EventLoop.main.loopOnce();
 			haxe.EventLoop.main.loopOnce();
 		Assert.pass();
 		Assert.pass();
 	}
 	}
+	
+	public function testSSL() {
+		var s = new sys.net.AsyncSocket();
+		var str = null, done = false;
+		s.onConnect = function() {
+			s.writeString("GET / HTTP/1.1\nHost: google.com\n\n");
+		};
+		s.onData = function(bytes,pos,len) {
+			str = bytes.getString(pos, len);
+			s.close();
+			done = true;
+		};
+		s.onDisconnect = function() {
+			done = true;
+		};
+		s.connect(new sys.net.Host("google.com"),443,true);
+		while( !done )
+			haxe.EventLoop.current.loopOnce();
+		Assert.isTrue(str != null && str.indexOf("Content-Type") > 0);
+	}
+	
 }
 }