Socket.hx 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. /*
  2. * Copyright (C)2005-2019 Haxe Foundation
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a
  5. * copy of this software and associated documentation files (the "Software"),
  6. * to deal in the Software without restriction, including without limitation
  7. * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  8. * and/or sell copies of the Software, and to permit persons to whom the
  9. * Software is furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  20. * DEALINGS IN THE SOFTWARE.
  21. */
  22. package sys.ssl;
  23. import sys.ssl.Lib;
  24. import sys.ssl.Key.KeyPtr;
  25. import sys.ssl.Certificate.CertificatePtr;
  26. import sys.net.Socket.SocketHandle;
  27. private class SocketInput extends haxe.io.Input {
  28. @:allow(sys.ssl.Socket) private var __s:Socket;
  29. public function new(s:Socket) {
  30. this.__s = s;
  31. }
  32. public override function readByte() {
  33. __s.handshake();
  34. var r = @:privateAccess __s.ssl.recvChar();
  35. if (r == -1)
  36. throw haxe.io.Error.Blocked;
  37. else if (r < 0)
  38. throw new haxe.io.Eof();
  39. return r;
  40. }
  41. public override function readBytes(buf:haxe.io.Bytes, pos:Int, len:Int):Int {
  42. if (pos < 0 || len < 0 || ((pos + len) : UInt) > (buf.length : UInt))
  43. throw haxe.io.Error.OutsideBounds;
  44. __s.handshake();
  45. var r = @:privateAccess __s.ssl.recv(buf, pos, len);
  46. if (r == -1)
  47. throw haxe.io.Error.Blocked;
  48. else if (r <= 0)
  49. throw new haxe.io.Eof();
  50. return r;
  51. }
  52. public override function close() {
  53. super.close();
  54. if (__s != null)
  55. __s.close();
  56. }
  57. }
  58. private class SocketOutput extends haxe.io.Output {
  59. @:allow(sys.ssl.Socket) private var __s:Socket;
  60. public function new(s:Socket) {
  61. this.__s = s;
  62. }
  63. public override function writeByte(c:Int) {
  64. __s.handshake();
  65. var r = @:privateAccess __s.ssl.sendChar(c);
  66. if (r == -1)
  67. throw haxe.io.Error.Blocked;
  68. else if (r < 0)
  69. throw new haxe.io.Eof();
  70. }
  71. public override function writeBytes(buf:haxe.io.Bytes, pos:Int, len:Int):Int {
  72. if (pos < 0 || len < 0 || ((pos + len) : UInt) > (buf.length : UInt))
  73. throw haxe.io.Error.OutsideBounds;
  74. __s.handshake();
  75. var r = @:privateAccess __s.ssl.send(buf, pos, len);
  76. if (r == -1)
  77. throw haxe.io.Error.Blocked;
  78. else if (r < 0)
  79. throw new haxe.io.Eof();
  80. return r;
  81. }
  82. public override function close() {
  83. super.close();
  84. if (__s != null)
  85. __s.close();
  86. }
  87. }
  88. @:coreApi @:access(sys.net.Socket)
  89. class Socket extends sys.net.Socket {
  90. public static var DEFAULT_VERIFY_CERT:Null<Bool> = true;
  91. public static var DEFAULT_CA:Null<Certificate>;
  92. private var conf:Context.Config;
  93. private var ssl:Context;
  94. public var verifyCert:Null<Bool>;
  95. private var caCert:Null<Certificate>;
  96. private var hostname:String;
  97. private var ownCert:Null<Certificate>;
  98. private var ownKey:Null<Key>;
  99. private var altSNIContexts:Null<Array<{match:String->Bool, key:Key, cert:Certificate}>>;
  100. private var sniCallback:hl.Bytes->Context.SNICbResult;
  101. private var handshakeDone:Bool;
  102. private var isBlocking:Bool = true;
  103. private override function init():Void {
  104. __s = sys.net.Socket.socket_new(false);
  105. input = new SocketInput(this);
  106. output = new SocketOutput(this);
  107. if (DEFAULT_VERIFY_CERT && DEFAULT_CA == null) {
  108. try {
  109. DEFAULT_CA = Certificate.loadDefaults();
  110. } catch (e:Dynamic) {}
  111. }
  112. verifyCert = DEFAULT_VERIFY_CERT;
  113. caCert = DEFAULT_CA;
  114. }
  115. public override function connect(host:sys.net.Host, port:Int):Void {
  116. conf = buildConfig(false);
  117. ssl = new Context(conf);
  118. ssl.setSocket(__s);
  119. handshakeDone = false;
  120. if (hostname == null)
  121. hostname = host.host;
  122. if (hostname != null)
  123. ssl.setHostname(@:privateAccess hostname.toUtf8());
  124. if (!sys.net.Socket.socket_connect(__s, host.ip, port))
  125. throw new Sys.SysError("Failed to connect on " + host.toString() + ":" + port);
  126. if (isBlocking)
  127. handshake();
  128. }
  129. public function handshake():Void {
  130. if (!handshakeDone) {
  131. var r = ssl.handshake();
  132. if (r == 0)
  133. handshakeDone = true;
  134. else if (r == -1)
  135. throw haxe.io.Error.Blocked;
  136. else
  137. throw new haxe.io.Eof();
  138. }
  139. }
  140. override function setBlocking(b:Bool):Void {
  141. super.setBlocking(b);
  142. isBlocking = b;
  143. }
  144. public function setCA(cert:Certificate):Void {
  145. caCert = cert;
  146. }
  147. public function setHostname(name:String):Void {
  148. hostname = name;
  149. }
  150. public function setCertificate(cert:Certificate, key:Key):Void {
  151. ownCert = cert;
  152. ownKey = key;
  153. }
  154. public override function close():Void {
  155. if (ssl != null)
  156. ssl.close();
  157. if (conf != null)
  158. conf.close();
  159. if (altSNIContexts != null)
  160. sniCallback = null;
  161. sys.net.Socket.socket_close(__s);
  162. var input:SocketInput = cast input;
  163. var output:SocketOutput = cast output;
  164. @:privateAccess input.__s = output.__s = null;
  165. input.close();
  166. output.close();
  167. }
  168. public function addSNICertificate(cbServernameMatch:String->Bool, cert:Certificate, key:Key):Void {
  169. if (altSNIContexts == null)
  170. altSNIContexts = [];
  171. altSNIContexts.push({match: cbServernameMatch, cert: cert, key: key});
  172. }
  173. public override function bind(host:sys.net.Host, port:Int):Void {
  174. conf = buildConfig(true);
  175. sys.net.Socket.socket_bind(__s, host.ip, port);
  176. }
  177. public override function accept():Socket {
  178. var c = sys.net.Socket.socket_accept(__s);
  179. var cssl = new Context(conf);
  180. cssl.setSocket(c);
  181. var s = Type.createEmptyInstance(sys.ssl.Socket);
  182. s.__s = c;
  183. s.ssl = cssl;
  184. s.input = new SocketInput(s);
  185. s.output = new SocketOutput(s);
  186. s.handshakeDone = false;
  187. return s;
  188. }
  189. public function peerCertificate():sys.ssl.Certificate {
  190. var x = ssl.getPeerCertificate();
  191. return x == null ? null : new sys.ssl.Certificate(x);
  192. }
  193. private function buildConfig(server:Bool):Context.Config {
  194. var conf = new Context.Config(server);
  195. if (ownCert != null && ownKey != null)
  196. conf.setCert(@:privateAccess ownCert.__x, @:privateAccess ownKey.__k);
  197. if (altSNIContexts != null) {
  198. sniCallback = function(servername:hl.Bytes):Context.SNICbResult {
  199. var servername = @:privateAccess String.fromUTF8(servername);
  200. for (c in altSNIContexts) {
  201. if (c.match(servername))
  202. return new Context.SNICbResult(c.cert, c.key);
  203. }
  204. if (ownKey != null && ownCert != null)
  205. return new Context.SNICbResult(ownCert, ownKey);
  206. return null;
  207. }
  208. conf.setServernameCallback(sniCallback);
  209. }
  210. if (caCert != null)
  211. conf.setCa(caCert == null ? null : @:privateAccess caCert.__x);
  212. conf.setVerify(if (verifyCert) 1 else if (verifyCert == null) 2 else 0);
  213. return conf;
  214. }
  215. }