serving.py 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075
  1. # -*- coding: utf-8 -*-
  2. """
  3. werkzeug.serving
  4. ~~~~~~~~~~~~~~~~
  5. There are many ways to serve a WSGI application. While you're developing
  6. it you usually don't want a full blown webserver like Apache but a simple
  7. standalone one. From Python 2.5 onwards there is the `wsgiref`_ server in
  8. the standard library. If you're using older versions of Python you can
  9. download the package from the cheeseshop.
  10. However there are some caveats. Sourcecode won't reload itself when
  11. changed and each time you kill the server using ``^C`` you get an
  12. `KeyboardInterrupt` error. While the latter is easy to solve the first
  13. one can be a pain in the ass in some situations.
  14. The easiest way is creating a small ``start-myproject.py`` that runs the
  15. application::
  16. #!/usr/bin/env python
  17. # -*- coding: utf-8 -*-
  18. from myproject import make_app
  19. from werkzeug.serving import run_simple
  20. app = make_app(...)
  21. run_simple('localhost', 8080, app, use_reloader=True)
  22. You can also pass it a `extra_files` keyword argument with a list of
  23. additional files (like configuration files) you want to observe.
  24. For bigger applications you should consider using `click`
  25. (http://click.pocoo.org) instead of a simple start file.
  26. :copyright: 2007 Pallets
  27. :license: BSD-3-Clause
  28. """
  29. import io
  30. import os
  31. import signal
  32. import socket
  33. import sys
  34. from ._compat import PY2
  35. from ._compat import reraise
  36. from ._compat import WIN
  37. from ._compat import wsgi_encoding_dance
  38. from ._internal import _log
  39. from .exceptions import InternalServerError
  40. from .urls import uri_to_iri
  41. from .urls import url_parse
  42. from .urls import url_unquote
  43. try:
  44. import socketserver
  45. from http.server import BaseHTTPRequestHandler
  46. from http.server import HTTPServer
  47. except ImportError:
  48. import SocketServer as socketserver
  49. from BaseHTTPServer import HTTPServer
  50. from BaseHTTPServer import BaseHTTPRequestHandler
  51. try:
  52. import ssl
  53. except ImportError:
  54. class _SslDummy(object):
  55. def __getattr__(self, name):
  56. raise RuntimeError("SSL support unavailable")
  57. ssl = _SslDummy()
  58. try:
  59. import termcolor
  60. except ImportError:
  61. termcolor = None
  62. def _get_openssl_crypto_module():
  63. try:
  64. from OpenSSL import crypto
  65. except ImportError:
  66. raise TypeError("Using ad-hoc certificates requires the pyOpenSSL library.")
  67. else:
  68. return crypto
  69. ThreadingMixIn = socketserver.ThreadingMixIn
  70. can_fork = hasattr(os, "fork")
  71. if can_fork:
  72. ForkingMixIn = socketserver.ForkingMixIn
  73. else:
  74. class ForkingMixIn(object):
  75. pass
  76. try:
  77. af_unix = socket.AF_UNIX
  78. except AttributeError:
  79. af_unix = None
  80. LISTEN_QUEUE = 128
  81. can_open_by_fd = not WIN and hasattr(socket, "fromfd")
  82. # On Python 3, ConnectionError represents the same errnos as
  83. # socket.error from Python 2, while socket.error is an alias for the
  84. # more generic OSError.
  85. if PY2:
  86. _ConnectionError = socket.error
  87. else:
  88. _ConnectionError = ConnectionError
  89. class DechunkedInput(io.RawIOBase):
  90. """An input stream that handles Transfer-Encoding 'chunked'"""
  91. def __init__(self, rfile):
  92. self._rfile = rfile
  93. self._done = False
  94. self._len = 0
  95. def readable(self):
  96. return True
  97. def read_chunk_len(self):
  98. try:
  99. line = self._rfile.readline().decode("latin1")
  100. _len = int(line.strip(), 16)
  101. except ValueError:
  102. raise IOError("Invalid chunk header")
  103. if _len < 0:
  104. raise IOError("Negative chunk length not allowed")
  105. return _len
  106. def readinto(self, buf):
  107. read = 0
  108. while not self._done and read < len(buf):
  109. if self._len == 0:
  110. # This is the first chunk or we fully consumed the previous
  111. # one. Read the next length of the next chunk
  112. self._len = self.read_chunk_len()
  113. if self._len == 0:
  114. # Found the final chunk of size 0. The stream is now exhausted,
  115. # but there is still a final newline that should be consumed
  116. self._done = True
  117. if self._len > 0:
  118. # There is data (left) in this chunk, so append it to the
  119. # buffer. If this operation fully consumes the chunk, this will
  120. # reset self._len to 0.
  121. n = min(len(buf), self._len)
  122. buf[read : read + n] = self._rfile.read(n)
  123. self._len -= n
  124. read += n
  125. if self._len == 0:
  126. # Skip the terminating newline of a chunk that has been fully
  127. # consumed. This also applies to the 0-sized final chunk
  128. terminator = self._rfile.readline()
  129. if terminator not in (b"\n", b"\r\n", b"\r"):
  130. raise IOError("Missing chunk terminating newline")
  131. return read
  132. class WSGIRequestHandler(BaseHTTPRequestHandler, object):
  133. """A request handler that implements WSGI dispatching."""
  134. @property
  135. def server_version(self):
  136. from . import __version__
  137. return "Werkzeug/" + __version__
  138. def make_environ(self):
  139. request_url = url_parse(self.path)
  140. def shutdown_server():
  141. self.server.shutdown_signal = True
  142. url_scheme = "http" if self.server.ssl_context is None else "https"
  143. if not self.client_address:
  144. self.client_address = "<local>"
  145. if isinstance(self.client_address, str):
  146. self.client_address = (self.client_address, 0)
  147. else:
  148. pass
  149. path_info = url_unquote(request_url.path)
  150. environ = {
  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.server.shutdown": shutdown_server,
  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.get_header_items():
  175. key = key.upper().replace("-", "_")
  176. value = value.replace("\r\n", "")
  177. if key not in ("CONTENT_TYPE", "CONTENT_LENGTH"):
  178. key = "HTTP_" + key
  179. if key in environ:
  180. value = "{},{}".format(environ[key], value)
  181. environ[key] = value
  182. if environ.get("HTTP_TRANSFER_ENCODING", "").strip().lower() == "chunked":
  183. environ["wsgi.input_terminated"] = True
  184. environ["wsgi.input"] = DechunkedInput(environ["wsgi.input"])
  185. if request_url.scheme and request_url.netloc:
  186. environ["HTTP_HOST"] = request_url.netloc
  187. return environ
  188. def run_wsgi(self):
  189. if self.headers.get("Expect", "").lower().strip() == "100-continue":
  190. self.wfile.write(b"HTTP/1.1 100 Continue\r\n\r\n")
  191. self.environ = environ = self.make_environ()
  192. headers_set = []
  193. headers_sent = []
  194. def write(data):
  195. assert headers_set, "write() before start_response"
  196. if not headers_sent:
  197. status, response_headers = headers_sent[:] = headers_set
  198. try:
  199. code, msg = status.split(None, 1)
  200. except ValueError:
  201. code, msg = status, ""
  202. code = int(code)
  203. self.send_response(code, msg)
  204. header_keys = set()
  205. for key, value in response_headers:
  206. self.send_header(key, value)
  207. key = key.lower()
  208. header_keys.add(key)
  209. if not (
  210. "content-length" in header_keys
  211. or environ["REQUEST_METHOD"] == "HEAD"
  212. or code < 200
  213. or code in (204, 304)
  214. ):
  215. self.close_connection = True
  216. self.send_header("Connection", "close")
  217. if "server" not in header_keys:
  218. self.send_header("Server", self.version_string())
  219. if "date" not in header_keys:
  220. self.send_header("Date", self.date_time_string())
  221. self.end_headers()
  222. assert isinstance(data, bytes), "applications must write bytes"
  223. self.wfile.write(data)
  224. self.wfile.flush()
  225. def start_response(status, response_headers, exc_info=None):
  226. if exc_info:
  227. try:
  228. if headers_sent:
  229. reraise(*exc_info)
  230. finally:
  231. exc_info = None
  232. elif headers_set:
  233. raise AssertionError("Headers already set")
  234. headers_set[:] = [status, response_headers]
  235. return write
  236. def execute(app):
  237. application_iter = app(environ, start_response)
  238. try:
  239. for data in application_iter:
  240. write(data)
  241. if not headers_sent:
  242. write(b"")
  243. finally:
  244. if hasattr(application_iter, "close"):
  245. application_iter.close()
  246. application_iter = None
  247. try:
  248. execute(self.server.app)
  249. except (_ConnectionError, socket.timeout) as e:
  250. self.connection_dropped(e, environ)
  251. except Exception:
  252. if self.server.passthrough_errors:
  253. raise
  254. from .debug.tbtools import get_current_traceback
  255. traceback = get_current_traceback(ignore_system_exceptions=True)
  256. try:
  257. # if we haven't yet sent the headers but they are set
  258. # we roll back to be able to set them again.
  259. if not headers_sent:
  260. del headers_set[:]
  261. execute(InternalServerError())
  262. except Exception:
  263. pass
  264. self.server.log("error", "Error on request:\n%s", traceback.plaintext)
  265. def handle(self):
  266. """Handles a request ignoring dropped connections."""
  267. rv = None
  268. try:
  269. rv = BaseHTTPRequestHandler.handle(self)
  270. except (_ConnectionError, socket.timeout) as e:
  271. self.connection_dropped(e)
  272. except Exception as e:
  273. if self.server.ssl_context is None or not is_ssl_error(e):
  274. raise
  275. if self.server.shutdown_signal:
  276. self.initiate_shutdown()
  277. return rv
  278. def initiate_shutdown(self):
  279. """A horrible, horrible way to kill the server for Python 2.6 and
  280. later. It's the best we can do.
  281. """
  282. # Windows does not provide SIGKILL, go with SIGTERM then.
  283. sig = getattr(signal, "SIGKILL", signal.SIGTERM)
  284. # reloader active
  285. if is_running_from_reloader():
  286. os.kill(os.getpid(), sig)
  287. # python 2.7
  288. self.server._BaseServer__shutdown_request = True
  289. # python 2.6
  290. self.server._BaseServer__serving = False
  291. def connection_dropped(self, error, environ=None):
  292. """Called if the connection was closed by the client. By default
  293. nothing happens.
  294. """
  295. def handle_one_request(self):
  296. """Handle a single HTTP request."""
  297. self.raw_requestline = self.rfile.readline()
  298. if not self.raw_requestline:
  299. self.close_connection = 1
  300. elif self.parse_request():
  301. return self.run_wsgi()
  302. def send_response(self, code, message=None):
  303. """Send the response header and log the response code."""
  304. self.log_request(code)
  305. if message is None:
  306. message = code in self.responses and self.responses[code][0] or ""
  307. if self.request_version != "HTTP/0.9":
  308. hdr = "%s %d %s\r\n" % (self.protocol_version, code, message)
  309. self.wfile.write(hdr.encode("ascii"))
  310. def version_string(self):
  311. return BaseHTTPRequestHandler.version_string(self).strip()
  312. def address_string(self):
  313. if getattr(self, "environ", None):
  314. return self.environ["REMOTE_ADDR"]
  315. elif not self.client_address:
  316. return "<local>"
  317. elif isinstance(self.client_address, str):
  318. return self.client_address
  319. else:
  320. return self.client_address[0]
  321. def port_integer(self):
  322. return self.client_address[1]
  323. def log_request(self, code="-", size="-"):
  324. try:
  325. path = uri_to_iri(self.path)
  326. msg = "%s %s %s" % (self.command, path, self.request_version)
  327. except AttributeError:
  328. # path isn't set if the requestline was bad
  329. msg = self.requestline
  330. code = str(code)
  331. if termcolor:
  332. color = termcolor.colored
  333. if code[0] == "1": # 1xx - Informational
  334. msg = color(msg, attrs=["bold"])
  335. elif code[0] == "2": # 2xx - Success
  336. msg = color(msg, color="white")
  337. elif code == "304": # 304 - Resource Not Modified
  338. msg = color(msg, color="cyan")
  339. elif code[0] == "3": # 3xx - Redirection
  340. msg = color(msg, color="green")
  341. elif code == "404": # 404 - Resource Not Found
  342. msg = color(msg, color="yellow")
  343. elif code[0] == "4": # 4xx - Client Error
  344. msg = color(msg, color="red", attrs=["bold"])
  345. else: # 5xx, or any other response
  346. msg = color(msg, color="magenta", attrs=["bold"])
  347. self.log("info", '"%s" %s %s', msg, code, size)
  348. def log_error(self, *args):
  349. self.log("error", *args)
  350. def log_message(self, format, *args):
  351. self.log("info", format, *args)
  352. def log(self, type, message, *args):
  353. _log(
  354. type,
  355. "%s - - [%s] %s\n"
  356. % (self.address_string(), self.log_date_time_string(), message % args),
  357. )
  358. def get_header_items(self):
  359. """
  360. Get an iterable list of key/value pairs representing headers.
  361. This function provides Python 2/3 compatibility as related to the
  362. parsing of request headers. Python 2.7 is not compliant with
  363. RFC 3875 Section 4.1.18 which requires multiple values for headers
  364. to be provided or RFC 2616 which allows for folding of multi-line
  365. headers. This function will return a matching list regardless
  366. of Python version. It can be removed once Python 2.7 support
  367. is dropped.
  368. :return: List of tuples containing header hey/value pairs
  369. """
  370. if PY2:
  371. # For Python 2, process the headers manually according to
  372. # W3C RFC 2616 Section 4.2.
  373. items = []
  374. for header in self.headers.headers:
  375. # Remove "\r\n" from the header and split on ":" to get
  376. # the field name and value.
  377. try:
  378. key, value = header[0:-2].split(":", 1)
  379. except ValueError:
  380. # If header could not be slit with : but starts with white
  381. # space and it follows an existing header, it's a folded
  382. # header.
  383. if header[0] in ("\t", " ") and items:
  384. # Pop off the last header
  385. key, value = items.pop()
  386. # Append the current header to the value of the last
  387. # header which will be placed back on the end of the
  388. # list
  389. value = value + header
  390. # Otherwise it's just a bad header and should error
  391. else:
  392. # Re-raise the value error
  393. raise
  394. # Add the key and the value once stripped of leading
  395. # white space. The specification allows for stripping
  396. # trailing white space but the Python 3 code does not
  397. # strip trailing white space. Therefore, trailing space
  398. # will be left as is to match the Python 3 behavior.
  399. items.append((key, value.lstrip()))
  400. else:
  401. items = self.headers.items()
  402. return items
  403. #: backwards compatible name if someone is subclassing it
  404. BaseRequestHandler = WSGIRequestHandler
  405. def generate_adhoc_ssl_pair(cn=None):
  406. from random import random
  407. crypto = _get_openssl_crypto_module()
  408. # pretty damn sure that this is not actually accepted by anyone
  409. if cn is None:
  410. cn = "*"
  411. cert = crypto.X509()
  412. cert.set_serial_number(int(random() * sys.maxsize))
  413. cert.gmtime_adj_notBefore(0)
  414. cert.gmtime_adj_notAfter(60 * 60 * 24 * 365)
  415. subject = cert.get_subject()
  416. subject.CN = cn
  417. subject.O = "Dummy Certificate" # noqa: E741
  418. issuer = cert.get_issuer()
  419. issuer.CN = subject.CN
  420. issuer.O = subject.O # noqa: E741
  421. pkey = crypto.PKey()
  422. pkey.generate_key(crypto.TYPE_RSA, 2048)
  423. cert.set_pubkey(pkey)
  424. cert.sign(pkey, "sha256")
  425. return cert, pkey
  426. def make_ssl_devcert(base_path, host=None, cn=None):
  427. """Creates an SSL key for development. This should be used instead of
  428. the ``'adhoc'`` key which generates a new cert on each server start.
  429. It accepts a path for where it should store the key and cert and
  430. either a host or CN. If a host is given it will use the CN
  431. ``*.host/CN=host``.
  432. For more information see :func:`run_simple`.
  433. .. versionadded:: 0.9
  434. :param base_path: the path to the certificate and key. The extension
  435. ``.crt`` is added for the certificate, ``.key`` is
  436. added for the key.
  437. :param host: the name of the host. This can be used as an alternative
  438. for the `cn`.
  439. :param cn: the `CN` to use.
  440. """
  441. from OpenSSL import crypto
  442. if host is not None:
  443. cn = "*.%s/CN=%s" % (host, host)
  444. cert, pkey = generate_adhoc_ssl_pair(cn=cn)
  445. cert_file = base_path + ".crt"
  446. pkey_file = base_path + ".key"
  447. with open(cert_file, "wb") as f:
  448. f.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
  449. with open(pkey_file, "wb") as f:
  450. f.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey))
  451. return cert_file, pkey_file
  452. def generate_adhoc_ssl_context():
  453. """Generates an adhoc SSL context for the development server."""
  454. crypto = _get_openssl_crypto_module()
  455. import tempfile
  456. import atexit
  457. cert, pkey = generate_adhoc_ssl_pair()
  458. cert_handle, cert_file = tempfile.mkstemp()
  459. pkey_handle, pkey_file = tempfile.mkstemp()
  460. atexit.register(os.remove, pkey_file)
  461. atexit.register(os.remove, cert_file)
  462. os.write(cert_handle, crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
  463. os.write(pkey_handle, crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey))
  464. os.close(cert_handle)
  465. os.close(pkey_handle)
  466. ctx = load_ssl_context(cert_file, pkey_file)
  467. return ctx
  468. def load_ssl_context(cert_file, pkey_file=None, protocol=None):
  469. """Loads SSL context from cert/private key files and optional protocol.
  470. Many parameters are directly taken from the API of
  471. :py:class:`ssl.SSLContext`.
  472. :param cert_file: Path of the certificate to use.
  473. :param pkey_file: Path of the private key to use. If not given, the key
  474. will be obtained from the certificate file.
  475. :param protocol: One of the ``PROTOCOL_*`` constants in the stdlib ``ssl``
  476. module. Defaults to ``PROTOCOL_SSLv23``.
  477. """
  478. if protocol is None:
  479. protocol = ssl.PROTOCOL_SSLv23
  480. ctx = _SSLContext(protocol)
  481. ctx.load_cert_chain(cert_file, pkey_file)
  482. return ctx
  483. class _SSLContext(object):
  484. """A dummy class with a small subset of Python3's ``ssl.SSLContext``, only
  485. intended to be used with and by Werkzeug."""
  486. def __init__(self, protocol):
  487. self._protocol = protocol
  488. self._certfile = None
  489. self._keyfile = None
  490. self._password = None
  491. def load_cert_chain(self, certfile, keyfile=None, password=None):
  492. self._certfile = certfile
  493. self._keyfile = keyfile or certfile
  494. self._password = password
  495. def wrap_socket(self, sock, **kwargs):
  496. return ssl.wrap_socket(
  497. sock,
  498. keyfile=self._keyfile,
  499. certfile=self._certfile,
  500. ssl_version=self._protocol,
  501. **kwargs
  502. )
  503. def is_ssl_error(error=None):
  504. """Checks if the given error (or the current one) is an SSL error."""
  505. exc_types = (ssl.SSLError,)
  506. try:
  507. from OpenSSL.SSL import Error
  508. exc_types += (Error,)
  509. except ImportError:
  510. pass
  511. if error is None:
  512. error = sys.exc_info()[1]
  513. return isinstance(error, exc_types)
  514. def select_address_family(host, port):
  515. """Return ``AF_INET4``, ``AF_INET6``, or ``AF_UNIX`` depending on
  516. the host and port."""
  517. # disabled due to problems with current ipv6 implementations
  518. # and various operating systems. Probably this code also is
  519. # not supposed to work, but I can't come up with any other
  520. # ways to implement this.
  521. # try:
  522. # info = socket.getaddrinfo(host, port, socket.AF_UNSPEC,
  523. # socket.SOCK_STREAM, 0,
  524. # socket.AI_PASSIVE)
  525. # if info:
  526. # return info[0][0]
  527. # except socket.gaierror:
  528. # pass
  529. if host.startswith("unix://"):
  530. return socket.AF_UNIX
  531. elif ":" in host and hasattr(socket, "AF_INET6"):
  532. return socket.AF_INET6
  533. return socket.AF_INET
  534. def get_sockaddr(host, port, family):
  535. """Return a fully qualified socket address that can be passed to
  536. :func:`socket.bind`."""
  537. if family == af_unix:
  538. return host.split("://", 1)[1]
  539. try:
  540. res = socket.getaddrinfo(
  541. host, port, family, socket.SOCK_STREAM, socket.IPPROTO_TCP
  542. )
  543. except socket.gaierror:
  544. return host, port
  545. return res[0][4]
  546. class BaseWSGIServer(HTTPServer, object):
  547. """Simple single-threaded, single-process WSGI server."""
  548. multithread = False
  549. multiprocess = False
  550. request_queue_size = LISTEN_QUEUE
  551. def __init__(
  552. self,
  553. host,
  554. port,
  555. app,
  556. handler=None,
  557. passthrough_errors=False,
  558. ssl_context=None,
  559. fd=None,
  560. ):
  561. if handler is None:
  562. handler = WSGIRequestHandler
  563. self.address_family = select_address_family(host, port)
  564. if fd is not None:
  565. real_sock = socket.fromfd(fd, self.address_family, socket.SOCK_STREAM)
  566. port = 0
  567. server_address = get_sockaddr(host, int(port), self.address_family)
  568. # remove socket file if it already exists
  569. if self.address_family == af_unix and os.path.exists(server_address):
  570. os.unlink(server_address)
  571. HTTPServer.__init__(self, server_address, handler)
  572. self.app = app
  573. self.passthrough_errors = passthrough_errors
  574. self.shutdown_signal = False
  575. self.host = host
  576. self.port = self.socket.getsockname()[1]
  577. # Patch in the original socket.
  578. if fd is not None:
  579. self.socket.close()
  580. self.socket = real_sock
  581. self.server_address = self.socket.getsockname()
  582. if ssl_context is not None:
  583. if isinstance(ssl_context, tuple):
  584. ssl_context = load_ssl_context(*ssl_context)
  585. if ssl_context == "adhoc":
  586. ssl_context = generate_adhoc_ssl_context()
  587. # If we are on Python 2 the return value from socket.fromfd
  588. # is an internal socket object but what we need for ssl wrap
  589. # is the wrapper around it :(
  590. sock = self.socket
  591. if PY2 and not isinstance(sock, socket.socket):
  592. sock = socket.socket(sock.family, sock.type, sock.proto, sock)
  593. self.socket = ssl_context.wrap_socket(sock, server_side=True)
  594. self.ssl_context = ssl_context
  595. else:
  596. self.ssl_context = None
  597. def log(self, type, message, *args):
  598. _log(type, message, *args)
  599. def serve_forever(self):
  600. self.shutdown_signal = False
  601. try:
  602. HTTPServer.serve_forever(self)
  603. except KeyboardInterrupt:
  604. pass
  605. finally:
  606. self.server_close()
  607. def handle_error(self, request, client_address):
  608. if self.passthrough_errors:
  609. raise
  610. # Python 2 still causes a socket.error after the earlier
  611. # handling, so silence it here.
  612. if isinstance(sys.exc_info()[1], _ConnectionError):
  613. return
  614. return HTTPServer.handle_error(self, request, client_address)
  615. def get_request(self):
  616. con, info = self.socket.accept()
  617. return con, info
  618. class ThreadedWSGIServer(ThreadingMixIn, BaseWSGIServer):
  619. """A WSGI server that does threading."""
  620. multithread = True
  621. daemon_threads = True
  622. class ForkingWSGIServer(ForkingMixIn, BaseWSGIServer):
  623. """A WSGI server that does forking."""
  624. multiprocess = True
  625. def __init__(
  626. self,
  627. host,
  628. port,
  629. app,
  630. processes=40,
  631. handler=None,
  632. passthrough_errors=False,
  633. ssl_context=None,
  634. fd=None,
  635. ):
  636. if not can_fork:
  637. raise ValueError("Your platform does not support forking.")
  638. BaseWSGIServer.__init__(
  639. self, host, port, app, handler, passthrough_errors, ssl_context, fd
  640. )
  641. self.max_children = processes
  642. def make_server(
  643. host=None,
  644. port=None,
  645. app=None,
  646. threaded=False,
  647. processes=1,
  648. request_handler=None,
  649. passthrough_errors=False,
  650. ssl_context=None,
  651. fd=None,
  652. ):
  653. """Create a new server instance that is either threaded, or forks
  654. or just processes one request after another.
  655. """
  656. if threaded and processes > 1:
  657. raise ValueError("cannot have a multithreaded and multi process server.")
  658. elif threaded:
  659. return ThreadedWSGIServer(
  660. host, port, app, request_handler, passthrough_errors, ssl_context, fd=fd
  661. )
  662. elif processes > 1:
  663. return ForkingWSGIServer(
  664. host,
  665. port,
  666. app,
  667. processes,
  668. request_handler,
  669. passthrough_errors,
  670. ssl_context,
  671. fd=fd,
  672. )
  673. else:
  674. return BaseWSGIServer(
  675. host, port, app, request_handler, passthrough_errors, ssl_context, fd=fd
  676. )
  677. def is_running_from_reloader():
  678. """Checks if the application is running from within the Werkzeug
  679. reloader subprocess.
  680. .. versionadded:: 0.10
  681. """
  682. return os.environ.get("WERKZEUG_RUN_MAIN") == "true"
  683. def run_simple(
  684. hostname,
  685. port,
  686. application,
  687. use_reloader=False,
  688. use_debugger=False,
  689. use_evalex=True,
  690. extra_files=None,
  691. reloader_interval=1,
  692. reloader_type="auto",
  693. threaded=False,
  694. processes=1,
  695. request_handler=None,
  696. static_files=None,
  697. passthrough_errors=False,
  698. ssl_context=None,
  699. ):
  700. """Start a WSGI application. Optional features include a reloader,
  701. multithreading and fork support.
  702. This function has a command-line interface too::
  703. python -m werkzeug.serving --help
  704. .. versionadded:: 0.5
  705. `static_files` was added to simplify serving of static files as well
  706. as `passthrough_errors`.
  707. .. versionadded:: 0.6
  708. support for SSL was added.
  709. .. versionadded:: 0.8
  710. Added support for automatically loading a SSL context from certificate
  711. file and private key.
  712. .. versionadded:: 0.9
  713. Added command-line interface.
  714. .. versionadded:: 0.10
  715. Improved the reloader and added support for changing the backend
  716. through the `reloader_type` parameter. See :ref:`reloader`
  717. for more information.
  718. .. versionchanged:: 0.15
  719. Bind to a Unix socket by passing a path that starts with
  720. ``unix://`` as the ``hostname``.
  721. :param hostname: The host to bind to, for example ``'localhost'``.
  722. If the value is a path that starts with ``unix://`` it will bind
  723. to a Unix socket instead of a TCP socket..
  724. :param port: The port for the server. eg: ``8080``
  725. :param application: the WSGI application to execute
  726. :param use_reloader: should the server automatically restart the python
  727. process if modules were changed?
  728. :param use_debugger: should the werkzeug debugging system be used?
  729. :param use_evalex: should the exception evaluation feature be enabled?
  730. :param extra_files: a list of files the reloader should watch
  731. additionally to the modules. For example configuration
  732. files.
  733. :param reloader_interval: the interval for the reloader in seconds.
  734. :param reloader_type: the type of reloader to use. The default is
  735. auto detection. Valid values are ``'stat'`` and
  736. ``'watchdog'``. See :ref:`reloader` for more
  737. information.
  738. :param threaded: should the process handle each request in a separate
  739. thread?
  740. :param processes: if greater than 1 then handle each request in a new process
  741. up to this maximum number of concurrent processes.
  742. :param request_handler: optional parameter that can be used to replace
  743. the default one. You can use this to replace it
  744. with a different
  745. :class:`~BaseHTTPServer.BaseHTTPRequestHandler`
  746. subclass.
  747. :param static_files: a list or dict of paths for static files. This works
  748. exactly like :class:`SharedDataMiddleware`, it's actually
  749. just wrapping the application in that middleware before
  750. serving.
  751. :param passthrough_errors: set this to `True` to disable the error catching.
  752. This means that the server will die on errors but
  753. it can be useful to hook debuggers in (pdb etc.)
  754. :param ssl_context: an SSL context for the connection. Either an
  755. :class:`ssl.SSLContext`, a tuple in the form
  756. ``(cert_file, pkey_file)``, the string ``'adhoc'`` if
  757. the server should automatically create one, or ``None``
  758. to disable SSL (which is the default).
  759. """
  760. if not isinstance(port, int):
  761. raise TypeError("port must be an integer")
  762. if use_debugger:
  763. from .debug import DebuggedApplication
  764. application = DebuggedApplication(application, use_evalex)
  765. if static_files:
  766. from .middleware.shared_data import SharedDataMiddleware
  767. application = SharedDataMiddleware(application, static_files)
  768. def log_startup(sock):
  769. display_hostname = hostname if hostname not in ("", "*") else "localhost"
  770. quit_msg = "(Press CTRL+C to quit)"
  771. if sock.family == af_unix:
  772. _log("info", " * Running on %s %s", display_hostname, quit_msg)
  773. else:
  774. if ":" in display_hostname:
  775. display_hostname = "[%s]" % display_hostname
  776. port = sock.getsockname()[1]
  777. _log(
  778. "info",
  779. " * Running on %s://%s:%d/ %s",
  780. "http" if ssl_context is None else "https",
  781. display_hostname,
  782. port,
  783. quit_msg,
  784. )
  785. def inner():
  786. try:
  787. fd = int(os.environ["WERKZEUG_SERVER_FD"])
  788. except (LookupError, ValueError):
  789. fd = None
  790. srv = make_server(
  791. hostname,
  792. port,
  793. application,
  794. threaded,
  795. processes,
  796. request_handler,
  797. passthrough_errors,
  798. ssl_context,
  799. fd=fd,
  800. )
  801. if fd is None:
  802. log_startup(srv.socket)
  803. srv.serve_forever()
  804. if use_reloader:
  805. # If we're not running already in the subprocess that is the
  806. # reloader we want to open up a socket early to make sure the
  807. # port is actually available.
  808. if not is_running_from_reloader():
  809. if port == 0 and not can_open_by_fd:
  810. raise ValueError(
  811. "Cannot bind to a random port with enabled "
  812. "reloader if the Python interpreter does "
  813. "not support socket opening by fd."
  814. )
  815. # Create and destroy a socket so that any exceptions are
  816. # raised before we spawn a separate Python interpreter and
  817. # lose this ability.
  818. address_family = select_address_family(hostname, port)
  819. server_address = get_sockaddr(hostname, port, address_family)
  820. s = socket.socket(address_family, socket.SOCK_STREAM)
  821. s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  822. s.bind(server_address)
  823. if hasattr(s, "set_inheritable"):
  824. s.set_inheritable(True)
  825. # If we can open the socket by file descriptor, then we can just
  826. # reuse this one and our socket will survive the restarts.
  827. if can_open_by_fd:
  828. os.environ["WERKZEUG_SERVER_FD"] = str(s.fileno())
  829. s.listen(LISTEN_QUEUE)
  830. log_startup(s)
  831. else:
  832. s.close()
  833. if address_family == af_unix:
  834. _log("info", "Unlinking %s" % server_address)
  835. os.unlink(server_address)
  836. # Do not use relative imports, otherwise "python -m werkzeug.serving"
  837. # breaks.
  838. from ._reloader import run_with_reloader
  839. run_with_reloader(inner, extra_files, reloader_interval, reloader_type)
  840. else:
  841. inner()
  842. def run_with_reloader(*args, **kwargs):
  843. # People keep using undocumented APIs. Do not use this function
  844. # please, we do not guarantee that it continues working.
  845. from ._reloader import run_with_reloader
  846. return run_with_reloader(*args, **kwargs)
  847. def main():
  848. """A simple command-line interface for :py:func:`run_simple`."""
  849. # in contrast to argparse, this works at least under Python < 2.7
  850. import optparse
  851. from .utils import import_string
  852. parser = optparse.OptionParser(usage="Usage: %prog [options] app_module:app_object")
  853. parser.add_option(
  854. "-b",
  855. "--bind",
  856. dest="address",
  857. help="The hostname:port the app should listen on.",
  858. )
  859. parser.add_option(
  860. "-d",
  861. "--debug",
  862. dest="use_debugger",
  863. action="store_true",
  864. default=False,
  865. help="Use Werkzeug's debugger.",
  866. )
  867. parser.add_option(
  868. "-r",
  869. "--reload",
  870. dest="use_reloader",
  871. action="store_true",
  872. default=False,
  873. help="Reload Python process if modules change.",
  874. )
  875. options, args = parser.parse_args()
  876. hostname, port = None, None
  877. if options.address:
  878. address = options.address.split(":")
  879. hostname = address[0]
  880. if len(address) > 1:
  881. port = address[1]
  882. if len(args) != 1:
  883. sys.stdout.write("No application supplied, or too much. See --help\n")
  884. sys.exit(1)
  885. app = import_string(args[0])
  886. run_simple(
  887. hostname=(hostname or "127.0.0.1"),
  888. port=int(port or 5000),
  889. application=app,
  890. use_reloader=options.use_reloader,
  891. use_debugger=options.use_debugger,
  892. )
  893. if __name__ == "__main__":
  894. main()