Socket.hx 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  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. if (@:privateAccess __s.isBlocking)
  48. return 0
  49. else
  50. throw haxe.io.Error.Blocked;
  51. else if (r <= 0)
  52. throw new haxe.io.Eof();
  53. return r;
  54. }
  55. public override function close() {
  56. super.close();
  57. if (__s != null)
  58. __s.close();
  59. }
  60. }
  61. private class SocketOutput extends haxe.io.Output {
  62. @:allow(sys.ssl.Socket) private var __s:Socket;
  63. public function new(s:Socket) {
  64. this.__s = s;
  65. }
  66. public override function writeByte(c:Int) {
  67. __s.handshake();
  68. var r = @:privateAccess __s.ssl.sendChar(c);
  69. if (r == -1)
  70. throw haxe.io.Error.Blocked;
  71. else if (r < 0)
  72. throw new haxe.io.Eof();
  73. }
  74. public override function writeBytes(buf:haxe.io.Bytes, pos:Int, len:Int):Int {
  75. if (pos < 0 || len < 0 || ((pos + len) : UInt) > (buf.length : UInt))
  76. throw haxe.io.Error.OutsideBounds;
  77. __s.handshake();
  78. var r = @:privateAccess __s.ssl.send(buf, pos, len);
  79. if (r == -1)
  80. if (@:privateAccess __s.isBlocking)
  81. return 0
  82. else
  83. throw haxe.io.Error.Blocked;
  84. else if (r < 0)
  85. throw new haxe.io.Eof();
  86. return r;
  87. }
  88. public override function close() {
  89. super.close();
  90. if (__s != null)
  91. __s.close();
  92. }
  93. }
  94. @:coreApi @:access(sys.net.Socket)
  95. class Socket extends sys.net.Socket {
  96. public static var DEFAULT_VERIFY_CERT:Null<Bool> = true;
  97. public static var DEFAULT_CA:Null<Certificate>;
  98. private var conf:Context.Config;
  99. private var ssl:Context;
  100. public var verifyCert:Null<Bool>;
  101. private var caCert:Null<Certificate>;
  102. private var hostname:String;
  103. private var ownCert:Null<Certificate>;
  104. private var ownKey:Null<Key>;
  105. private var altSNIContexts:Null<Array<{match:String->Bool, key:Key, cert:Certificate}>>;
  106. private var sniCallback:hl.Bytes->Context.SNICbResult;
  107. private var handshakeDone:Bool;
  108. private var isBlocking:Bool = true;
  109. private override function init():Void {
  110. __s = sys.net.Socket.socket_new(false);
  111. input = new SocketInput(this);
  112. output = new SocketOutput(this);
  113. verifyCert = DEFAULT_VERIFY_CERT;
  114. caCert = getDefaultCA();
  115. }
  116. public override function connect(host:sys.net.Host, port:Int):Void {
  117. conf = buildConfig(false);
  118. ssl = new Context(conf);
  119. ssl.setSocket(__s);
  120. handshakeDone = false;
  121. if (hostname == null)
  122. hostname = host.host;
  123. if (hostname != null)
  124. ssl.setHostname(@:privateAccess hostname.toUtf8());
  125. if (!sys.net.Socket.socket_connect(__s, host.ip, port))
  126. throw new Sys.SysError("Failed to connect on " + host.toString() + ":" + port);
  127. if (isBlocking)
  128. handshake();
  129. }
  130. public function handshake():Void {
  131. if (!handshakeDone) {
  132. var r = ssl.handshake();
  133. if (r == 0)
  134. handshakeDone = true;
  135. else if (r == -1)
  136. throw haxe.io.Error.Blocked;
  137. else
  138. throw new haxe.io.Eof();
  139. }
  140. }
  141. override function setBlocking(b:Bool):Void {
  142. super.setBlocking(b);
  143. isBlocking = b;
  144. }
  145. public function setCA(cert:Certificate):Void {
  146. caCert = cert;
  147. }
  148. public function setHostname(name:String):Void {
  149. hostname = name;
  150. }
  151. public function setCertificate(cert:Certificate, key:Key):Void {
  152. ownCert = cert;
  153. ownKey = key;
  154. }
  155. public override function close():Void {
  156. if (ssl != null)
  157. ssl.close();
  158. if (conf != null)
  159. conf.close();
  160. if (altSNIContexts != null)
  161. sniCallback = null;
  162. sys.net.Socket.socket_close(__s);
  163. var input:SocketInput = cast input;
  164. var output:SocketOutput = cast output;
  165. @:privateAccess input.__s = output.__s = null;
  166. input.close();
  167. output.close();
  168. }
  169. public function addSNICertificate(cbServernameMatch:String->Bool, cert:Certificate, key:Key):Void {
  170. if (altSNIContexts == null)
  171. altSNIContexts = [];
  172. altSNIContexts.push({match: cbServernameMatch, cert: cert, key: key});
  173. }
  174. public override function bind(host:sys.net.Host, port:Int):Void {
  175. conf = buildConfig(true);
  176. sys.net.Socket.socket_bind(__s, host.ip, port);
  177. }
  178. public override function accept():Socket {
  179. var c = sys.net.Socket.socket_accept(__s);
  180. if(c == null)
  181. throw "Blocking";
  182. var cssl = new Context(conf);
  183. cssl.setSocket(c);
  184. var s = Type.createEmptyInstance(sys.ssl.Socket);
  185. s.__s = c;
  186. s.ssl = cssl;
  187. s.input = new SocketInput(s);
  188. s.output = new SocketOutput(s);
  189. s.handshakeDone = false;
  190. return s;
  191. }
  192. public function peerCertificate():sys.ssl.Certificate {
  193. var x = ssl.getPeerCertificate();
  194. return x == null ? null : new sys.ssl.Certificate(x);
  195. }
  196. private function buildConfig(server:Bool):Context.Config {
  197. var conf = new Context.Config(server);
  198. if (ownCert != null && ownKey != null)
  199. conf.setCert(@:privateAccess ownCert.__x, @:privateAccess ownKey.__k);
  200. if (altSNIContexts != null) {
  201. sniCallback = function(servername:hl.Bytes):Context.SNICbResult {
  202. var servername = @:privateAccess String.fromUTF8(servername);
  203. for (c in altSNIContexts) {
  204. if (c.match(servername))
  205. return new Context.SNICbResult(c.cert, c.key);
  206. }
  207. if (ownKey != null && ownCert != null)
  208. return new Context.SNICbResult(ownCert, ownKey);
  209. return null;
  210. }
  211. conf.setServernameCallback(sniCallback);
  212. }
  213. if (caCert != null)
  214. conf.setCa(caCert == null ? null : @:privateAccess caCert.__x);
  215. conf.setVerify(if (verifyCert) 1 else if (verifyCert == null) 2 else 0);
  216. return conf;
  217. }
  218. static function getDefaultCA() : Certificate {
  219. if( !DEFAULT_VERIFY_CERT )
  220. return null;
  221. if (DEFAULT_CA == null) {
  222. try {
  223. DEFAULT_CA = Certificate.loadDefaults();
  224. } catch (e:Dynamic) {}
  225. }
  226. return DEFAULT_CA;
  227. }
  228. }