Socket.hx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. package asys.net;
  2. import haxe.Error;
  3. import haxe.NoData;
  4. import haxe.async.*;
  5. import haxe.io.*;
  6. import haxe.io.Readable.ReadResult;
  7. import asys.io.*;
  8. import asys.net.SocketOptions.SocketConnectTcpOptions;
  9. import asys.net.SocketOptions.SocketConnectIpcOptions;
  10. private typedef NativeStream =
  11. #if doc_gen
  12. Void;
  13. #elseif eval
  14. eval.uv.Stream;
  15. #elseif hl
  16. hl.uv.Stream;
  17. #elseif neko
  18. neko.uv.Stream;
  19. #else
  20. #error "socket not supported on this platform"
  21. #end
  22. private typedef NativeSocket =
  23. #if doc_gen
  24. Void;
  25. #elseif eval
  26. eval.uv.Socket;
  27. #elseif hl
  28. hl.uv.Socket;
  29. #elseif neko
  30. neko.uv.Socket;
  31. #else
  32. #error "socket not supported on this platform"
  33. #end
  34. private typedef NativePipe =
  35. #if doc_gen
  36. Void;
  37. #elseif eval
  38. eval.uv.Pipe;
  39. #elseif hl
  40. hl.uv.Pipe;
  41. #elseif neko
  42. neko.uv.Pipe;
  43. #else
  44. #error "socket not supported on this platform"
  45. #end
  46. /**
  47. Socket object, used for clients and servers for TCP communications and IPC
  48. (inter-process communications) over Windows named pipes and Unix local domain
  49. sockets.
  50. An IPC pipe is a communication channel between two processes. It may be
  51. uni-directional or bi-directional, depending on how it is created. Pipes can
  52. be automatically created for spawned subprocesses with `Process.spawn`.
  53. **/
  54. class Socket extends Duplex {
  55. /**
  56. Creates an unconnected socket or pipe instance.
  57. @param options.allowHalfOpen
  58. @param options.readable Whether the socket should be readable to the
  59. current process.
  60. @param options.writable Whether the socket should be writable to the
  61. current process.
  62. **/
  63. public static function create(?options:SocketOptions):Socket {
  64. // TODO: use options
  65. return new Socket();
  66. }
  67. /**
  68. Emitted when the socket connects to a remote endpoint.
  69. **/
  70. public final closeSignal:Signal<NoData> = new ArraySignal();
  71. public final connectSignal:Signal<NoData> = new ArraySignal();
  72. // endSignal
  73. /**
  74. (TCP only.) Emitted after the IP address of the hostname given in
  75. `connectTcp` is resolved, but before the socket connects.
  76. **/
  77. public final lookupSignal:Signal<Address> = new ArraySignal();
  78. /**
  79. Emitted when a timeout occurs. See `setTimeout`.
  80. **/
  81. public final timeoutSignal:Signal<NoData> = new ArraySignal();
  82. private function get_localAddress():Null<SocketAddress> {
  83. if (nativeSocket != null)
  84. return nativeSocket.getSockName();
  85. if (nativePipe != null)
  86. return nativePipe.getSockName();
  87. return null;
  88. }
  89. /**
  90. The address of the local side of the socket connection, or `null` if not
  91. connected.
  92. **/
  93. public var localAddress(get, never):Null<SocketAddress>;
  94. private function get_remoteAddress():Null<SocketAddress> {
  95. if (nativeSocket != null)
  96. return nativeSocket.getPeerName();
  97. if (nativePipe != null)
  98. return nativePipe.getPeerName();
  99. return null;
  100. }
  101. /**
  102. The address of the remote side of the socket connection, or `null` if not
  103. connected.
  104. **/
  105. public var remoteAddress(get, never):Null<SocketAddress>;
  106. private function get_handlesPending():Int {
  107. if (nativePipe == null)
  108. throw "not connected via IPC";
  109. return nativePipe.pendingCount();
  110. }
  111. /**
  112. (IPC only.) Number of pending sockets or pipes. Accessible using
  113. `readHandle`.
  114. **/
  115. public var handlesPending(get, never):Int;
  116. /**
  117. `true` when `this` socket is connected to a remote host or an IPC pipe.
  118. **/
  119. public var connected(default, null):Bool = false;
  120. /**
  121. Connect `this` socket via TCP to the given remote.
  122. If neither `options.host` nor `options.address` is specified, the host
  123. `localhost` is resolved via DNS and used as the address. At least one of
  124. `options.host` or `options.address` must be `null`.
  125. `options.localAddress` and `options.localPort` can be used to specify what
  126. address and port to use on the local machine for the outgoing connection.
  127. If `null` or not specified, an address and/or a port will be chosen
  128. automatically by the system when connecting. The local address and port can
  129. be obtained using the `localAddress`.
  130. @param options.port Remote port to connect to.
  131. @param options.host Hostname to connect to, will be resolved using
  132. `Dns.resolve` to an address. `lookupSignal` will be emitted with the
  133. resolved address before the connection is attempted.
  134. @param options.address IPv4 or IPv6 address to connect to.
  135. @param options.localAddress Local IPv4 or IPv6 address to connect from.
  136. @param options.localPort Local port to connect from.
  137. @param options.family Limit DNS lookup to the given family.
  138. **/
  139. public function connectTcp(options:SocketConnectTcpOptions, ?cb:Callback<NoData>):Void {
  140. if (connectStarted || connected)
  141. throw "already connected";
  142. if (options.host != null && options.address != null)
  143. throw "cannot specify both host and address";
  144. connectStarted = true;
  145. nativeSocket = new NativeSocket();
  146. native = nativeSocket.asStream();
  147. // take a copy since we reuse the object asynchronously
  148. var options = {
  149. port: options.port,
  150. host: options.host,
  151. address: options.address,
  152. localAddress: options.localAddress,
  153. localPort: options.localPort,
  154. family: options.family
  155. };
  156. function connect(address:Address):Void {
  157. connectDefer = null;
  158. // TODO: bindTcp for localAddress and localPort, if specified
  159. try {
  160. nativeSocket.connectTcp(address, options.port, (err, nd) -> {
  161. timeoutReset();
  162. if (err == null)
  163. connected = true;
  164. if (cb != null)
  165. cb(err, nd);
  166. if (err == null)
  167. connectSignal.emit(new NoData());
  168. });
  169. } catch (err:haxe.Error) {
  170. if (cb != null)
  171. cb(err, new NoData());
  172. }
  173. }
  174. if (options.address != null) {
  175. connectDefer = Defer.nextTick(() -> connect(options.address));
  176. return;
  177. }
  178. if (options.host == null)
  179. options.host = "localhost";
  180. Dns.lookup(options.host, {family: options.family}, (err, entries) -> {
  181. timeoutReset();
  182. if (err != null)
  183. return errorSignal.emit(err);
  184. if (entries.length == 0)
  185. throw "!";
  186. lookupSignal.emit(entries[0]);
  187. connect(entries[0]);
  188. });
  189. }
  190. /**
  191. Connect `this` socket to an IPC pipe.
  192. @param options.path Pipe path.
  193. **/
  194. public function connectIpc(options:SocketConnectIpcOptions, ?cb:Callback<NoData>):Void {
  195. if (connectStarted || connected)
  196. throw "already connected";
  197. connectStarted = true;
  198. nativePipe = new NativePipe(false);
  199. native = nativePipe.asStream();
  200. try {
  201. nativePipe.connectIpc(options.path, (err, nd) -> {
  202. timeoutReset();
  203. if (err == null)
  204. connected = true;
  205. if (cb != null)
  206. cb(err, nd);
  207. if (err == null)
  208. connectSignal.emit(new NoData());
  209. });
  210. } catch (err:haxe.Error) {
  211. if (cb != null)
  212. cb(err, new NoData());
  213. }
  214. }
  215. /**
  216. Connect `this` socket to a file descriptor. Used internally to establish
  217. IPC channels between Haxe processes.
  218. @param ipc Whether IPC features (sending sockets) should be enabled.
  219. **/
  220. public function connectFd(ipc:Bool, fd:Int):Void {
  221. if (connectStarted || connected)
  222. throw "already connected";
  223. connectStarted = true;
  224. nativePipe = new NativePipe(ipc);
  225. nativePipe.open(fd);
  226. connected = true;
  227. native = nativePipe.asStream();
  228. // TODO: signal consistency with other connect methods
  229. }
  230. /**
  231. Closes `this` socket and all underlying resources.
  232. **/
  233. public function destroy(?cb:Callback<NoData>):Void {
  234. if (readStarted)
  235. native.stopRead();
  236. native.close((err, nd) -> {
  237. if (err != null)
  238. errorSignal.emit(err);
  239. if (cb != null)
  240. cb(err, nd);
  241. closeSignal.emit(new NoData());
  242. });
  243. }
  244. /**
  245. (TCP only.) Enable or disable TCP keep-alive.
  246. @param initialDelay Initial delay in seconds. Ignored if `enable` is
  247. `false`.
  248. **/
  249. public function setKeepAlive(?enable:Bool = false, ?initialDelay:Int = 0):Void {
  250. if (nativeSocket == null)
  251. throw "not connected via TCP";
  252. nativeSocket.setKeepAlive(enable, initialDelay);
  253. }
  254. /**
  255. (TCP only.) Enable or disable TCP no-delay. Enabling no-delay disables
  256. Nagle's algorithm.
  257. **/
  258. public function setNoDelay(?noDelay:Bool = true):Void {
  259. if (nativeSocket == null)
  260. throw "not connected via TCP";
  261. nativeSocket.setNoDelay(noDelay);
  262. }
  263. /**
  264. Set a timeout for socket oprations. Any time activity is detected on the
  265. socket (see below), the timer is reset to `timeout`. When the timer runs
  266. out, `timeoutSignal` is emitted. Note that a timeout will not automatically
  267. do anything to the socket - it is up to the `timeoutSignal` handler to
  268. perform an action, e.g. ping the remote host or close the socket.
  269. Socket activity which resets the timer:
  270. - A chunk of data is received.
  271. - An error occurs during reading.
  272. - A chunk of data is written to the socket.
  273. - Connection is established.
  274. - (TCP only.) DNS lookup is finished (successfully or not).
  275. @param timeout Timeout in seconds, or `0` to disable.
  276. **/
  277. public function setTimeout(timeout:Int, ?listener:Listener<NoData>):Void {
  278. timeoutTime = timeout;
  279. timeoutReset();
  280. if (listener != null)
  281. timeoutSignal.once(listener);
  282. }
  283. /**
  284. (IPC only.) Send a socket or pipe in along with the given `data`. The
  285. socket must be connected.
  286. **/
  287. public function writeHandle(data:Bytes, handle:Socket):Void {
  288. if (nativePipe == null)
  289. throw "not connected via IPC";
  290. nativePipe.writeHandle(data, handle.native, writeDone);
  291. }
  292. /**
  293. (IPC only.) Receive a socket or pipe. Should only be called when
  294. `handlesPending` is greater than zero.
  295. **/
  296. public function readHandle():Socket {
  297. if (nativePipe == null)
  298. throw "not connected via IPC";
  299. var ret = new Socket();
  300. switch (nativePipe.acceptPending()) {
  301. case Socket(nativeSocket):
  302. ret.nativeSocket = nativeSocket;
  303. ret.native = nativeSocket.asStream();
  304. case Pipe(nativePipe):
  305. ret.nativePipe = nativePipe;
  306. ret.native = nativePipe.asStream();
  307. }
  308. ret.connected = true;
  309. return ret;
  310. }
  311. public function ref():Void {
  312. if (native == null)
  313. throw "not connected";
  314. native.ref();
  315. }
  316. public function unref():Void {
  317. if (native == null)
  318. throw "not connected";
  319. native.unref();
  320. }
  321. var connectDefer:haxe.Timer;
  322. var native:NativeStream;
  323. var nativeSocket:NativeSocket;
  324. var nativePipe:NativePipe;
  325. var internalReadCalled = false;
  326. var readStarted = false;
  327. var connectStarted = false;
  328. var serverSpawn:Bool = false;
  329. var timeoutTime:Int = 0;
  330. var timeoutTimer:haxe.Timer;
  331. function new() {
  332. super();
  333. }
  334. function initPipe(ipc:Bool):Void {
  335. nativePipe = new NativePipe(ipc);
  336. native = nativePipe.asStream();
  337. connected = true;
  338. }
  339. override function internalRead(remaining):ReadResult {
  340. if (internalReadCalled)
  341. return None;
  342. internalReadCalled = true;
  343. function start():Void {
  344. readStarted = true;
  345. native.startRead((err, chunk) -> {
  346. timeoutReset();
  347. if (err != null) {
  348. switch (err.type) {
  349. case UVError(EOF):
  350. asyncRead([], true);
  351. case _:
  352. errorSignal.emit(err);
  353. }
  354. } else {
  355. asyncRead([chunk], false);
  356. }
  357. });
  358. }
  359. if (connected)
  360. start();
  361. else
  362. connectSignal.once(start);
  363. return None;
  364. }
  365. // TODO: keep track of pending writes for finish event emission
  366. // in `internalWrite` and `writeHandle`
  367. function writeDone(err:Error, nd:NoData):Void {
  368. timeoutReset();
  369. if (err != null)
  370. errorSignal.emit(err);
  371. // TODO: destroy stream and socket
  372. }
  373. override function internalWrite():Void {
  374. while (inputBuffer.length > 0) {
  375. native.write(pop(), writeDone);
  376. }
  377. }
  378. function timeoutTrigger():Void {
  379. timeoutTimer = null;
  380. timeoutSignal.emit(new NoData());
  381. }
  382. function timeoutReset():Void {
  383. if (timeoutTimer != null)
  384. timeoutTimer.stop();
  385. timeoutTimer = null;
  386. if (timeoutTime != 0) {
  387. timeoutTimer = haxe.Timer.delay(timeoutTrigger, timeoutTime);
  388. timeoutTimer.unref();
  389. }
  390. }
  391. /*
  392. // TODO: #8263 (static hxUnserialize)
  393. // Automatic un/serialisation will not work here since hxUnserialize needs to
  394. // call super, otherwise the socket is unusable; for now sockets are
  395. // delivered separately in IPC.
  396. @:access(asys.io.IpcSerializer)
  397. private function hxSerialize(_):Void {
  398. if (IpcSerializer.activeSerializer == null)
  399. throw "cannot serialize socket";
  400. IpcSerializer.activeSerializer.chunkSockets.push(this);
  401. }
  402. @:access(asys.io.IpcUnserializer)
  403. private function hxUnserialize(_):Void {
  404. if (IpcUnserializer.activeUnserializer == null)
  405. throw "cannot unserialize socket";
  406. trace(dataSignal, input);
  407. var source:Socket = IpcUnserializer.activeUnserializer.chunkSockets.shift();
  408. this.native = source.native;
  409. this.nativePipe = source.nativePipe;
  410. this.nativeSocket = source.nativeSocket;
  411. this.connected = true;
  412. trace("successfully unserialized", this.nativeSocket);
  413. }
  414. */
  415. }