serving.py 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081
  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. import io
  12. import os
  13. import platform
  14. import signal
  15. import socket
  16. import socketserver
  17. import sys
  18. import typing as t
  19. import warnings
  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 ._internal import _log
  26. from ._internal import _wsgi_encoding_dance
  27. from .exceptions import InternalServerError
  28. from .urls import uri_to_iri
  29. from .urls import url_parse
  30. from .urls import url_unquote
  31. try:
  32. import ssl
  33. except ImportError:
  34. class _SslDummy:
  35. def __getattr__(self, name: str) -> t.Any:
  36. raise RuntimeError("SSL support unavailable") # noqa: B904
  37. ssl = _SslDummy() # type: ignore
  38. _log_add_style = True
  39. if os.name == "nt":
  40. try:
  41. __import__("colorama")
  42. except ImportError:
  43. _log_add_style = False
  44. can_fork = hasattr(os, "fork")
  45. if can_fork:
  46. ForkingMixIn = socketserver.ForkingMixIn
  47. else:
  48. class ForkingMixIn: # type: ignore
  49. pass
  50. try:
  51. af_unix = socket.AF_UNIX
  52. except AttributeError:
  53. af_unix = None # type: ignore
  54. LISTEN_QUEUE = 128
  55. can_open_by_fd = not platform.system() == "Windows" and hasattr(socket, "fromfd")
  56. _TSSLContextArg = t.Optional[
  57. t.Union["ssl.SSLContext", t.Tuple[str, t.Optional[str]], "te.Literal['adhoc']"]
  58. ]
  59. if t.TYPE_CHECKING:
  60. import typing_extensions as te # noqa: F401
  61. from _typeshed.wsgi import WSGIApplication
  62. from _typeshed.wsgi import WSGIEnvironment
  63. from cryptography.hazmat.primitives.asymmetric.rsa import (
  64. RSAPrivateKeyWithSerialization,
  65. )
  66. from cryptography.x509 import Certificate
  67. class DechunkedInput(io.RawIOBase):
  68. """An input stream that handles Transfer-Encoding 'chunked'"""
  69. def __init__(self, rfile: t.IO[bytes]) -> None:
  70. self._rfile = rfile
  71. self._done = False
  72. self._len = 0
  73. def readable(self) -> bool:
  74. return True
  75. def read_chunk_len(self) -> int:
  76. try:
  77. line = self._rfile.readline().decode("latin1")
  78. _len = int(line.strip(), 16)
  79. except ValueError as e:
  80. raise OSError("Invalid chunk header") from e
  81. if _len < 0:
  82. raise OSError("Negative chunk length not allowed")
  83. return _len
  84. def readinto(self, buf: bytearray) -> int: # type: ignore
  85. read = 0
  86. while not self._done and read < len(buf):
  87. if self._len == 0:
  88. # This is the first chunk or we fully consumed the previous
  89. # one. Read the next length of the next chunk
  90. self._len = self.read_chunk_len()
  91. if self._len == 0:
  92. # Found the final chunk of size 0. The stream is now exhausted,
  93. # but there is still a final newline that should be consumed
  94. self._done = True
  95. if self._len > 0:
  96. # There is data (left) in this chunk, so append it to the
  97. # buffer. If this operation fully consumes the chunk, this will
  98. # reset self._len to 0.
  99. n = min(len(buf), self._len)
  100. # If (read + chunk size) becomes more than len(buf), buf will
  101. # grow beyond the original size and read more data than
  102. # required. So only read as much data as can fit in buf.
  103. if read + n > len(buf):
  104. buf[read:] = self._rfile.read(len(buf) - read)
  105. self._len -= len(buf) - read
  106. read = len(buf)
  107. else:
  108. buf[read : read + n] = self._rfile.read(n)
  109. self._len -= n
  110. read += n
  111. if self._len == 0:
  112. # Skip the terminating newline of a chunk that has been fully
  113. # consumed. This also applies to the 0-sized final chunk
  114. terminator = self._rfile.readline()
  115. if terminator not in (b"\n", b"\r\n", b"\r"):
  116. raise OSError("Missing chunk terminating newline")
  117. return read
  118. class WSGIRequestHandler(BaseHTTPRequestHandler):
  119. """A request handler that implements WSGI dispatching."""
  120. server: "BaseWSGIServer"
  121. @property
  122. def server_version(self) -> str: # type: ignore
  123. from . import __version__
  124. return f"Werkzeug/{__version__}"
  125. def make_environ(self) -> "WSGIEnvironment":
  126. request_url = url_parse(self.path)
  127. def shutdown_server() -> None:
  128. warnings.warn(
  129. "The 'environ['werkzeug.server.shutdown']' function is"
  130. " deprecated and will be removed in Werkzeug 2.1.",
  131. stacklevel=2,
  132. )
  133. self.server.shutdown_signal = True
  134. url_scheme = "http" if self.server.ssl_context is None else "https"
  135. if not self.client_address:
  136. self.client_address = ("<local>", 0)
  137. elif isinstance(self.client_address, str):
  138. self.client_address = (self.client_address, 0)
  139. # If there was no scheme but the path started with two slashes,
  140. # the first segment may have been incorrectly parsed as the
  141. # netloc, prepend it to the path again.
  142. if not request_url.scheme and request_url.netloc:
  143. path_info = f"/{request_url.netloc}{request_url.path}"
  144. else:
  145. path_info = request_url.path
  146. path_info = url_unquote(path_info)
  147. environ: "WSGIEnvironment" = {
  148. "wsgi.version": (1, 0),
  149. "wsgi.url_scheme": url_scheme,
  150. "wsgi.input": self.rfile,
  151. "wsgi.errors": sys.stderr,
  152. "wsgi.multithread": self.server.multithread,
  153. "wsgi.multiprocess": self.server.multiprocess,
  154. "wsgi.run_once": False,
  155. "werkzeug.server.shutdown": shutdown_server,
  156. "werkzeug.socket": self.connection,
  157. "SERVER_SOFTWARE": self.server_version,
  158. "REQUEST_METHOD": self.command,
  159. "SCRIPT_NAME": "",
  160. "PATH_INFO": _wsgi_encoding_dance(path_info),
  161. "QUERY_STRING": _wsgi_encoding_dance(request_url.query),
  162. # Non-standard, added by mod_wsgi, uWSGI
  163. "REQUEST_URI": _wsgi_encoding_dance(self.path),
  164. # Non-standard, added by gunicorn
  165. "RAW_URI": _wsgi_encoding_dance(self.path),
  166. "REMOTE_ADDR": self.address_string(),
  167. "REMOTE_PORT": self.port_integer(),
  168. "SERVER_NAME": self.server.server_address[0],
  169. "SERVER_PORT": str(self.server.server_address[1]),
  170. "SERVER_PROTOCOL": self.request_version,
  171. }
  172. for key, value in self.headers.items():
  173. key = key.upper().replace("-", "_")
  174. value = value.replace("\r\n", "")
  175. if key not in ("CONTENT_TYPE", "CONTENT_LENGTH"):
  176. key = f"HTTP_{key}"
  177. if key in environ:
  178. value = f"{environ[key]},{value}"
  179. environ[key] = value
  180. if environ.get("HTTP_TRANSFER_ENCODING", "").strip().lower() == "chunked":
  181. environ["wsgi.input_terminated"] = True
  182. environ["wsgi.input"] = DechunkedInput(environ["wsgi.input"])
  183. # Per RFC 2616, if the URL is absolute, use that as the host.
  184. # We're using "has a scheme" to indicate an absolute URL.
  185. if request_url.scheme and request_url.netloc:
  186. environ["HTTP_HOST"] = request_url.netloc
  187. try:
  188. # binary_form=False gives nicer information, but wouldn't be compatible with
  189. # what Nginx or Apache could return.
  190. peer_cert = self.connection.getpeercert(binary_form=True)
  191. if peer_cert is not None:
  192. # Nginx and Apache use PEM format.
  193. environ["SSL_CLIENT_CERT"] = ssl.DER_cert_to_PEM_cert(peer_cert)
  194. except ValueError:
  195. # SSL handshake hasn't finished.
  196. self.server.log("error", "Cannot fetch SSL peer certificate info")
  197. except AttributeError:
  198. # Not using TLS, the socket will not have getpeercert().
  199. pass
  200. return environ
  201. def run_wsgi(self) -> None:
  202. if self.headers.get("Expect", "").lower().strip() == "100-continue":
  203. self.wfile.write(b"HTTP/1.1 100 Continue\r\n\r\n")
  204. self.environ = environ = self.make_environ()
  205. status_set: t.Optional[str] = None
  206. headers_set: t.Optional[t.List[t.Tuple[str, str]]] = None
  207. status_sent: t.Optional[str] = None
  208. headers_sent: t.Optional[t.List[t.Tuple[str, str]]] = None
  209. def write(data: bytes) -> None:
  210. nonlocal status_sent, headers_sent
  211. assert status_set is not None, "write() before start_response"
  212. assert headers_set is not None, "write() before start_response"
  213. if status_sent is None:
  214. status_sent = status_set
  215. headers_sent = headers_set
  216. try:
  217. code_str, msg = status_sent.split(None, 1)
  218. except ValueError:
  219. code_str, msg = status_sent, ""
  220. code = int(code_str)
  221. self.send_response(code, msg)
  222. header_keys = set()
  223. for key, value in headers_sent:
  224. self.send_header(key, value)
  225. key = key.lower()
  226. header_keys.add(key)
  227. if not (
  228. "content-length" in header_keys
  229. or environ["REQUEST_METHOD"] == "HEAD"
  230. or code < 200
  231. or code in (204, 304)
  232. ):
  233. self.close_connection = True
  234. self.send_header("Connection", "close")
  235. if "server" not in header_keys:
  236. self.send_header("Server", self.version_string())
  237. if "date" not in header_keys:
  238. self.send_header("Date", self.date_time_string())
  239. self.end_headers()
  240. assert isinstance(data, bytes), "applications must write bytes"
  241. self.wfile.write(data)
  242. self.wfile.flush()
  243. def start_response(status, headers, exc_info=None): # type: ignore
  244. nonlocal status_set, headers_set
  245. if exc_info:
  246. try:
  247. if headers_sent:
  248. raise exc_info[1].with_traceback(exc_info[2])
  249. finally:
  250. exc_info = None
  251. elif headers_set:
  252. raise AssertionError("Headers already set")
  253. status_set = status
  254. headers_set = headers
  255. return write
  256. def execute(app: "WSGIApplication") -> None:
  257. application_iter = app(environ, start_response)
  258. try:
  259. for data in application_iter:
  260. write(data)
  261. if not headers_sent:
  262. write(b"")
  263. finally:
  264. if hasattr(application_iter, "close"):
  265. application_iter.close() # type: ignore
  266. try:
  267. execute(self.server.app)
  268. except (ConnectionError, socket.timeout) as e:
  269. self.connection_dropped(e, environ)
  270. except Exception:
  271. if self.server.passthrough_errors:
  272. raise
  273. from .debug.tbtools import get_current_traceback
  274. traceback = get_current_traceback(ignore_system_exceptions=True)
  275. try:
  276. # if we haven't yet sent the headers but they are set
  277. # we roll back to be able to set them again.
  278. if status_sent is None:
  279. status_set = None
  280. headers_set = None
  281. execute(InternalServerError())
  282. except Exception:
  283. pass
  284. self.server.log("error", "Error on request:\n%s", traceback.plaintext)
  285. def handle(self) -> None:
  286. """Handles a request ignoring dropped connections."""
  287. try:
  288. BaseHTTPRequestHandler.handle(self)
  289. except (ConnectionError, socket.timeout) as e:
  290. self.connection_dropped(e)
  291. except Exception as e:
  292. if self.server.ssl_context is not None and is_ssl_error(e):
  293. self.log_error("SSL error occurred: %s", e)
  294. else:
  295. raise
  296. if self.server.shutdown_signal:
  297. self.initiate_shutdown()
  298. def initiate_shutdown(self) -> None:
  299. if is_running_from_reloader():
  300. # Windows does not provide SIGKILL, go with SIGTERM then.
  301. sig = getattr(signal, "SIGKILL", signal.SIGTERM)
  302. os.kill(os.getpid(), sig)
  303. self.server._BaseServer__shutdown_request = True # type: ignore
  304. def connection_dropped(
  305. self, error: BaseException, environ: t.Optional["WSGIEnvironment"] = None
  306. ) -> None:
  307. """Called if the connection was closed by the client. By default
  308. nothing happens.
  309. """
  310. def handle_one_request(self) -> None:
  311. """Handle a single HTTP request."""
  312. self.raw_requestline = self.rfile.readline()
  313. if not self.raw_requestline:
  314. self.close_connection = True
  315. elif self.parse_request():
  316. self.run_wsgi()
  317. def send_response(self, code: int, message: t.Optional[str] = None) -> None:
  318. """Send the response header and log the response code."""
  319. self.log_request(code)
  320. if message is None:
  321. message = self.responses[code][0] if code in self.responses else ""
  322. if self.request_version != "HTTP/0.9":
  323. hdr = f"{self.protocol_version} {code} {message}\r\n"
  324. self.wfile.write(hdr.encode("ascii"))
  325. def version_string(self) -> str:
  326. return super().version_string().strip()
  327. def address_string(self) -> str:
  328. if getattr(self, "environ", None):
  329. return self.environ["REMOTE_ADDR"] # type: ignore
  330. if not self.client_address:
  331. return "<local>"
  332. return self.client_address[0]
  333. def port_integer(self) -> int:
  334. return self.client_address[1]
  335. def log_request(
  336. self, code: t.Union[int, str] = "-", size: t.Union[int, str] = "-"
  337. ) -> None:
  338. try:
  339. path = uri_to_iri(self.path)
  340. msg = f"{self.command} {path} {self.request_version}"
  341. except AttributeError:
  342. # path isn't set if the requestline was bad
  343. msg = self.requestline
  344. code = str(code)
  345. if _log_add_style:
  346. if code[0] == "1": # 1xx - Informational
  347. msg = _ansi_style(msg, "bold")
  348. elif code == "200": # 2xx - Success
  349. pass
  350. elif code == "304": # 304 - Resource Not Modified
  351. msg = _ansi_style(msg, "cyan")
  352. elif code[0] == "3": # 3xx - Redirection
  353. msg = _ansi_style(msg, "green")
  354. elif code == "404": # 404 - Resource Not Found
  355. msg = _ansi_style(msg, "yellow")
  356. elif code[0] == "4": # 4xx - Client Error
  357. msg = _ansi_style(msg, "bold", "red")
  358. else: # 5xx, or any other response
  359. msg = _ansi_style(msg, "bold", "magenta")
  360. self.log("info", '"%s" %s %s', msg, code, size)
  361. def log_error(self, format: str, *args: t.Any) -> None:
  362. self.log("error", format, *args)
  363. def log_message(self, format: str, *args: t.Any) -> None:
  364. self.log("info", format, *args)
  365. def log(self, type: str, message: str, *args: t.Any) -> None:
  366. _log(
  367. type,
  368. f"{self.address_string()} - - [{self.log_date_time_string()}] {message}\n",
  369. *args,
  370. )
  371. def _ansi_style(value: str, *styles: str) -> str:
  372. codes = {
  373. "bold": 1,
  374. "red": 31,
  375. "green": 32,
  376. "yellow": 33,
  377. "magenta": 35,
  378. "cyan": 36,
  379. }
  380. for style in styles:
  381. value = f"\x1b[{codes[style]}m{value}"
  382. return f"{value}\x1b[0m"
  383. def generate_adhoc_ssl_pair(
  384. cn: t.Optional[str] = None,
  385. ) -> t.Tuple["Certificate", "RSAPrivateKeyWithSerialization"]:
  386. try:
  387. from cryptography import x509
  388. from cryptography.x509.oid import NameOID
  389. from cryptography.hazmat.backends import default_backend
  390. from cryptography.hazmat.primitives import hashes
  391. from cryptography.hazmat.primitives.asymmetric import rsa
  392. except ImportError:
  393. raise TypeError(
  394. "Using ad-hoc certificates requires the cryptography library."
  395. ) from None
  396. backend = default_backend()
  397. pkey = rsa.generate_private_key(
  398. public_exponent=65537, key_size=2048, backend=backend
  399. )
  400. # pretty damn sure that this is not actually accepted by anyone
  401. if cn is None:
  402. cn = "*"
  403. subject = x509.Name(
  404. [
  405. x509.NameAttribute(NameOID.ORGANIZATION_NAME, "Dummy Certificate"),
  406. x509.NameAttribute(NameOID.COMMON_NAME, cn),
  407. ]
  408. )
  409. backend = default_backend()
  410. cert = (
  411. x509.CertificateBuilder()
  412. .subject_name(subject)
  413. .issuer_name(subject)
  414. .public_key(pkey.public_key())
  415. .serial_number(x509.random_serial_number())
  416. .not_valid_before(dt.now(timezone.utc))
  417. .not_valid_after(dt.now(timezone.utc) + timedelta(days=365))
  418. .add_extension(x509.ExtendedKeyUsage([x509.OID_SERVER_AUTH]), critical=False)
  419. .add_extension(x509.SubjectAlternativeName([x509.DNSName(cn)]), critical=False)
  420. .sign(pkey, hashes.SHA256(), backend)
  421. )
  422. return cert, pkey
  423. def make_ssl_devcert(
  424. base_path: str, host: t.Optional[str] = None, cn: t.Optional[str] = None
  425. ) -> t.Tuple[str, str]:
  426. """Creates an SSL key for development. This should be used instead of
  427. the ``'adhoc'`` key which generates a new cert on each server start.
  428. It accepts a path for where it should store the key and cert and
  429. either a host or CN. If a host is given it will use the CN
  430. ``*.host/CN=host``.
  431. For more information see :func:`run_simple`.
  432. .. versionadded:: 0.9
  433. :param base_path: the path to the certificate and key. The extension
  434. ``.crt`` is added for the certificate, ``.key`` is
  435. added for the key.
  436. :param host: the name of the host. This can be used as an alternative
  437. for the `cn`.
  438. :param cn: the `CN` to use.
  439. """
  440. if host is not None:
  441. cn = f"*.{host}/CN={host}"
  442. cert, pkey = generate_adhoc_ssl_pair(cn=cn)
  443. from cryptography.hazmat.primitives import serialization
  444. cert_file = f"{base_path}.crt"
  445. pkey_file = f"{base_path}.key"
  446. with open(cert_file, "wb") as f:
  447. f.write(cert.public_bytes(serialization.Encoding.PEM))
  448. with open(pkey_file, "wb") as f:
  449. f.write(
  450. pkey.private_bytes(
  451. encoding=serialization.Encoding.PEM,
  452. format=serialization.PrivateFormat.TraditionalOpenSSL,
  453. encryption_algorithm=serialization.NoEncryption(),
  454. )
  455. )
  456. return cert_file, pkey_file
  457. def generate_adhoc_ssl_context() -> "ssl.SSLContext":
  458. """Generates an adhoc SSL context for the development server."""
  459. import tempfile
  460. import atexit
  461. cert, pkey = generate_adhoc_ssl_pair()
  462. from cryptography.hazmat.primitives import serialization
  463. cert_handle, cert_file = tempfile.mkstemp()
  464. pkey_handle, pkey_file = tempfile.mkstemp()
  465. atexit.register(os.remove, pkey_file)
  466. atexit.register(os.remove, cert_file)
  467. os.write(cert_handle, cert.public_bytes(serialization.Encoding.PEM))
  468. os.write(
  469. pkey_handle,
  470. pkey.private_bytes(
  471. encoding=serialization.Encoding.PEM,
  472. format=serialization.PrivateFormat.TraditionalOpenSSL,
  473. encryption_algorithm=serialization.NoEncryption(),
  474. ),
  475. )
  476. os.close(cert_handle)
  477. os.close(pkey_handle)
  478. ctx = load_ssl_context(cert_file, pkey_file)
  479. return ctx
  480. def load_ssl_context(
  481. cert_file: str, pkey_file: t.Optional[str] = None, protocol: t.Optional[int] = None
  482. ) -> "ssl.SSLContext":
  483. """Loads SSL context from cert/private key files and optional protocol.
  484. Many parameters are directly taken from the API of
  485. :py:class:`ssl.SSLContext`.
  486. :param cert_file: Path of the certificate to use.
  487. :param pkey_file: Path of the private key to use. If not given, the key
  488. will be obtained from the certificate file.
  489. :param protocol: A ``PROTOCOL`` constant from the :mod:`ssl` module.
  490. Defaults to :data:`ssl.PROTOCOL_TLS_SERVER`.
  491. """
  492. if protocol is None:
  493. protocol = ssl.PROTOCOL_TLS_SERVER
  494. ctx = ssl.SSLContext(protocol)
  495. ctx.load_cert_chain(cert_file, pkey_file)
  496. return ctx
  497. def is_ssl_error(error: t.Optional[Exception] = None) -> bool:
  498. """Checks if the given error (or the current one) is an SSL error."""
  499. if error is None:
  500. error = t.cast(Exception, sys.exc_info()[1])
  501. return isinstance(error, ssl.SSLError)
  502. def select_address_family(host: str, port: int) -> socket.AddressFamily:
  503. """Return ``AF_INET4``, ``AF_INET6``, or ``AF_UNIX`` depending on
  504. the host and port."""
  505. if host.startswith("unix://"):
  506. return socket.AF_UNIX
  507. elif ":" in host and hasattr(socket, "AF_INET6"):
  508. return socket.AF_INET6
  509. return socket.AF_INET
  510. def get_sockaddr(
  511. host: str, port: int, family: socket.AddressFamily
  512. ) -> t.Union[t.Tuple[str, int], str]:
  513. """Return a fully qualified socket address that can be passed to
  514. :func:`socket.bind`."""
  515. if family == af_unix:
  516. return host.split("://", 1)[1]
  517. try:
  518. res = socket.getaddrinfo(
  519. host, port, family, socket.SOCK_STREAM, socket.IPPROTO_TCP
  520. )
  521. except socket.gaierror:
  522. return host, port
  523. return res[0][4] # type: ignore
  524. def get_interface_ip(family: socket.AddressFamily) -> str:
  525. """Get the IP address of an external interface. Used when binding to
  526. 0.0.0.0 or ::1 to show a more useful URL.
  527. :meta private:
  528. """
  529. # arbitrary private address
  530. host = "fd31:f903:5ab5:1::1" if family == socket.AF_INET6 else "10.253.155.219"
  531. with socket.socket(family, socket.SOCK_DGRAM) as s:
  532. try:
  533. s.connect((host, 58162))
  534. except OSError:
  535. return "::1" if family == socket.AF_INET6 else "127.0.0.1"
  536. return s.getsockname()[0] # type: ignore
  537. class BaseWSGIServer(HTTPServer):
  538. """Simple single-threaded, single-process WSGI server."""
  539. multithread = False
  540. multiprocess = False
  541. request_queue_size = LISTEN_QUEUE
  542. def __init__(
  543. self,
  544. host: str,
  545. port: int,
  546. app: "WSGIApplication",
  547. handler: t.Optional[t.Type[WSGIRequestHandler]] = None,
  548. passthrough_errors: bool = False,
  549. ssl_context: t.Optional[_TSSLContextArg] = None,
  550. fd: t.Optional[int] = None,
  551. ) -> None:
  552. if handler is None:
  553. handler = WSGIRequestHandler
  554. self.address_family = select_address_family(host, port)
  555. if fd is not None:
  556. real_sock = socket.fromfd(fd, self.address_family, socket.SOCK_STREAM)
  557. port = 0
  558. server_address = get_sockaddr(host, int(port), self.address_family)
  559. # remove socket file if it already exists
  560. if self.address_family == af_unix:
  561. server_address = t.cast(str, server_address)
  562. if os.path.exists(server_address):
  563. os.unlink(server_address)
  564. super().__init__(server_address, handler) # type: ignore
  565. self.app = app
  566. self.passthrough_errors = passthrough_errors
  567. self.shutdown_signal = False
  568. self.host = host
  569. self.port = self.socket.getsockname()[1]
  570. # Patch in the original socket.
  571. if fd is not None:
  572. self.socket.close()
  573. self.socket = real_sock
  574. self.server_address = self.socket.getsockname()
  575. if ssl_context is not None:
  576. if isinstance(ssl_context, tuple):
  577. ssl_context = load_ssl_context(*ssl_context)
  578. if ssl_context == "adhoc":
  579. ssl_context = generate_adhoc_ssl_context()
  580. self.socket = ssl_context.wrap_socket(self.socket, server_side=True)
  581. self.ssl_context: t.Optional["ssl.SSLContext"] = ssl_context
  582. else:
  583. self.ssl_context = None
  584. def log(self, type: str, message: str, *args: t.Any) -> None:
  585. _log(type, message, *args)
  586. def serve_forever(self, poll_interval: float = 0.5) -> None:
  587. self.shutdown_signal = False
  588. try:
  589. super().serve_forever(poll_interval=poll_interval)
  590. except KeyboardInterrupt:
  591. pass
  592. finally:
  593. self.server_close()
  594. def handle_error(self, request: t.Any, client_address: t.Tuple[str, int]) -> None:
  595. if self.passthrough_errors:
  596. raise
  597. return super().handle_error(request, client_address)
  598. class ThreadedWSGIServer(socketserver.ThreadingMixIn, BaseWSGIServer):
  599. """A WSGI server that does threading."""
  600. multithread = True
  601. daemon_threads = True
  602. class ForkingWSGIServer(ForkingMixIn, BaseWSGIServer):
  603. """A WSGI server that does forking."""
  604. multiprocess = True
  605. def __init__(
  606. self,
  607. host: str,
  608. port: int,
  609. app: "WSGIApplication",
  610. processes: int = 40,
  611. handler: t.Optional[t.Type[WSGIRequestHandler]] = None,
  612. passthrough_errors: bool = False,
  613. ssl_context: t.Optional[_TSSLContextArg] = None,
  614. fd: t.Optional[int] = None,
  615. ) -> None:
  616. if not can_fork:
  617. raise ValueError("Your platform does not support forking.")
  618. BaseWSGIServer.__init__(
  619. self, host, port, app, handler, passthrough_errors, ssl_context, fd
  620. )
  621. self.max_children = processes
  622. def make_server(
  623. host: str,
  624. port: int,
  625. app: "WSGIApplication",
  626. threaded: bool = False,
  627. processes: int = 1,
  628. request_handler: t.Optional[t.Type[WSGIRequestHandler]] = None,
  629. passthrough_errors: bool = False,
  630. ssl_context: t.Optional[_TSSLContextArg] = None,
  631. fd: t.Optional[int] = None,
  632. ) -> BaseWSGIServer:
  633. """Create a new server instance that is either threaded, or forks
  634. or just processes one request after another.
  635. """
  636. if threaded and processes > 1:
  637. raise ValueError("cannot have a multithreaded and multi process server.")
  638. elif threaded:
  639. return ThreadedWSGIServer(
  640. host, port, app, request_handler, passthrough_errors, ssl_context, fd=fd
  641. )
  642. elif processes > 1:
  643. return ForkingWSGIServer(
  644. host,
  645. port,
  646. app,
  647. processes,
  648. request_handler,
  649. passthrough_errors,
  650. ssl_context,
  651. fd=fd,
  652. )
  653. else:
  654. return BaseWSGIServer(
  655. host, port, app, request_handler, passthrough_errors, ssl_context, fd=fd
  656. )
  657. def is_running_from_reloader() -> bool:
  658. """Checks if the application is running from within the Werkzeug
  659. reloader subprocess.
  660. .. versionadded:: 0.10
  661. """
  662. return os.environ.get("WERKZEUG_RUN_MAIN") == "true"
  663. def run_simple(
  664. hostname: str,
  665. port: int,
  666. application: "WSGIApplication",
  667. use_reloader: bool = False,
  668. use_debugger: bool = False,
  669. use_evalex: bool = True,
  670. extra_files: t.Optional[t.Iterable[str]] = None,
  671. exclude_patterns: t.Optional[t.Iterable[str]] = None,
  672. reloader_interval: int = 1,
  673. reloader_type: str = "auto",
  674. threaded: bool = False,
  675. processes: int = 1,
  676. request_handler: t.Optional[t.Type[WSGIRequestHandler]] = None,
  677. static_files: t.Optional[t.Dict[str, t.Union[str, t.Tuple[str, str]]]] = None,
  678. passthrough_errors: bool = False,
  679. ssl_context: t.Optional[_TSSLContextArg] = None,
  680. ) -> None:
  681. """Start a WSGI application. Optional features include a reloader,
  682. multithreading and fork support.
  683. This function has a command-line interface too::
  684. python -m werkzeug.serving --help
  685. .. versionchanged:: 2.0
  686. Added ``exclude_patterns`` parameter.
  687. .. versionadded:: 0.5
  688. `static_files` was added to simplify serving of static files as well
  689. as `passthrough_errors`.
  690. .. versionadded:: 0.6
  691. support for SSL was added.
  692. .. versionadded:: 0.8
  693. Added support for automatically loading a SSL context from certificate
  694. file and private key.
  695. .. versionadded:: 0.9
  696. Added command-line interface.
  697. .. versionadded:: 0.10
  698. Improved the reloader and added support for changing the backend
  699. through the `reloader_type` parameter. See :ref:`reloader`
  700. for more information.
  701. .. versionchanged:: 0.15
  702. Bind to a Unix socket by passing a path that starts with
  703. ``unix://`` as the ``hostname``.
  704. :param hostname: The host to bind to, for example ``'localhost'``.
  705. If the value is a path that starts with ``unix://`` it will bind
  706. to a Unix socket instead of a TCP socket..
  707. :param port: The port for the server. eg: ``8080``
  708. :param application: the WSGI application to execute
  709. :param use_reloader: should the server automatically restart the python
  710. process if modules were changed?
  711. :param use_debugger: should the werkzeug debugging system be used?
  712. :param use_evalex: should the exception evaluation feature be enabled?
  713. :param extra_files: a list of files the reloader should watch
  714. additionally to the modules. For example configuration
  715. files.
  716. :param exclude_patterns: List of :mod:`fnmatch` patterns to ignore
  717. when running the reloader. For example, ignore cache files that
  718. shouldn't reload when updated.
  719. :param reloader_interval: the interval for the reloader in seconds.
  720. :param reloader_type: the type of reloader to use. The default is
  721. auto detection. Valid values are ``'stat'`` and
  722. ``'watchdog'``. See :ref:`reloader` for more
  723. information.
  724. :param threaded: should the process handle each request in a separate
  725. thread?
  726. :param processes: if greater than 1 then handle each request in a new process
  727. up to this maximum number of concurrent processes.
  728. :param request_handler: optional parameter that can be used to replace
  729. the default one. You can use this to replace it
  730. with a different
  731. :class:`~BaseHTTPServer.BaseHTTPRequestHandler`
  732. subclass.
  733. :param static_files: a list or dict of paths for static files. This works
  734. exactly like :class:`SharedDataMiddleware`, it's actually
  735. just wrapping the application in that middleware before
  736. serving.
  737. :param passthrough_errors: set this to `True` to disable the error catching.
  738. This means that the server will die on errors but
  739. it can be useful to hook debuggers in (pdb etc.)
  740. :param ssl_context: an SSL context for the connection. Either an
  741. :class:`ssl.SSLContext`, a tuple in the form
  742. ``(cert_file, pkey_file)``, the string ``'adhoc'`` if
  743. the server should automatically create one, or ``None``
  744. to disable SSL (which is the default).
  745. """
  746. if not isinstance(port, int):
  747. raise TypeError("port must be an integer")
  748. if use_debugger:
  749. from .debug import DebuggedApplication
  750. application = DebuggedApplication(application, use_evalex)
  751. if static_files:
  752. from .middleware.shared_data import SharedDataMiddleware
  753. application = SharedDataMiddleware(application, static_files)
  754. def log_startup(sock: socket.socket) -> None:
  755. all_addresses_message = (
  756. " * Running on all addresses.\n"
  757. " WARNING: This is a development server. Do not use it in"
  758. " a production deployment."
  759. )
  760. if sock.family == af_unix:
  761. _log("info", " * Running on %s (Press CTRL+C to quit)", hostname)
  762. else:
  763. if hostname == "0.0.0.0":
  764. _log("warning", all_addresses_message)
  765. display_hostname = get_interface_ip(socket.AF_INET)
  766. elif hostname == "::":
  767. _log("warning", all_addresses_message)
  768. display_hostname = get_interface_ip(socket.AF_INET6)
  769. else:
  770. display_hostname = hostname
  771. if ":" in display_hostname:
  772. display_hostname = f"[{display_hostname}]"
  773. _log(
  774. "info",
  775. " * Running on %s://%s:%d/ (Press CTRL+C to quit)",
  776. "http" if ssl_context is None else "https",
  777. display_hostname,
  778. sock.getsockname()[1],
  779. )
  780. def inner() -> None:
  781. try:
  782. fd: t.Optional[int] = int(os.environ["WERKZEUG_SERVER_FD"])
  783. except (LookupError, ValueError):
  784. fd = None
  785. srv = make_server(
  786. hostname,
  787. port,
  788. application,
  789. threaded,
  790. processes,
  791. request_handler,
  792. passthrough_errors,
  793. ssl_context,
  794. fd=fd,
  795. )
  796. if fd is None:
  797. log_startup(srv.socket)
  798. srv.serve_forever()
  799. if use_reloader:
  800. # If we're not running already in the subprocess that is the
  801. # reloader we want to open up a socket early to make sure the
  802. # port is actually available.
  803. if not is_running_from_reloader():
  804. if port == 0 and not can_open_by_fd:
  805. raise ValueError(
  806. "Cannot bind to a random port with enabled "
  807. "reloader if the Python interpreter does "
  808. "not support socket opening by fd."
  809. )
  810. # Create and destroy a socket so that any exceptions are
  811. # raised before we spawn a separate Python interpreter and
  812. # lose this ability.
  813. address_family = select_address_family(hostname, port)
  814. server_address = get_sockaddr(hostname, port, address_family)
  815. s = socket.socket(address_family, socket.SOCK_STREAM)
  816. s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  817. s.bind(server_address)
  818. s.set_inheritable(True)
  819. # If we can open the socket by file descriptor, then we can just
  820. # reuse this one and our socket will survive the restarts.
  821. if can_open_by_fd:
  822. os.environ["WERKZEUG_SERVER_FD"] = str(s.fileno())
  823. s.listen(LISTEN_QUEUE)
  824. log_startup(s)
  825. else:
  826. s.close()
  827. if address_family == af_unix:
  828. server_address = t.cast(str, server_address)
  829. _log("info", "Unlinking %s", server_address)
  830. os.unlink(server_address)
  831. from ._reloader import run_with_reloader as _rwr
  832. _rwr(
  833. inner,
  834. extra_files=extra_files,
  835. exclude_patterns=exclude_patterns,
  836. interval=reloader_interval,
  837. reloader_type=reloader_type,
  838. )
  839. else:
  840. inner()
  841. def run_with_reloader(*args: t.Any, **kwargs: t.Any) -> None:
  842. """Run a process with the reloader. This is not a public API, do
  843. not use this function.
  844. .. deprecated:: 2.0
  845. Will be removed in Werkzeug 2.1.
  846. """
  847. from ._reloader import run_with_reloader as _rwr
  848. warnings.warn(
  849. (
  850. "'run_with_reloader' is a private API, it will no longer be"
  851. " accessible in Werkzeug 2.1. Use 'run_simple' instead."
  852. ),
  853. DeprecationWarning,
  854. stacklevel=2,
  855. )
  856. _rwr(*args, **kwargs)
  857. def main() -> None:
  858. """A simple command-line interface for :py:func:`run_simple`."""
  859. import argparse
  860. from .utils import import_string
  861. _log("warning", "This CLI is deprecated and will be removed in version 2.1.")
  862. parser = argparse.ArgumentParser(
  863. description="Run the given WSGI application with the development server.",
  864. allow_abbrev=False,
  865. )
  866. parser.add_argument(
  867. "-b",
  868. "--bind",
  869. dest="address",
  870. help="The hostname:port the app should listen on.",
  871. )
  872. parser.add_argument(
  873. "-d",
  874. "--debug",
  875. action="store_true",
  876. help="Show the interactive debugger for unhandled exceptions.",
  877. )
  878. parser.add_argument(
  879. "-r",
  880. "--reload",
  881. action="store_true",
  882. help="Reload the process if modules change.",
  883. )
  884. parser.add_argument(
  885. "application", help="Application to import and serve, in the form module:app."
  886. )
  887. args = parser.parse_args()
  888. hostname, port = None, None
  889. if args.address:
  890. hostname, _, port = args.address.partition(":")
  891. run_simple(
  892. hostname=hostname or "127.0.0.1",
  893. port=int(port or 5000),
  894. application=import_string(args.application),
  895. use_reloader=args.reload,
  896. use_debugger=args.debug,
  897. )
  898. if __name__ == "__main__":
  899. main()