Debian Codegraph @

django/core/servers/basehttp.py

raw
1 """
2 HTTP server that implements the Python WSGI protocol (PEP 333, rev 1.21).
3
4 Based on wsgiref.simple_server which is part of the standard library since 2.5.
5
6 This is a simple server for use in testing or debugging Django apps. It hasn't
7 been reviewed for security issues. DON'T USE IT FOR PRODUCTION USE!
8 """
9
10 import logging
11 import socket
12 import socketserver
13 import sys
14 from collections import deque
15 from wsgiref import simple_server
16
17 from django.core.exceptions import ImproperlyConfigured
18 from django.core.handlers.wsgi import LimitedStream
19 from django.core.wsgi import get_wsgi_application
20 from django.db import connections
21 from django.utils.module_loading import import_string
22
23 __all__ = ("WSGIServer", "WSGIRequestHandler")
24
25 logger = logging.getLogger("django.server")
26
27
28 def get_internal_wsgi_application():
29 """
30 Load and return the WSGI application as configured by the user in
31 ``settings.WSGI_APPLICATION``. With the default ``startproject`` layout,
32 this will be the ``application`` object in ``projectname/wsgi.py``.
33
34 This function, and the ``WSGI_APPLICATION`` setting itself, are only useful
35 for Django's internal server (runserver); external WSGI servers should just
36 be configured to point to the correct application object directly.
37
38 If settings.WSGI_APPLICATION is not set (is ``None``), return
39 whatever ``django.core.wsgi.get_wsgi_application`` returns.
40 """
41 from django.conf import settings
42
43 app_path = getattr(settings, "WSGI_APPLICATION")
44 if app_path is None:
45 return get_wsgi_application()
46
47 try:
48 return import_string(app_path)
49 except ImportError as err:
50 raise ImproperlyConfigured(
51 "WSGI application '%s' could not be loaded; "
52 "Error importing module." % app_path
53 ) from err
54
55
56 def is_broken_pipe_error():
57 exc_type, _, _ = sys.exc_info()
58 return issubclass(
59 exc_type,
60 (
61 BrokenPipeError,
62 ConnectionAbortedError,
63 ConnectionResetError,
64 ),
65 )
66
67
68 class WSGIServer(simple_server.WSGIServer):
69 """BaseHTTPServer that implements the Python WSGI protocol"""
70
71 request_queue_size = 10
72
73 def __init__(self, *args, ipv6=False, allow_reuse_address=True, **kwargs):
74 if ipv6:
75 self.address_family = socket.AF_INET6
76 self.allow_reuse_address = allow_reuse_address
77 super().__init__(*args, **kwargs)
78
79 def handle_error(self, request, client_address):
80 if is_broken_pipe_error():
81 logger.info("- Broken pipe from %s", client_address)
82 else:
83 super().handle_error(request, client_address)
84
85
86 class ThreadedWSGIServer(socketserver.ThreadingMixIn, WSGIServer):
87 """A threaded version of the WSGIServer"""
88
89 daemon_threads = True
90
91 def __init__(self, *args, connections_override=None, **kwargs):
92 super().__init__(*args, **kwargs)
93 self.connections_override = connections_override
94
95 # socketserver.ThreadingMixIn.process_request() passes this method as
96 # the target to a new Thread object.
97 def process_request_thread(self, request, client_address):
98 if self.connections_override:
99 # Override this thread's database connections with the ones
100 # provided by the parent thread.
101 for alias, conn in self.connections_override.items():
102 connections[alias] = conn
103 super().process_request_thread(request, client_address)
104
105 def _close_connections(self):
106 # Used for mocking in tests.
107 connections.close_all()
108
109 def close_request(self, request):
110 self._close_connections()
111 super().close_request(request)
112
113
114 class ServerHandler(simple_server.ServerHandler):
115 http_version = "1.1"
116
117 def __init__(self, stdin, stdout, stderr, environ, **kwargs):
118 """
119 Use a LimitedStream so that unread request data will be ignored at
120 the end of the request. WSGIRequest uses a LimitedStream but it
121 shouldn't discard the data since the upstream servers usually do this.
122 This fix applies only for testserver/runserver.
123 """
124 try:
125 content_length = int(environ.get("CONTENT_LENGTH"))
126 except (ValueError, TypeError):
127 content_length = 0
128 super().__init__(
129 LimitedStream(stdin, content_length), stdout, stderr, environ, **kwargs
130 )
131
132 def cleanup_headers(self):
133 super().cleanup_headers()
134 if (
135 self.environ["REQUEST_METHOD"] == "HEAD"
136 and "Content-Length" in self.headers
137 and str(self.headers["Content-Length"]) == "0"
138 ):
139 del self.headers["Content-Length"]
140 # HTTP/1.1 requires support for persistent connections. Send 'close' if
141 # the content length is unknown to prevent clients from reusing the
142 # connection.
143 if (
144 self.environ["REQUEST_METHOD"] != "HEAD"
145 and "Content-Length" not in self.headers
146 ):
147 self.headers["Connection"] = "close"
148 # Persistent connections require threading server.
149 elif not isinstance(self.request_handler.server, socketserver.ThreadingMixIn):
150 self.headers["Connection"] = "close"
151 # Mark the connection for closing if it's set as such above or if the
152 # application sent the header.
153 if self.headers.get("Connection") == "close":
154 self.request_handler.close_connection = True
155
156 def close(self):
157 self.get_stdin().read()
158 super().close()
159
160 def finish_response(self):
161 if self.environ["REQUEST_METHOD"] == "HEAD":
162 try:
163 deque(self.result, maxlen=0) # Consume iterator.
164 # Don't call self.finish_content() as, if the headers have not
165 # been sent and Content-Length isn't set, it'll default to "0"
166 # which will prevent omission of the Content-Length header with
167 # HEAD requests as permitted by RFC 9110 Section 9.3.2.
168 # Instead, send the headers, if not sent yet.
169 if not self.headers_sent:
170 self.send_headers()
171 finally:
172 self.close()
173 else:
174 super().finish_response()
175
176
177 class WSGIRequestHandler(simple_server.WSGIRequestHandler):
178 protocol_version = "HTTP/1.1"
179
180 def address_string(self):
181 # Short-circuit parent method to not call socket.getfqdn
182 return self.client_address[0]
183
184 def log_message(self, format, *args):
185 extra = {
186 "request": self.request,
187 "server_time": self.log_date_time_string(),
188 }
189 if args[1][0] == "4":
190 # 0x16 = Handshake, 0x03 = SSL 3.0 or TLS 1.x
191 if args[0].startswith("\x16\x03"):
192 extra["status_code"] = 500
193 logger.error(
194 "You're accessing the development server over HTTPS, but "
195 "it only supports HTTP.",
196 extra=extra,
197 )
198 return
199
200 if args[1].isdigit() and len(args[1]) == 3:
201 status_code = int(args[1])
202 extra["status_code"] = status_code
203
204 if status_code >= 500:
205 level = logger.error
206 elif status_code >= 400:
207 level = logger.warning
208 else:
209 level = logger.info
210 else:
211 level = logger.info
212
213 level(format, *args, extra=extra)
214
215 def get_environ(self):
216 # Strip all headers with underscores in the name before constructing
217 # the WSGI environ. This prevents header-spoofing based on ambiguity
218 # between underscores and dashes both normalized to underscores in WSGI
219 # env vars. Nginx and Apache 2.4+ both do this as well.
220 for k in self.headers:
221 if "_" in k:
222 del self.headers[k]
223
224 return super().get_environ()
225
226 def handle(self):
227 self.close_connection = True
228 self.handle_one_request()
229 while not self.close_connection:
230 self.handle_one_request()
231 try:
232 self.connection.shutdown(socket.SHUT_WR)
233 except (AttributeError, OSError):
234 pass
235
236 def handle_one_request(self):
237 """Copy of WSGIRequestHandler.handle() but with different ServerHandler"""
238 self.raw_requestline = self.rfile.readline(65537)
239 if len(self.raw_requestline) > 65536:
240 self.requestline = ""
241 self.request_version = ""
242 self.command = ""
243 self.send_error(414)
244 return
245
246 if not self.parse_request(): # An error code has been sent, just exit
247 return
248
249 handler = ServerHandler(
250 self.rfile, self.wfile, self.get_stderr(), self.get_environ()
251 )
252 handler.request_handler = self # backpointer for logging & connection closing
253 handler.run(self.server.get_app())
254
255
256 def run(
257 addr,
258 port,
259 wsgi_handler,
260 ipv6=False,
261 threading=False,
262 on_bind=None,
263 server_cls=WSGIServer,
264 ):
265 server_address = (addr, port)
266 if threading:
267 httpd_cls = type("WSGIServer", (socketserver.ThreadingMixIn, server_cls), {})
268 else:
269 httpd_cls = server_cls
270 httpd = httpd_cls(server_address, WSGIRequestHandler, ipv6=ipv6)
271 if on_bind is not None:
272 on_bind(getattr(httpd, "server_port", port))
273 if threading:
274 # ThreadingMixIn.daemon_threads indicates how threads will behave on an
275 # abrupt shutdown; like quitting the server by the user or restarting
276 # by the auto-reloader. True means the server will not wait for thread
277 # termination before it quits. This will make auto-reloader faster
278 # and will prevent the need to kill the server manually if a thread
279 # isn't terminating correctly.
280 httpd.daemon_threads = True
281 httpd.set_app(wsgi_handler)
282 httpd.serve_forever()