serving.py 38 KB

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