@@ -66,7 +66,10 @@ public function toggle(Stream $stream, $toggle)
6666
6767 // TODO: add write() event to make sure we're not sending any excessive data
6868
69- $ deferred = new Deferred ();
69+ $ deferred = new Deferred (function ($ _ , $ reject ) use ($ toggle ) {
70+ // cancelling this leaves this stream in an inconsistent state…
71+ $ reject (new \RuntimeException ('Cancelled toggling encryption ' . $ toggle ? 'on ' : 'off ' ));
72+ });
7073
7174 // get actual stream socket from stream instance
7275 $ socket = $ stream ->stream ;
@@ -82,15 +85,18 @@ public function toggle(Stream $stream, $toggle)
8285 $ wrap = $ this ->wrapSecure && $ toggle ;
8386 $ loop = $ this ->loop ;
8487
85- return $ deferred ->promise ()->then (function () use ($ stream , $ wrap , $ loop ) {
88+ return $ deferred ->promise ()->then (function () use ($ stream , $ socket , $ wrap , $ loop ) {
89+ $ this ->loop ->removeReadStream ($ socket );
90+
8691 if ($ wrap ) {
8792 return new SecureStream ($ stream , $ loop );
8893 }
8994
9095 $ stream ->resume ();
9196
9297 return $ stream ;
93- }, function ($ error ) use ($ stream ) {
98+ }, function ($ error ) use ($ stream , $ socket ) {
99+ $ this ->loop ->removeReadStream ($ socket );
94100 $ stream ->resume ();
95101 throw $ error ;
96102 });
@@ -103,12 +109,8 @@ public function toggleCrypto($socket, Deferred $deferred, $toggle)
103109 restore_error_handler ();
104110
105111 if (true === $ result ) {
106- $ this ->loop ->removeReadStream ($ socket );
107-
108112 $ deferred ->resolve ();
109113 } else if (false === $ result ) {
110- $ this ->loop ->removeReadStream ($ socket );
111-
112114 $ deferred ->reject (new UnexpectedValueException (
113115 sprintf ("Unable to complete SSL/TLS handshake: %s " , $ this ->errstr ),
114116 $ this ->errno
0 commit comments