You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

764 lines
27 KiB

  1. from __future__ import annotations
  2. import hmac
  3. import http
  4. import logging
  5. import os
  6. import re
  7. import selectors
  8. import socket
  9. import ssl as ssl_module
  10. import sys
  11. import threading
  12. import warnings
  13. from collections.abc import Iterable, Sequence
  14. from types import TracebackType
  15. from typing import Any, Callable, Mapping, cast
  16. from ..exceptions import InvalidHeader
  17. from ..extensions.base import ServerExtensionFactory
  18. from ..extensions.permessage_deflate import enable_server_permessage_deflate
  19. from ..frames import CloseCode
  20. from ..headers import (
  21. build_www_authenticate_basic,
  22. parse_authorization_basic,
  23. validate_subprotocols,
  24. )
  25. from ..http11 import SERVER, Request, Response
  26. from ..protocol import CONNECTING, OPEN, Event
  27. from ..server import ServerProtocol
  28. from ..typing import LoggerLike, Origin, StatusLike, Subprotocol
  29. from .connection import Connection
  30. from .utils import Deadline
  31. __all__ = ["serve", "unix_serve", "ServerConnection", "Server", "basic_auth"]
  32. class ServerConnection(Connection):
  33. """
  34. :mod:`threading` implementation of a WebSocket server connection.
  35. :class:`ServerConnection` provides :meth:`recv` and :meth:`send` methods for
  36. receiving and sending messages.
  37. It supports iteration to receive messages::
  38. for message in websocket:
  39. process(message)
  40. The iterator exits normally when the connection is closed with close code
  41. 1000 (OK) or 1001 (going away) or without a close code. It raises a
  42. :exc:`~websockets.exceptions.ConnectionClosedError` when the connection is
  43. closed with any other code.
  44. The ``ping_interval``, ``ping_timeout``, ``close_timeout``, and
  45. ``max_queue`` arguments have the same meaning as in :func:`serve`.
  46. Args:
  47. socket: Socket connected to a WebSocket client.
  48. protocol: Sans-I/O connection.
  49. """
  50. def __init__(
  51. self,
  52. socket: socket.socket,
  53. protocol: ServerProtocol,
  54. *,
  55. ping_interval: float | None = 20,
  56. ping_timeout: float | None = 20,
  57. close_timeout: float | None = 10,
  58. max_queue: int | None | tuple[int | None, int | None] = 16,
  59. ) -> None:
  60. self.protocol: ServerProtocol
  61. self.request_rcvd = threading.Event()
  62. super().__init__(
  63. socket,
  64. protocol,
  65. ping_interval=ping_interval,
  66. ping_timeout=ping_timeout,
  67. close_timeout=close_timeout,
  68. max_queue=max_queue,
  69. )
  70. self.username: str # see basic_auth()
  71. self.handler: Callable[[ServerConnection], None] # see route()
  72. self.handler_kwargs: Mapping[str, Any] # see route()
  73. def respond(self, status: StatusLike, text: str) -> Response:
  74. """
  75. Create a plain text HTTP response.
  76. ``process_request`` and ``process_response`` may call this method to
  77. return an HTTP response instead of performing the WebSocket opening
  78. handshake.
  79. You can modify the response before returning it, for example by changing
  80. HTTP headers.
  81. Args:
  82. status: HTTP status code.
  83. text: HTTP response body; it will be encoded to UTF-8.
  84. Returns:
  85. HTTP response to send to the client.
  86. """
  87. return self.protocol.reject(status, text)
  88. def handshake(
  89. self,
  90. process_request: (
  91. Callable[
  92. [ServerConnection, Request],
  93. Response | None,
  94. ]
  95. | None
  96. ) = None,
  97. process_response: (
  98. Callable[
  99. [ServerConnection, Request, Response],
  100. Response | None,
  101. ]
  102. | None
  103. ) = None,
  104. server_header: str | None = SERVER,
  105. timeout: float | None = None,
  106. ) -> None:
  107. """
  108. Perform the opening handshake.
  109. """
  110. if not self.request_rcvd.wait(timeout):
  111. raise TimeoutError("timed out while waiting for handshake request")
  112. if self.request is not None:
  113. with self.send_context(expected_state=CONNECTING):
  114. response = None
  115. if process_request is not None:
  116. try:
  117. response = process_request(self, self.request)
  118. except Exception as exc:
  119. self.protocol.handshake_exc = exc
  120. response = self.protocol.reject(
  121. http.HTTPStatus.INTERNAL_SERVER_ERROR,
  122. (
  123. "Failed to open a WebSocket connection.\n"
  124. "See server log for more information.\n"
  125. ),
  126. )
  127. if response is None:
  128. self.response = self.protocol.accept(self.request)
  129. else:
  130. self.response = response
  131. if server_header:
  132. self.response.headers["Server"] = server_header
  133. response = None
  134. if process_response is not None:
  135. try:
  136. response = process_response(self, self.request, self.response)
  137. except Exception as exc:
  138. self.protocol.handshake_exc = exc
  139. response = self.protocol.reject(
  140. http.HTTPStatus.INTERNAL_SERVER_ERROR,
  141. (
  142. "Failed to open a WebSocket connection.\n"
  143. "See server log for more information.\n"
  144. ),
  145. )
  146. if response is not None:
  147. self.response = response
  148. self.protocol.send_response(self.response)
  149. # self.protocol.handshake_exc is set when the connection is lost before
  150. # receiving a request, when the request cannot be parsed, or when the
  151. # handshake fails, including when process_request or process_response
  152. # raises an exception.
  153. # It isn't set when process_request or process_response sends an HTTP
  154. # response that rejects the handshake.
  155. if self.protocol.handshake_exc is not None:
  156. raise self.protocol.handshake_exc
  157. def process_event(self, event: Event) -> None:
  158. """
  159. Process one incoming event.
  160. """
  161. # First event - handshake request.
  162. if self.request is None:
  163. assert isinstance(event, Request)
  164. self.request = event
  165. self.request_rcvd.set()
  166. # Later events - frames.
  167. else:
  168. super().process_event(event)
  169. def recv_events(self) -> None:
  170. """
  171. Read incoming data from the socket and process events.
  172. """
  173. try:
  174. super().recv_events()
  175. finally:
  176. # If the connection is closed during the handshake, unblock it.
  177. self.request_rcvd.set()
  178. class Server:
  179. """
  180. WebSocket server returned by :func:`serve`.
  181. This class mirrors the API of :class:`~socketserver.BaseServer`, notably the
  182. :meth:`~socketserver.BaseServer.serve_forever` and
  183. :meth:`~socketserver.BaseServer.shutdown` methods, as well as the context
  184. manager protocol.
  185. Args:
  186. socket: Server socket listening for new connections.
  187. handler: Handler for one connection. Receives the socket and address
  188. returned by :meth:`~socket.socket.accept`.
  189. logger: Logger for this server.
  190. It defaults to ``logging.getLogger("websockets.server")``.
  191. See the :doc:`logging guide <../../topics/logging>` for details.
  192. """
  193. def __init__(
  194. self,
  195. socket: socket.socket,
  196. handler: Callable[[socket.socket, Any], None],
  197. logger: LoggerLike | None = None,
  198. ) -> None:
  199. self.socket = socket
  200. self.handler = handler
  201. if logger is None:
  202. logger = logging.getLogger("websockets.server")
  203. self.logger = logger
  204. if sys.platform != "win32":
  205. self.shutdown_watcher, self.shutdown_notifier = os.pipe()
  206. def serve_forever(self) -> None:
  207. """
  208. See :meth:`socketserver.BaseServer.serve_forever`.
  209. This method doesn't return. Calling :meth:`shutdown` from another thread
  210. stops the server.
  211. Typical use::
  212. with serve(...) as server:
  213. server.serve_forever()
  214. """
  215. poller = selectors.DefaultSelector()
  216. try:
  217. poller.register(self.socket, selectors.EVENT_READ)
  218. except ValueError: # pragma: no cover
  219. # If shutdown() is called before poller.register(),
  220. # the socket is closed and poller.register() raises
  221. # ValueError: Invalid file descriptor: -1
  222. return
  223. if sys.platform != "win32":
  224. poller.register(self.shutdown_watcher, selectors.EVENT_READ)
  225. while True:
  226. poller.select()
  227. try:
  228. # If the socket is closed, this will raise an exception and exit
  229. # the loop. So we don't need to check the return value of select().
  230. sock, addr = self.socket.accept()
  231. except OSError:
  232. break
  233. # Since there isn't a mechanism for tracking connections and waiting
  234. # for them to terminate, we cannot use daemon threads, or else all
  235. # connections would be terminate brutally when closing the server.
  236. thread = threading.Thread(target=self.handler, args=(sock, addr))
  237. thread.start()
  238. def shutdown(self) -> None:
  239. """
  240. See :meth:`socketserver.BaseServer.shutdown`.
  241. """
  242. self.socket.close()
  243. if sys.platform != "win32":
  244. os.write(self.shutdown_notifier, b"x")
  245. def fileno(self) -> int:
  246. """
  247. See :meth:`socketserver.BaseServer.fileno`.
  248. """
  249. return self.socket.fileno()
  250. def __enter__(self) -> Server:
  251. return self
  252. def __exit__(
  253. self,
  254. exc_type: type[BaseException] | None,
  255. exc_value: BaseException | None,
  256. traceback: TracebackType | None,
  257. ) -> None:
  258. self.shutdown()
  259. def __getattr__(name: str) -> Any:
  260. if name == "WebSocketServer":
  261. warnings.warn( # deprecated in 13.0 - 2024-08-20
  262. "WebSocketServer was renamed to Server",
  263. DeprecationWarning,
  264. )
  265. return Server
  266. raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
  267. def serve(
  268. handler: Callable[[ServerConnection], None],
  269. host: str | None = None,
  270. port: int | None = None,
  271. *,
  272. # TCP/TLS
  273. sock: socket.socket | None = None,
  274. ssl: ssl_module.SSLContext | None = None,
  275. # WebSocket
  276. origins: Sequence[Origin | re.Pattern[str] | None] | None = None,
  277. extensions: Sequence[ServerExtensionFactory] | None = None,
  278. subprotocols: Sequence[Subprotocol] | None = None,
  279. select_subprotocol: (
  280. Callable[
  281. [ServerConnection, Sequence[Subprotocol]],
  282. Subprotocol | None,
  283. ]
  284. | None
  285. ) = None,
  286. compression: str | None = "deflate",
  287. # HTTP
  288. process_request: (
  289. Callable[
  290. [ServerConnection, Request],
  291. Response | None,
  292. ]
  293. | None
  294. ) = None,
  295. process_response: (
  296. Callable[
  297. [ServerConnection, Request, Response],
  298. Response | None,
  299. ]
  300. | None
  301. ) = None,
  302. server_header: str | None = SERVER,
  303. # Timeouts
  304. open_timeout: float | None = 10,
  305. ping_interval: float | None = 20,
  306. ping_timeout: float | None = 20,
  307. close_timeout: float | None = 10,
  308. # Limits
  309. max_size: int | None = 2**20,
  310. max_queue: int | None | tuple[int | None, int | None] = 16,
  311. # Logging
  312. logger: LoggerLike | None = None,
  313. # Escape hatch for advanced customization
  314. create_connection: type[ServerConnection] | None = None,
  315. **kwargs: Any,
  316. ) -> Server:
  317. """
  318. Create a WebSocket server listening on ``host`` and ``port``.
  319. Whenever a client connects, the server creates a :class:`ServerConnection`,
  320. performs the opening handshake, and delegates to the ``handler``.
  321. The handler receives the :class:`ServerConnection` instance, which you can
  322. use to send and receive messages.
  323. Once the handler completes, either normally or with an exception, the server
  324. performs the closing handshake and closes the connection.
  325. This function returns a :class:`Server` whose API mirrors
  326. :class:`~socketserver.BaseServer`. Treat it as a context manager to ensure
  327. that it will be closed and call :meth:`~Server.serve_forever` to serve
  328. requests::
  329. from websockets.sync.server import serve
  330. def handler(websocket):
  331. ...
  332. with serve(handler, ...) as server:
  333. server.serve_forever()
  334. Args:
  335. handler: Connection handler. It receives the WebSocket connection,
  336. which is a :class:`ServerConnection`, in argument.
  337. host: Network interfaces the server binds to.
  338. See :func:`~socket.create_server` for details.
  339. port: TCP port the server listens on.
  340. See :func:`~socket.create_server` for details.
  341. sock: Preexisting TCP socket. ``sock`` replaces ``host`` and ``port``.
  342. You may call :func:`socket.create_server` to create a suitable TCP
  343. socket.
  344. ssl: Configuration for enabling TLS on the connection.
  345. origins: Acceptable values of the ``Origin`` header, for defending
  346. against Cross-Site WebSocket Hijacking attacks. Values can be
  347. :class:`str` to test for an exact match or regular expressions
  348. compiled by :func:`re.compile` to test against a pattern. Include
  349. :obj:`None` in the list if the lack of an origin is acceptable.
  350. extensions: List of supported extensions, in order in which they
  351. should be negotiated and run.
  352. subprotocols: List of supported subprotocols, in order of decreasing
  353. preference.
  354. select_subprotocol: Callback for selecting a subprotocol among
  355. those supported by the client and the server. It receives a
  356. :class:`ServerConnection` (not a
  357. :class:`~websockets.server.ServerProtocol`!) instance and a list of
  358. subprotocols offered by the client. Other than the first argument,
  359. it has the same behavior as the
  360. :meth:`ServerProtocol.select_subprotocol
  361. <websockets.server.ServerProtocol.select_subprotocol>` method.
  362. compression: The "permessage-deflate" extension is enabled by default.
  363. Set ``compression`` to :obj:`None` to disable it. See the
  364. :doc:`compression guide <../../topics/compression>` for details.
  365. process_request: Intercept the request during the opening handshake.
  366. Return an HTTP response to force the response. Return :obj:`None` to
  367. continue normally. When you force an HTTP 101 Continue response, the
  368. handshake is successful. Else, the connection is aborted.
  369. process_response: Intercept the response during the opening handshake.
  370. Modify the response or return a new HTTP response to force the
  371. response. Return :obj:`None` to continue normally. When you force an
  372. HTTP 101 Continue response, the handshake is successful. Else, the
  373. connection is aborted.
  374. server_header: Value of the ``Server`` response header.
  375. It defaults to ``"Python/x.y.z websockets/X.Y"``. Setting it to
  376. :obj:`None` removes the header.
  377. open_timeout: Timeout for opening connections in seconds.
  378. :obj:`None` disables the timeout.
  379. ping_interval: Interval between keepalive pings in seconds.
  380. :obj:`None` disables keepalive.
  381. ping_timeout: Timeout for keepalive pings in seconds.
  382. :obj:`None` disables timeouts.
  383. close_timeout: Timeout for closing connections in seconds.
  384. :obj:`None` disables the timeout.
  385. max_size: Maximum size of incoming messages in bytes.
  386. :obj:`None` disables the limit.
  387. max_queue: High-water mark of the buffer where frames are received.
  388. It defaults to 16 frames. The low-water mark defaults to ``max_queue
  389. // 4``. You may pass a ``(high, low)`` tuple to set the high-water
  390. and low-water marks. If you want to disable flow control entirely,
  391. you may set it to ``None``, although that's a bad idea.
  392. logger: Logger for this server.
  393. It defaults to ``logging.getLogger("websockets.server")``. See the
  394. :doc:`logging guide <../../topics/logging>` for details.
  395. create_connection: Factory for the :class:`ServerConnection` managing
  396. the connection. Set it to a wrapper or a subclass to customize
  397. connection handling.
  398. Any other keyword arguments are passed to :func:`~socket.create_server`.
  399. """
  400. # Process parameters
  401. # Backwards compatibility: ssl used to be called ssl_context.
  402. if ssl is None and "ssl_context" in kwargs:
  403. ssl = kwargs.pop("ssl_context")
  404. warnings.warn( # deprecated in 13.0 - 2024-08-20
  405. "ssl_context was renamed to ssl",
  406. DeprecationWarning,
  407. )
  408. if subprotocols is not None:
  409. validate_subprotocols(subprotocols)
  410. if compression == "deflate":
  411. extensions = enable_server_permessage_deflate(extensions)
  412. elif compression is not None:
  413. raise ValueError(f"unsupported compression: {compression}")
  414. if create_connection is None:
  415. create_connection = ServerConnection
  416. # Bind socket and listen
  417. # Private APIs for unix_connect()
  418. unix: bool = kwargs.pop("unix", False)
  419. path: str | None = kwargs.pop("path", None)
  420. if sock is None:
  421. if unix:
  422. if path is None:
  423. raise ValueError("missing path argument")
  424. kwargs.setdefault("family", socket.AF_UNIX)
  425. sock = socket.create_server(path, **kwargs)
  426. else:
  427. sock = socket.create_server((host, port), **kwargs)
  428. else:
  429. if path is not None:
  430. raise ValueError("path and sock arguments are incompatible")
  431. # Initialize TLS wrapper
  432. if ssl is not None:
  433. sock = ssl.wrap_socket(
  434. sock,
  435. server_side=True,
  436. # Delay TLS handshake until after we set a timeout on the socket.
  437. do_handshake_on_connect=False,
  438. )
  439. # Define request handler
  440. def conn_handler(sock: socket.socket, addr: Any) -> None:
  441. # Calculate timeouts on the TLS and WebSocket handshakes.
  442. # The TLS timeout must be set on the socket, then removed
  443. # to avoid conflicting with the WebSocket timeout in handshake().
  444. deadline = Deadline(open_timeout)
  445. try:
  446. # Disable Nagle algorithm
  447. if not unix:
  448. sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, True)
  449. # Perform TLS handshake
  450. if ssl is not None:
  451. sock.settimeout(deadline.timeout())
  452. # mypy cannot figure this out
  453. assert isinstance(sock, ssl_module.SSLSocket)
  454. sock.do_handshake()
  455. sock.settimeout(None)
  456. # Create a closure to give select_subprotocol access to connection.
  457. protocol_select_subprotocol: (
  458. Callable[
  459. [ServerProtocol, Sequence[Subprotocol]],
  460. Subprotocol | None,
  461. ]
  462. | None
  463. ) = None
  464. if select_subprotocol is not None:
  465. def protocol_select_subprotocol(
  466. protocol: ServerProtocol,
  467. subprotocols: Sequence[Subprotocol],
  468. ) -> Subprotocol | None:
  469. # mypy doesn't know that select_subprotocol is immutable.
  470. assert select_subprotocol is not None
  471. # Ensure this function is only used in the intended context.
  472. assert protocol is connection.protocol
  473. return select_subprotocol(connection, subprotocols)
  474. # Initialize WebSocket protocol
  475. protocol = ServerProtocol(
  476. origins=origins,
  477. extensions=extensions,
  478. subprotocols=subprotocols,
  479. select_subprotocol=protocol_select_subprotocol,
  480. max_size=max_size,
  481. logger=logger,
  482. )
  483. # Initialize WebSocket connection
  484. assert create_connection is not None # help mypy
  485. connection = create_connection(
  486. sock,
  487. protocol,
  488. ping_interval=ping_interval,
  489. ping_timeout=ping_timeout,
  490. close_timeout=close_timeout,
  491. max_queue=max_queue,
  492. )
  493. except Exception:
  494. sock.close()
  495. return
  496. try:
  497. try:
  498. connection.handshake(
  499. process_request,
  500. process_response,
  501. server_header,
  502. deadline.timeout(),
  503. )
  504. except TimeoutError:
  505. connection.close_socket()
  506. connection.recv_events_thread.join()
  507. return
  508. except Exception:
  509. connection.logger.error("opening handshake failed", exc_info=True)
  510. connection.close_socket()
  511. connection.recv_events_thread.join()
  512. return
  513. assert connection.protocol.state is OPEN
  514. try:
  515. connection.start_keepalive()
  516. handler(connection)
  517. except Exception:
  518. connection.logger.error("connection handler failed", exc_info=True)
  519. connection.close(CloseCode.INTERNAL_ERROR)
  520. else:
  521. connection.close()
  522. except Exception: # pragma: no cover
  523. # Don't leak sockets on unexpected errors.
  524. sock.close()
  525. # Initialize server
  526. return Server(sock, conn_handler, logger)
  527. def unix_serve(
  528. handler: Callable[[ServerConnection], None],
  529. path: str | None = None,
  530. **kwargs: Any,
  531. ) -> Server:
  532. """
  533. Create a WebSocket server listening on a Unix socket.
  534. This function accepts the same keyword arguments as :func:`serve`.
  535. It's only available on Unix.
  536. It's useful for deploying a server behind a reverse proxy such as nginx.
  537. Args:
  538. handler: Connection handler. It receives the WebSocket connection,
  539. which is a :class:`ServerConnection`, in argument.
  540. path: File system path to the Unix socket.
  541. """
  542. return serve(handler, unix=True, path=path, **kwargs)
  543. def is_credentials(credentials: Any) -> bool:
  544. try:
  545. username, password = credentials
  546. except (TypeError, ValueError):
  547. return False
  548. else:
  549. return isinstance(username, str) and isinstance(password, str)
  550. def basic_auth(
  551. realm: str = "",
  552. credentials: tuple[str, str] | Iterable[tuple[str, str]] | None = None,
  553. check_credentials: Callable[[str, str], bool] | None = None,
  554. ) -> Callable[[ServerConnection, Request], Response | None]:
  555. """
  556. Factory for ``process_request`` to enforce HTTP Basic Authentication.
  557. :func:`basic_auth` is designed to integrate with :func:`serve` as follows::
  558. from websockets.sync.server import basic_auth, serve
  559. with serve(
  560. ...,
  561. process_request=basic_auth(
  562. realm="my dev server",
  563. credentials=("hello", "iloveyou"),
  564. ),
  565. ):
  566. If authentication succeeds, the connection's ``username`` attribute is set.
  567. If it fails, the server responds with an HTTP 401 Unauthorized status.
  568. One of ``credentials`` or ``check_credentials`` must be provided; not both.
  569. Args:
  570. realm: Scope of protection. It should contain only ASCII characters
  571. because the encoding of non-ASCII characters is undefined. Refer to
  572. section 2.2 of :rfc:`7235` for details.
  573. credentials: Hard coded authorized credentials. It can be a
  574. ``(username, password)`` pair or a list of such pairs.
  575. check_credentials: Function that verifies credentials.
  576. It receives ``username`` and ``password`` arguments and returns
  577. whether they're valid.
  578. Raises:
  579. TypeError: If ``credentials`` or ``check_credentials`` is wrong.
  580. ValueError: If ``credentials`` and ``check_credentials`` are both
  581. provided or both not provided.
  582. """
  583. if (credentials is None) == (check_credentials is None):
  584. raise ValueError("provide either credentials or check_credentials")
  585. if credentials is not None:
  586. if is_credentials(credentials):
  587. credentials_list = [cast(tuple[str, str], credentials)]
  588. elif isinstance(credentials, Iterable):
  589. credentials_list = list(cast(Iterable[tuple[str, str]], credentials))
  590. if not all(is_credentials(item) for item in credentials_list):
  591. raise TypeError(f"invalid credentials argument: {credentials}")
  592. else:
  593. raise TypeError(f"invalid credentials argument: {credentials}")
  594. credentials_dict = dict(credentials_list)
  595. def check_credentials(username: str, password: str) -> bool:
  596. try:
  597. expected_password = credentials_dict[username]
  598. except KeyError:
  599. return False
  600. return hmac.compare_digest(expected_password, password)
  601. assert check_credentials is not None # help mypy
  602. def process_request(
  603. connection: ServerConnection,
  604. request: Request,
  605. ) -> Response | None:
  606. """
  607. Perform HTTP Basic Authentication.
  608. If it succeeds, set the connection's ``username`` attribute and return
  609. :obj:`None`. If it fails, return an HTTP 401 Unauthorized responss.
  610. """
  611. try:
  612. authorization = request.headers["Authorization"]
  613. except KeyError:
  614. response = connection.respond(
  615. http.HTTPStatus.UNAUTHORIZED,
  616. "Missing credentials\n",
  617. )
  618. response.headers["WWW-Authenticate"] = build_www_authenticate_basic(realm)
  619. return response
  620. try:
  621. username, password = parse_authorization_basic(authorization)
  622. except InvalidHeader:
  623. response = connection.respond(
  624. http.HTTPStatus.UNAUTHORIZED,
  625. "Unsupported credentials\n",
  626. )
  627. response.headers["WWW-Authenticate"] = build_www_authenticate_basic(realm)
  628. return response
  629. if not check_credentials(username, password):
  630. response = connection.respond(
  631. http.HTTPStatus.UNAUTHORIZED,
  632. "Invalid credentials\n",
  633. )
  634. response.headers["WWW-Authenticate"] = build_www_authenticate_basic(realm)
  635. return response
  636. connection.username = username
  637. return None
  638. return process_request