serving.py 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129
  1. """A WSGI and HTTP server for use **during development only**. This
  2. server is convenient to use, but is not designed to be particularly
  3. stable, secure, or efficient. Use a dedicate WSGI server and HTTP
  4. server when deploying to production.
  5. It provides features like interactive debugging and code reloading. Use
  6. ``run_simple`` to start the server. Put this in a ``run.py`` script:
  7. .. code-block:: python
  8. from myapp import create_app
  9. from werkzeug import run_simple
  10. """
  11. from __future__ import annotations
  12. import errno
  13. import io
  14. import os
  15. import selectors
  16. import socket
  17. import socketserver
  18. import sys
  19. import typing as t
  20. from datetime import datetime as dt
  21. from datetime import timedelta
  22. from datetime import timezone
  23. from http.server import BaseHTTPRequestHandler
  24. from http.server import HTTPServer
  25. from urllib.parse import unquote
  26. from urllib.parse import urlsplit
  27. from ._internal import _log
  28. from ._internal import _wsgi_encoding_dance
  29. from .exceptions import InternalServerError
  30. from .http import parse_set_header
  31. from .urls import uri_to_iri
  32. try:
  33. import ssl
  34. connection_dropped_errors: tuple[type[Exception], ...] = (
  35. ConnectionError,
  36. socket.timeout,
  37. ssl.SSLEOFError,
  38. )
  39. except ImportError:
  40. class _SslDummy:
  41. def __getattr__(self, name: str) -> t.Any:
  42. raise RuntimeError( # noqa: B904
  43. "SSL is unavailable because this Python runtime was not"
  44. " compiled with SSL/TLS support."
  45. )
  46. ssl = _SslDummy() # type: ignore
  47. connection_dropped_errors = (ConnectionError, socket.timeout)
  48. _log_add_style = True
  49. if os.name == "nt":
  50. try:
  51. __import__("colorama")
  52. except ImportError:
  53. _log_add_style = False
  54. can_fork = hasattr(os, "fork")
  55. if can_fork:
  56. ForkingMixIn = socketserver.ForkingMixIn
  57. else:
  58. class ForkingMixIn: # type: ignore
  59. pass
  60. try:
  61. af_unix = socket.AF_UNIX
  62. except AttributeError:
  63. af_unix = None # type: ignore
  64. LISTEN_QUEUE = 128
  65. _TSSLContextArg = t.Optional[
  66. t.Union["ssl.SSLContext", tuple[str, t.Optional[str]], t.Literal["adhoc"]]
  67. ]
  68. if t.TYPE_CHECKING:
  69. from _typeshed.wsgi import WSGIApplication
  70. from _typeshed.wsgi import WSGIEnvironment
  71. from cryptography.hazmat.primitives.asymmetric.rsa import (
  72. RSAPrivateKeyWithSerialization,
  73. )
  74. from cryptography.x509 import Certificate
  75. class DechunkedInput(io.RawIOBase):
  76. """An input stream that handles ``Transfer-Encoding: chunked``. Only
  77. used by the dev server, which must not be used in production. A production
  78. WSGI server will have its own robust, secure chunk handler.
  79. """
  80. def __init__(self, rfile: t.IO[bytes]) -> None:
  81. self._rfile = rfile
  82. self._done = False
  83. self._len = 0
  84. def readable(self) -> bool:
  85. return True
  86. def read_chunk_len(self) -> int:
  87. try:
  88. line = self._rfile.readline(100).decode("latin1")
  89. _len = int(line.strip(" \t\r\n"), 16)
  90. except ValueError as e:
  91. raise OSError("Invalid chunk header") from e
  92. if _len < 0:
  93. raise OSError("Negative chunk length not allowed")
  94. return _len
  95. def readinto(self, buf: bytearray) -> int: # type: ignore
  96. read = 0
  97. while not self._done and read < len(buf):
  98. if self._len == 0:
  99. # This is the first chunk or we fully consumed the previous
  100. # one. Read the next length of the next chunk
  101. self._len = self.read_chunk_len()
  102. if self._len == 0:
  103. # Found the final chunk of size 0. The stream is now exhausted,
  104. # but there is still a final newline that should be consumed
  105. self._done = True
  106. if self._len > 0:
  107. # There is data (left) in this chunk, so append it to the
  108. # buffer. If this operation fully consumes the chunk, this will
  109. # reset self._len to 0.
  110. n = min(len(buf), self._len)
  111. # If (read + chunk size) becomes more than len(buf), buf will
  112. # grow beyond the original size and read more data than
  113. # required. So only read as much data as can fit in buf.
  114. if read + n > len(buf):
  115. buf[read:] = self._rfile.read(len(buf) - read)
  116. self._len -= len(buf) - read
  117. read = len(buf)
  118. else:
  119. buf[read : read + n] = self._rfile.read(n)
  120. self._len -= n
  121. read += n
  122. if self._len == 0:
  123. # Skip the terminating newline of a chunk that has been fully
  124. # consumed. This also applies to the 0-sized final chunk
  125. terminator = self._rfile.readline(2)
  126. if terminator not in (b"\n", b"\r\n", b"\r"):
  127. raise OSError("Missing chunk terminating newline")
  128. return read
  129. class WSGIRequestHandler(BaseHTTPRequestHandler):
  130. """A request handler that implements WSGI dispatching."""
  131. server: BaseWSGIServer
  132. @property
  133. def server_version(self) -> str: # type: ignore
  134. return self.server._server_version
  135. def make_environ(self) -> WSGIEnvironment:
  136. request_url = urlsplit(self.path)
  137. url_scheme = "http" if self.server.ssl_context is None else "https"
  138. if not self.client_address:
  139. self.client_address = ("<local>", 0)
  140. elif isinstance(self.client_address, str):
  141. self.client_address = (self.client_address, 0)
  142. # If there was no scheme but the path started with two slashes,
  143. # the first segment may have been incorrectly parsed as the
  144. # netloc, prepend it to the path again.
  145. if not request_url.scheme and request_url.netloc:
  146. path_info = f"/{request_url.netloc}{request_url.path}"
  147. else:
  148. path_info = request_url.path
  149. path_info = unquote(path_info)
  150. environ: WSGIEnvironment = {
  151. "wsgi.version": (1, 0),
  152. "wsgi.url_scheme": url_scheme,
  153. "wsgi.input": self.rfile,
  154. "wsgi.errors": sys.stderr,
  155. "wsgi.multithread": self.server.multithread,
  156. "wsgi.multiprocess": self.server.multiprocess,
  157. "wsgi.run_once": False,
  158. "werkzeug.socket": self.connection,
  159. "SERVER_SOFTWARE": self.server_version,
  160. "REQUEST_METHOD": self.command,
  161. "SCRIPT_NAME": "",
  162. "PATH_INFO": _wsgi_encoding_dance(path_info),
  163. "QUERY_STRING": _wsgi_encoding_dance(request_url.query),
  164. # Non-standard, added by mod_wsgi, uWSGI
  165. "REQUEST_URI": _wsgi_encoding_dance(self.path),
  166. # Non-standard, added by gunicorn
  167. "RAW_URI": _wsgi_encoding_dance(self.path),
  168. "REMOTE_ADDR": self.address_string(),
  169. "REMOTE_PORT": self.port_integer(),
  170. "SERVER_NAME": self.server.server_address[0],
  171. "SERVER_PORT": str(self.server.server_address[1]),
  172. "SERVER_PROTOCOL": self.request_version,
  173. }
  174. for key, value in self.headers.items():
  175. if "_" in key:
  176. continue
  177. key = key.upper().replace("-", "_")
  178. value = value.replace("\r\n", "")
  179. if key not in ("CONTENT_TYPE", "CONTENT_LENGTH"):
  180. key = f"HTTP_{key}"
  181. if key in environ:
  182. value = f"{environ[key]},{value}"
  183. environ[key] = value
  184. if "chunked" in parse_set_header(environ.get("HTTP_TRANSFER_ENCODING")):
  185. environ["wsgi.input_terminated"] = True
  186. environ["wsgi.input"] = DechunkedInput(environ["wsgi.input"])
  187. # Per RFC 2616, if the URL is absolute, use that as the host.
  188. # We're using "has a scheme" to indicate an absolute URL.
  189. if request_url.scheme and request_url.netloc:
  190. environ["HTTP_HOST"] = request_url.netloc
  191. try:
  192. # binary_form=False gives nicer information, but wouldn't be compatible with
  193. # what Nginx or Apache could return.
  194. peer_cert = self.connection.getpeercert(binary_form=True)
  195. if peer_cert is not None:
  196. # Nginx and Apache use PEM format.
  197. environ["SSL_CLIENT_CERT"] = ssl.DER_cert_to_PEM_cert(peer_cert)
  198. except ValueError:
  199. # SSL handshake hasn't finished.
  200. self.server.log("error", "Cannot fetch SSL peer certificate info")
  201. except AttributeError:
  202. # Not using TLS, the socket will not have getpeercert().
  203. pass
  204. return environ
  205. def run_wsgi(self) -> None:
  206. if self.headers.get("Expect", "").lower().strip(" \t") == "100-continue":
  207. self.wfile.write(b"HTTP/1.1 100 Continue\r\n\r\n")
  208. self.environ = environ = self.make_environ()
  209. status_set: str | None = None
  210. headers_set: list[tuple[str, str]] | None = None
  211. status_sent: str | None = None
  212. headers_sent: list[tuple[str, str]] | None = None
  213. chunk_response: bool = False
  214. def write(data: bytes) -> None:
  215. nonlocal status_sent, headers_sent, chunk_response
  216. assert status_set is not None, "write() before start_response"
  217. assert headers_set is not None, "write() before start_response"
  218. if status_sent is None:
  219. status_sent = status_set
  220. headers_sent = headers_set
  221. try:
  222. code_str, msg = status_sent.split(None, 1)
  223. except ValueError:
  224. code_str, msg = status_sent, ""
  225. code = int(code_str)
  226. self.send_response(code, msg)
  227. header_keys = set()
  228. for key, value in headers_sent:
  229. self.send_header(key, value)
  230. header_keys.add(key.lower())
  231. # Use chunked transfer encoding if there is no content
  232. # length. Do not use for 1xx and 204 responses. 304
  233. # responses and HEAD requests are also excluded, which
  234. # is the more conservative behavior and matches other
  235. # parts of the code.
  236. # https://httpwg.org/specs/rfc7230.html#rfc.section.3.3.1
  237. if (
  238. not (
  239. "content-length" in header_keys
  240. or environ["REQUEST_METHOD"] == "HEAD"
  241. or (100 <= code < 200)
  242. or code in {204, 304}
  243. )
  244. and self.protocol_version >= "HTTP/1.1"
  245. ):
  246. chunk_response = True
  247. self.send_header("Transfer-Encoding", "chunked")
  248. # Always close the connection. This disables HTTP/1.1
  249. # keep-alive connections. They aren't handled well by
  250. # Python's http.server because it doesn't know how to
  251. # drain the stream before the next request line.
  252. self.send_header("Connection", "close")
  253. self.end_headers()
  254. assert isinstance(data, bytes), "applications must write bytes"
  255. if data:
  256. if chunk_response:
  257. self.wfile.write(hex(len(data))[2:].encode())
  258. self.wfile.write(b"\r\n")
  259. self.wfile.write(data)
  260. if chunk_response:
  261. self.wfile.write(b"\r\n")
  262. self.wfile.flush()
  263. def start_response(status, headers, exc_info=None): # type: ignore
  264. nonlocal status_set, headers_set
  265. if exc_info:
  266. try:
  267. if headers_sent:
  268. raise exc_info[1].with_traceback(exc_info[2])
  269. finally:
  270. exc_info = None
  271. elif headers_set:
  272. raise AssertionError("Headers already set")
  273. status_set = status
  274. headers_set = headers
  275. return write
  276. def execute(app: WSGIApplication) -> None:
  277. application_iter = app(environ, start_response)
  278. try:
  279. for data in application_iter:
  280. write(data)
  281. if not headers_sent:
  282. write(b"")
  283. if chunk_response:
  284. self.wfile.write(b"0\r\n\r\n")
  285. finally:
  286. # Check for any remaining data in the read socket, and discard it. This
  287. # will read past request.max_content_length, but lets the client see a
  288. # 413 response instead of a connection reset failure. If we supported
  289. # keep-alive connections, this naive approach would break by reading the
  290. # next request line. Since we know that write (above) closes every
  291. # connection we can read everything.
  292. selector = selectors.DefaultSelector()
  293. selector.register(self.connection, selectors.EVENT_READ)
  294. total_size = 0
  295. total_reads = 0
  296. # A timeout of 0 tends to fail because a client needs a small amount of
  297. # time to continue sending its data.
  298. while selector.select(timeout=0.01):
  299. # Only read 10MB into memory at a time.
  300. data = self.rfile.read(10_000_000)
  301. total_size += len(data)
  302. total_reads += 1
  303. # Stop reading on no data, >=10GB, or 1000 reads. If a client sends
  304. # more than that, they'll get a connection reset failure.
  305. if not data or total_size >= 10_000_000_000 or total_reads > 1000:
  306. break
  307. selector.close()
  308. if hasattr(application_iter, "close"):
  309. application_iter.close()
  310. try:
  311. execute(self.server.app)
  312. except connection_dropped_errors as e:
  313. self.connection_dropped(e, environ)
  314. except Exception as e:
  315. if self.server.passthrough_errors:
  316. raise
  317. if status_sent is not None and chunk_response:
  318. self.close_connection = True
  319. try:
  320. # if we haven't yet sent the headers but they are set
  321. # we roll back to be able to set them again.
  322. if status_sent is None:
  323. status_set = None
  324. headers_set = None
  325. execute(InternalServerError())
  326. except Exception:
  327. pass
  328. from .debug.tbtools import DebugTraceback
  329. msg = DebugTraceback(e).render_traceback_text()
  330. self.server.log("error", f"Error on request:\n{msg}")
  331. def handle(self) -> None:
  332. """Handles a request ignoring dropped connections."""
  333. try:
  334. super().handle()
  335. except (ConnectionError, socket.timeout) as e:
  336. self.connection_dropped(e)
  337. except Exception as e:
  338. if self.server.ssl_context is not None and is_ssl_error(e):
  339. self.log_error("SSL error occurred: %s", e)
  340. else:
  341. raise
  342. def connection_dropped(
  343. self, error: BaseException, environ: WSGIEnvironment | None = None
  344. ) -> None:
  345. """Called if the connection was closed by the client. By default
  346. nothing happens.
  347. """
  348. def __getattr__(self, name: str) -> t.Any:
  349. # All HTTP methods are handled by run_wsgi.
  350. if name.startswith("do_"):
  351. return self.run_wsgi
  352. # All other attributes are forwarded to the base class.
  353. return getattr(super(), name)
  354. def address_string(self) -> str:
  355. if getattr(self, "environ", None):
  356. return self.environ["REMOTE_ADDR"] # type: ignore
  357. if not self.client_address:
  358. return "<local>"
  359. return self.client_address[0]
  360. def port_integer(self) -> int:
  361. return self.client_address[1]
  362. # Escape control characters. This is defined (but private) in Python 3.12.
  363. _control_char_table = str.maketrans(
  364. {c: rf"\x{c:02x}" for c in [*range(0x20), *range(0x7F, 0xA0)]}
  365. )
  366. _control_char_table[ord("\\")] = r"\\"
  367. def log_request(self, code: int | str = "-", size: int | str = "-") -> None:
  368. try:
  369. path = uri_to_iri(self.path)
  370. msg = f"{self.command} {path} {self.request_version}"
  371. except AttributeError:
  372. # path isn't set if the requestline was bad
  373. msg = self.requestline
  374. # Escape control characters that may be in the decoded path.
  375. msg = msg.translate(self._control_char_table)
  376. code = str(code)
  377. if code.startswith("1"): # 1xx - Informational
  378. msg = _ansi_style(msg, "bold")
  379. elif code == "200": # 2xx - Success
  380. pass
  381. elif code == "304": # 304 - Resource Not Modified
  382. msg = _ansi_style(msg, "cyan")
  383. elif code.startswith("3"): # 3xx - Redirection
  384. msg = _ansi_style(msg, "green")
  385. elif code == "404": # 404 - Resource Not Found
  386. msg = _ansi_style(msg, "yellow")
  387. elif code.startswith("4"): # 4xx - Client Error
  388. msg = _ansi_style(msg, "bold", "red")
  389. else: # 5xx, or any other response
  390. msg = _ansi_style(msg, "bold", "magenta")
  391. self.log("info", '"%s" %s %s', msg, code, size)
  392. def log_error(self, format: str, *args: t.Any) -> None:
  393. self.log("error", format, *args)
  394. def log_message(self, format: str, *args: t.Any) -> None:
  395. self.log("info", format, *args)
  396. def log(self, type: str, message: str, *args: t.Any) -> None:
  397. # an IPv6 scoped address contains "%" which breaks logging
  398. address_string = self.address_string().replace("%", "%%")
  399. _log(
  400. type,
  401. f"{address_string} - - [{self.log_date_time_string()}] {message}\n",
  402. *args,
  403. )
  404. def _ansi_style(value: str, *styles: str) -> str:
  405. if not _log_add_style:
  406. return value
  407. codes = {
  408. "bold": 1,
  409. "red": 31,
  410. "green": 32,
  411. "yellow": 33,
  412. "magenta": 35,
  413. "cyan": 36,
  414. }
  415. for style in styles:
  416. value = f"\x1b[{codes[style]}m{value}"
  417. return f"{value}\x1b[0m"
  418. def generate_adhoc_ssl_pair(
  419. cn: str | None = None,
  420. ) -> tuple[Certificate, RSAPrivateKeyWithSerialization]:
  421. try:
  422. from cryptography import x509
  423. from cryptography.hazmat.backends import default_backend
  424. from cryptography.hazmat.primitives import hashes
  425. from cryptography.hazmat.primitives.asymmetric import rsa
  426. from cryptography.x509.oid import NameOID
  427. except ImportError:
  428. raise TypeError(
  429. "Using ad-hoc certificates requires the cryptography library."
  430. ) from None
  431. backend = default_backend()
  432. pkey = rsa.generate_private_key(
  433. public_exponent=65537, key_size=2048, backend=backend
  434. )
  435. # pretty damn sure that this is not actually accepted by anyone
  436. if cn is None:
  437. cn = "*"
  438. subject = x509.Name(
  439. [
  440. x509.NameAttribute(NameOID.ORGANIZATION_NAME, "Dummy Certificate"),
  441. x509.NameAttribute(NameOID.COMMON_NAME, cn),
  442. ]
  443. )
  444. backend = default_backend()
  445. cert = (
  446. x509.CertificateBuilder()
  447. .subject_name(subject)
  448. .issuer_name(subject)
  449. .public_key(pkey.public_key())
  450. .serial_number(x509.random_serial_number())
  451. .not_valid_before(dt.now(timezone.utc))
  452. .not_valid_after(dt.now(timezone.utc) + timedelta(days=365))
  453. .add_extension(x509.ExtendedKeyUsage([x509.OID_SERVER_AUTH]), critical=False)
  454. .add_extension(
  455. x509.SubjectAlternativeName([x509.DNSName(cn), x509.DNSName(f"*.{cn}")]),
  456. critical=False,
  457. )
  458. .sign(pkey, hashes.SHA256(), backend)
  459. )
  460. return cert, pkey
  461. def make_ssl_devcert(
  462. base_path: str, host: str | None = None, cn: str | None = None
  463. ) -> tuple[str, str]:
  464. """Creates an SSL key for development. This should be used instead of
  465. the ``'adhoc'`` key which generates a new cert on each server start.
  466. It accepts a path for where it should store the key and cert and
  467. either a host or CN. If a host is given it will use the CN
  468. ``*.host/CN=host``.
  469. For more information see :func:`run_simple`.
  470. .. versionadded:: 0.9
  471. :param base_path: the path to the certificate and key. The extension
  472. ``.crt`` is added for the certificate, ``.key`` is
  473. added for the key.
  474. :param host: the name of the host. This can be used as an alternative
  475. for the `cn`.
  476. :param cn: the `CN` to use.
  477. """
  478. if host is not None:
  479. cn = host
  480. cert, pkey = generate_adhoc_ssl_pair(cn=cn)
  481. from cryptography.hazmat.primitives import serialization
  482. cert_file = f"{base_path}.crt"
  483. pkey_file = f"{base_path}.key"
  484. with open(cert_file, "wb") as f:
  485. f.write(cert.public_bytes(serialization.Encoding.PEM))
  486. with open(pkey_file, "wb") as f:
  487. f.write(
  488. pkey.private_bytes(
  489. encoding=serialization.Encoding.PEM,
  490. format=serialization.PrivateFormat.TraditionalOpenSSL,
  491. encryption_algorithm=serialization.NoEncryption(),
  492. )
  493. )
  494. return cert_file, pkey_file
  495. def generate_adhoc_ssl_context() -> ssl.SSLContext:
  496. """Generates an adhoc SSL context for the development server."""
  497. import atexit
  498. import tempfile
  499. cert, pkey = generate_adhoc_ssl_pair()
  500. from cryptography.hazmat.primitives import serialization
  501. cert_handle, cert_file = tempfile.mkstemp()
  502. pkey_handle, pkey_file = tempfile.mkstemp()
  503. atexit.register(os.remove, pkey_file)
  504. atexit.register(os.remove, cert_file)
  505. os.write(cert_handle, cert.public_bytes(serialization.Encoding.PEM))
  506. os.write(
  507. pkey_handle,
  508. pkey.private_bytes(
  509. encoding=serialization.Encoding.PEM,
  510. format=serialization.PrivateFormat.TraditionalOpenSSL,
  511. encryption_algorithm=serialization.NoEncryption(),
  512. ),
  513. )
  514. os.close(cert_handle)
  515. os.close(pkey_handle)
  516. ctx = load_ssl_context(cert_file, pkey_file)
  517. return ctx
  518. def load_ssl_context(
  519. cert_file: str, pkey_file: str | None = None, protocol: int | None = None
  520. ) -> ssl.SSLContext:
  521. """Loads SSL context from cert/private key files and optional protocol.
  522. Many parameters are directly taken from the API of
  523. :py:class:`ssl.SSLContext`.
  524. :param cert_file: Path of the certificate to use.
  525. :param pkey_file: Path of the private key to use. If not given, the key
  526. will be obtained from the certificate file.
  527. :param protocol: A ``PROTOCOL`` constant from the :mod:`ssl` module.
  528. Defaults to :data:`ssl.PROTOCOL_TLS_SERVER`.
  529. """
  530. if protocol is None:
  531. protocol = ssl.PROTOCOL_TLS_SERVER
  532. ctx = ssl.SSLContext(protocol)
  533. ctx.load_cert_chain(cert_file, pkey_file)
  534. return ctx
  535. def is_ssl_error(error: Exception | None = None) -> bool:
  536. """Checks if the given error (or the current one) is an SSL error."""
  537. if error is None:
  538. error = t.cast(Exception, sys.exc_info()[1])
  539. return isinstance(error, ssl.SSLError)
  540. def select_address_family(host: str, port: int) -> socket.AddressFamily:
  541. """Return ``AF_INET4``, ``AF_INET6``, or ``AF_UNIX`` depending on
  542. the host and port."""
  543. if host.startswith("unix://"):
  544. return socket.AF_UNIX
  545. elif ":" in host and hasattr(socket, "AF_INET6"):
  546. return socket.AF_INET6
  547. return socket.AF_INET
  548. def get_sockaddr(
  549. host: str, port: int, family: socket.AddressFamily
  550. ) -> tuple[str, int] | str:
  551. """Return a fully qualified socket address that can be passed to
  552. :func:`socket.bind`."""
  553. if family == af_unix:
  554. # Absolute path avoids IDNA encoding error when path starts with dot.
  555. return os.path.abspath(host.partition("://")[2])
  556. try:
  557. res = socket.getaddrinfo(
  558. host, port, family, socket.SOCK_STREAM, socket.IPPROTO_TCP
  559. )
  560. except socket.gaierror:
  561. return host, port
  562. return res[0][4] # type: ignore
  563. def get_interface_ip(family: socket.AddressFamily) -> str:
  564. """Get the IP address of an external interface. Used when binding to
  565. 0.0.0.0 or ::1 to show a more useful URL.
  566. :meta private:
  567. """
  568. # arbitrary private address
  569. host = "fd31:f903:5ab5:1::1" if family == socket.AF_INET6 else "10.253.155.219"
  570. with socket.socket(family, socket.SOCK_DGRAM) as s:
  571. try:
  572. s.connect((host, 58162))
  573. except OSError:
  574. return "::1" if family == socket.AF_INET6 else "127.0.0.1"
  575. return s.getsockname()[0] # type: ignore
  576. class BaseWSGIServer(HTTPServer):
  577. """A WSGI server that that handles one request at a time.
  578. Use :func:`make_server` to create a server instance.
  579. """
  580. multithread = False
  581. multiprocess = False
  582. request_queue_size = LISTEN_QUEUE
  583. allow_reuse_address = True
  584. def __init__(
  585. self,
  586. host: str,
  587. port: int,
  588. app: WSGIApplication,
  589. handler: type[WSGIRequestHandler] | None = None,
  590. passthrough_errors: bool = False,
  591. ssl_context: _TSSLContextArg | None = None,
  592. fd: int | None = None,
  593. ) -> None:
  594. if handler is None:
  595. handler = WSGIRequestHandler
  596. # If the handler doesn't directly set a protocol version and
  597. # thread or process workers are used, then allow chunked
  598. # responses and keep-alive connections by enabling HTTP/1.1.
  599. if "protocol_version" not in vars(handler) and (
  600. self.multithread or self.multiprocess
  601. ):
  602. handler.protocol_version = "HTTP/1.1"
  603. self.host = host
  604. self.port = port
  605. self.app = app
  606. self.passthrough_errors = passthrough_errors
  607. self.address_family = address_family = select_address_family(host, port)
  608. server_address = get_sockaddr(host, int(port), address_family)
  609. # Remove a leftover Unix socket file from a previous run. Don't
  610. # remove a file that was set up by run_simple.
  611. if address_family == af_unix and fd is None:
  612. server_address = t.cast(str, server_address)
  613. if os.path.exists(server_address):
  614. os.unlink(server_address)
  615. # Bind and activate will be handled manually, it should only
  616. # happen if we're not using a socket that was already set up.
  617. super().__init__(
  618. server_address, # type: ignore[arg-type]
  619. handler,
  620. bind_and_activate=False,
  621. )
  622. if fd is None:
  623. # No existing socket descriptor, do bind_and_activate=True.
  624. try:
  625. self.server_bind()
  626. self.server_activate()
  627. except OSError as e:
  628. # Catch connection issues and show them without the traceback. Show
  629. # extra instructions for address not found, and for macOS.
  630. self.server_close()
  631. print(e.strerror, file=sys.stderr)
  632. if e.errno == errno.EADDRINUSE:
  633. print(
  634. f"Port {port} is in use by another program. Either identify and"
  635. " stop that program, or start the server with a different"
  636. " port.",
  637. file=sys.stderr,
  638. )
  639. if sys.platform == "darwin" and port == 5000:
  640. print(
  641. "On macOS, try searching for and disabling"
  642. " 'AirPlay Receiver' in System Settings.",
  643. file=sys.stderr,
  644. )
  645. sys.exit(1)
  646. except BaseException:
  647. self.server_close()
  648. raise
  649. else:
  650. # TCPServer automatically opens a socket even if bind_and_activate is False.
  651. # Close it to silence a ResourceWarning.
  652. self.server_close()
  653. # Use the passed in socket directly.
  654. self.socket = socket.fromfd(fd, address_family, socket.SOCK_STREAM)
  655. self.server_address = self.socket.getsockname()
  656. if address_family != af_unix:
  657. # If port was 0, this will record the bound port.
  658. self.port = self.server_address[1]
  659. if ssl_context is not None:
  660. if isinstance(ssl_context, tuple):
  661. ssl_context = load_ssl_context(*ssl_context)
  662. elif ssl_context == "adhoc":
  663. ssl_context = generate_adhoc_ssl_context()
  664. self.socket = ssl_context.wrap_socket(self.socket, server_side=True)
  665. self.ssl_context: ssl.SSLContext | None = ssl_context
  666. else:
  667. self.ssl_context = None
  668. import importlib.metadata
  669. self._server_version = f"Werkzeug/{importlib.metadata.version('werkzeug')}"
  670. def log(self, type: str, message: str, *args: t.Any) -> None:
  671. _log(type, message, *args)
  672. def serve_forever(self, poll_interval: float = 0.5) -> None:
  673. try:
  674. super().serve_forever(poll_interval=poll_interval)
  675. except KeyboardInterrupt:
  676. pass
  677. finally:
  678. self.server_close()
  679. def handle_error(
  680. self, request: t.Any, client_address: tuple[str, int] | str
  681. ) -> None:
  682. if self.passthrough_errors:
  683. raise
  684. return super().handle_error(request, client_address)
  685. def log_startup(self) -> None:
  686. """Show information about the address when starting the server."""
  687. dev_warning = (
  688. "WARNING: This is a development server. Do not use it in a production"
  689. " deployment. Use a production WSGI server instead."
  690. )
  691. dev_warning = _ansi_style(dev_warning, "bold", "red")
  692. messages = [dev_warning]
  693. if self.address_family == af_unix:
  694. messages.append(f" * Running on {self.host}")
  695. else:
  696. scheme = "http" if self.ssl_context is None else "https"
  697. display_hostname = self.host
  698. if self.host in {"0.0.0.0", "::"}:
  699. messages.append(f" * Running on all addresses ({self.host})")
  700. if self.host == "0.0.0.0":
  701. localhost = "127.0.0.1"
  702. display_hostname = get_interface_ip(socket.AF_INET)
  703. else:
  704. localhost = "[::1]"
  705. display_hostname = get_interface_ip(socket.AF_INET6)
  706. messages.append(f" * Running on {scheme}://{localhost}:{self.port}")
  707. if ":" in display_hostname:
  708. display_hostname = f"[{display_hostname}]"
  709. messages.append(f" * Running on {scheme}://{display_hostname}:{self.port}")
  710. _log("info", "\n".join(messages))
  711. class ThreadedWSGIServer(socketserver.ThreadingMixIn, BaseWSGIServer):
  712. """A WSGI server that handles concurrent requests in separate
  713. threads.
  714. Use :func:`make_server` to create a server instance.
  715. """
  716. multithread = True
  717. daemon_threads = True
  718. class ForkingWSGIServer(ForkingMixIn, BaseWSGIServer):
  719. """A WSGI server that handles concurrent requests in separate forked
  720. processes.
  721. Use :func:`make_server` to create a server instance.
  722. """
  723. multiprocess = True
  724. def __init__(
  725. self,
  726. host: str,
  727. port: int,
  728. app: WSGIApplication,
  729. processes: int = 40,
  730. handler: type[WSGIRequestHandler] | None = None,
  731. passthrough_errors: bool = False,
  732. ssl_context: _TSSLContextArg | None = None,
  733. fd: int | None = None,
  734. ) -> None:
  735. if not can_fork:
  736. raise ValueError("Your platform does not support forking.")
  737. super().__init__(host, port, app, handler, passthrough_errors, ssl_context, fd)
  738. self.max_children = processes
  739. def make_server(
  740. host: str,
  741. port: int,
  742. app: WSGIApplication,
  743. threaded: bool = False,
  744. processes: int = 1,
  745. request_handler: type[WSGIRequestHandler] | None = None,
  746. passthrough_errors: bool = False,
  747. ssl_context: _TSSLContextArg | None = None,
  748. fd: int | None = None,
  749. ) -> BaseWSGIServer:
  750. """Create an appropriate WSGI server instance based on the value of
  751. ``threaded`` and ``processes``.
  752. This is called from :func:`run_simple`, but can be used separately
  753. to have access to the server object, such as to run it in a separate
  754. thread.
  755. See :func:`run_simple` for parameter docs.
  756. """
  757. if threaded and processes > 1:
  758. raise ValueError("Cannot have a multi-thread and multi-process server.")
  759. if threaded:
  760. return ThreadedWSGIServer(
  761. host, port, app, request_handler, passthrough_errors, ssl_context, fd=fd
  762. )
  763. if processes > 1:
  764. return ForkingWSGIServer(
  765. host,
  766. port,
  767. app,
  768. processes,
  769. request_handler,
  770. passthrough_errors,
  771. ssl_context,
  772. fd=fd,
  773. )
  774. return BaseWSGIServer(
  775. host, port, app, request_handler, passthrough_errors, ssl_context, fd=fd
  776. )
  777. def is_running_from_reloader() -> bool:
  778. """Check if the server is running as a subprocess within the
  779. Werkzeug reloader.
  780. .. versionadded:: 0.10
  781. """
  782. return os.environ.get("WERKZEUG_RUN_MAIN") == "true"
  783. def run_simple(
  784. hostname: str,
  785. port: int,
  786. application: WSGIApplication,
  787. use_reloader: bool = False,
  788. use_debugger: bool = False,
  789. use_evalex: bool = True,
  790. extra_files: t.Iterable[str] | None = None,
  791. exclude_patterns: t.Iterable[str] | None = None,
  792. reloader_interval: int = 1,
  793. reloader_type: str = "auto",
  794. threaded: bool = False,
  795. processes: int = 1,
  796. request_handler: type[WSGIRequestHandler] | None = None,
  797. static_files: dict[str, str | tuple[str, str]] | None = None,
  798. passthrough_errors: bool = False,
  799. ssl_context: _TSSLContextArg | None = None,
  800. ) -> None:
  801. """Start a development server for a WSGI application. Various
  802. optional features can be enabled.
  803. .. warning::
  804. Do not use the development server when deploying to production.
  805. It is intended for use only during local development. It is not
  806. designed to be particularly efficient, stable, or secure.
  807. :param hostname: The host to bind to, for example ``'localhost'``.
  808. Can be a domain, IPv4 or IPv6 address, or file path starting
  809. with ``unix://`` for a Unix socket.
  810. :param port: The port to bind to, for example ``8080``. Using ``0``
  811. tells the OS to pick a random free port.
  812. :param application: The WSGI application to run.
  813. :param use_reloader: Use a reloader process to restart the server
  814. process when files are changed.
  815. :param use_debugger: Use Werkzeug's debugger, which will show
  816. formatted tracebacks on unhandled exceptions.
  817. :param use_evalex: Make the debugger interactive. A Python terminal
  818. can be opened for any frame in the traceback. Some protection is
  819. provided by requiring a PIN, but this should never be enabled
  820. on a publicly visible server.
  821. :param extra_files: The reloader will watch these files for changes
  822. in addition to Python modules. For example, watch a
  823. configuration file.
  824. :param exclude_patterns: The reloader will ignore changes to any
  825. files matching these :mod:`fnmatch` patterns. For example,
  826. ignore cache files.
  827. :param reloader_interval: How often the reloader tries to check for
  828. changes.
  829. :param reloader_type: The reloader to use. The ``'stat'`` reloader
  830. is built in, but may require significant CPU to watch files. The
  831. ``'watchdog'`` reloader is much more efficient but requires
  832. installing the ``watchdog`` package first.
  833. :param threaded: Handle concurrent requests using threads. Cannot be
  834. used with ``processes``.
  835. :param processes: Handle concurrent requests using up to this number
  836. of processes. Cannot be used with ``threaded``.
  837. :param request_handler: Use a different
  838. :class:`~BaseHTTPServer.BaseHTTPRequestHandler` subclass to
  839. handle requests.
  840. :param static_files: A dict mapping URL prefixes to directories to
  841. serve static files from using
  842. :class:`~werkzeug.middleware.SharedDataMiddleware`.
  843. :param passthrough_errors: Don't catch unhandled exceptions at the
  844. server level, let the server crash instead. If ``use_debugger``
  845. is enabled, the debugger will still catch such errors.
  846. :param ssl_context: Configure TLS to serve over HTTPS. Can be an
  847. :class:`ssl.SSLContext` object, a ``(cert_file, key_file)``
  848. tuple to create a typical context, or the string ``'adhoc'`` to
  849. generate a temporary self-signed certificate.
  850. .. versionchanged:: 2.1
  851. Instructions are shown for dealing with an "address already in
  852. use" error.
  853. .. versionchanged:: 2.1
  854. Running on ``0.0.0.0`` or ``::`` shows the loopback IP in
  855. addition to a real IP.
  856. .. versionchanged:: 2.1
  857. The command-line interface was removed.
  858. .. versionchanged:: 2.0
  859. Running on ``0.0.0.0`` or ``::`` shows a real IP address that
  860. was bound as well as a warning not to run the development server
  861. in production.
  862. .. versionchanged:: 2.0
  863. The ``exclude_patterns`` parameter was added.
  864. .. versionchanged:: 0.15
  865. Bind to a Unix socket by passing a ``hostname`` that starts with
  866. ``unix://``.
  867. .. versionchanged:: 0.10
  868. Improved the reloader and added support for changing the backend
  869. through the ``reloader_type`` parameter.
  870. .. versionchanged:: 0.9
  871. A command-line interface was added.
  872. .. versionchanged:: 0.8
  873. ``ssl_context`` can be a tuple of paths to the certificate and
  874. private key files.
  875. .. versionchanged:: 0.6
  876. The ``ssl_context`` parameter was added.
  877. .. versionchanged:: 0.5
  878. The ``static_files`` and ``passthrough_errors`` parameters were
  879. added.
  880. """
  881. if not isinstance(port, int):
  882. raise TypeError("port must be an integer")
  883. if static_files:
  884. from .middleware.shared_data import SharedDataMiddleware
  885. application = SharedDataMiddleware(application, static_files)
  886. if use_debugger:
  887. from .debug import DebuggedApplication
  888. application = DebuggedApplication(application, evalex=use_evalex)
  889. # Allow the specified hostname to use the debugger, in addition to
  890. # localhost domains.
  891. application.trusted_hosts.append(hostname)
  892. if not is_running_from_reloader():
  893. fd = None
  894. else:
  895. fd = int(os.environ["WERKZEUG_SERVER_FD"])
  896. srv = make_server(
  897. hostname,
  898. port,
  899. application,
  900. threaded,
  901. processes,
  902. request_handler,
  903. passthrough_errors,
  904. ssl_context,
  905. fd=fd,
  906. )
  907. srv.socket.set_inheritable(True)
  908. os.environ["WERKZEUG_SERVER_FD"] = str(srv.fileno())
  909. if not is_running_from_reloader():
  910. srv.log_startup()
  911. _log("info", _ansi_style("Press CTRL+C to quit", "yellow"))
  912. if use_reloader:
  913. from ._reloader import run_with_reloader
  914. try:
  915. run_with_reloader(
  916. srv.serve_forever,
  917. extra_files=extra_files,
  918. exclude_patterns=exclude_patterns,
  919. interval=reloader_interval,
  920. reloader_type=reloader_type,
  921. )
  922. finally:
  923. srv.server_close()
  924. else:
  925. srv.serve_forever()