|
23 | 23 | validate_subprotocols,
|
24 | 24 | )
|
25 | 25 | from ..http11 import SERVER, Request, Response
|
26 |
| -from ..protocol import CONNECTING, Event |
| 26 | +from ..protocol import CONNECTING, OPEN, Event |
27 | 27 | from ..server import ServerProtocol
|
28 | 28 | from ..typing import LoggerLike, Origin, StatusLike, Subprotocol
|
29 | 29 | from .connection import Connection
|
@@ -167,7 +167,8 @@ def handshake(
|
167 | 167 |
|
168 | 168 | # self.protocol.handshake_exc is always set when the connection is lost
|
169 | 169 | # before receiving a request, when the request cannot be parsed, or when
|
170 |
| - # the response fails the handshake. |
| 170 | + # the handshake encounters an error. It isn't set when process_request |
| 171 | + # or process_response sends a HTTP response that rejects the handshake. |
171 | 172 |
|
172 | 173 | if self.protocol.handshake_exc is not None:
|
173 | 174 | raise self.protocol.handshake_exc
|
@@ -562,20 +563,23 @@ def protocol_select_subprotocol(
|
562 | 563 | except TimeoutError:
|
563 | 564 | connection.close_socket()
|
564 | 565 | connection.recv_events_thread.join()
|
565 |
| - return |
566 | 566 | except Exception:
|
567 | 567 | connection.logger.error("opening handshake failed", exc_info=True)
|
568 | 568 | connection.close_socket()
|
569 | 569 | connection.recv_events_thread.join()
|
570 |
| - return |
571 | 570 |
|
572 |
| - try: |
573 |
| - handler(connection) |
574 |
| - except Exception: |
575 |
| - connection.logger.error("connection handler failed", exc_info=True) |
576 |
| - connection.close(CloseCode.INTERNAL_ERROR) |
| 571 | + if connection.protocol.state is OPEN: |
| 572 | + try: |
| 573 | + handler(connection) |
| 574 | + except Exception: |
| 575 | + connection.logger.error("connection handler failed", exc_info=True) |
| 576 | + connection.close(CloseCode.INTERNAL_ERROR) |
| 577 | + else: |
| 578 | + connection.close() |
577 | 579 | else:
|
578 |
| - connection.close() |
| 580 | + # process_request or process_response sent a non-101 response. |
| 581 | + connection.close_socket() |
| 582 | + connection.recv_events_thread.join() |
579 | 583 |
|
580 | 584 | except Exception: # pragma: no cover
|
581 | 585 | # Don't leak sockets on unexpected errors.
|
|
0 commit comments