Debian Codegraph @

django/core/handlers/wsgi.py

raw
1 from io import IOBase
2
3 from django.conf import settings
4 from django.core import signals
5 from django.core.handlers import base
6 from django.http import HttpRequest, QueryDict, parse_cookie
7 from django.urls import set_script_prefix
8 from django.utils.encoding import repercent_broken_unicode
9 from django.utils.functional import cached_property
10 from django.utils.regex_helper import _lazy_re_compile
11
12 _slashes_re = _lazy_re_compile(rb"/+")
13
14
15 class LimitedStream(IOBase):
16 """
17 Wrap another stream to disallow reading it past a number of bytes.
18
19 Based on the implementation from werkzeug.wsgi.LimitedStream
20 See https://github.com/pallets/werkzeug/blob/dbf78f67/src/werkzeug/wsgi.py#L828
21 """
22
23 def __init__(self, stream, limit):
24 self._read = stream.read
25 self._readline = stream.readline
26 self._pos = 0
27 self.limit = limit
28
29 def read(self, size=-1, /):
30 _pos = self._pos
31 limit = self.limit
32 if _pos >= limit:
33 return b""
34 if size == -1 or size is None:
35 size = limit - _pos
36 else:
37 size = min(size, limit - _pos)
38 data = self._read(size)
39 self._pos += len(data)
40 return data
41
42 def readline(self, size=-1, /):
43 _pos = self._pos
44 limit = self.limit
45 if _pos >= limit:
46 return b""
47 if size == -1 or size is None:
48 size = limit - _pos
49 else:
50 size = min(size, limit - _pos)
51 line = self._readline(size)
52 self._pos += len(line)
53 return line
54
55
56 class WSGIRequest(HttpRequest):
57 def __init__(self, environ):
58 script_name = get_script_name(environ)
59 # If PATH_INFO is empty (e.g. accessing the SCRIPT_NAME URL without a
60 # trailing slash), operate as if '/' was requested.
61 path_info = get_path_info(environ) or "/"
62 self.environ = environ
63 self.path_info = path_info
64 # be careful to only replace the first slash in the path because of
65 # http://test/something and http://test//something being different as
66 # stated in RFC 3986.
67 self.path = "%s/%s" % (script_name.rstrip("/"), path_info.replace("/", "", 1))
68 self.META = environ
69 self.META["PATH_INFO"] = path_info
70 self.META["SCRIPT_NAME"] = script_name
71 self.method = environ["REQUEST_METHOD"].upper()
72 # Set content_type, content_params, and encoding.
73 self._set_content_type_params(environ)
74 try:
75 content_length = int(environ.get("CONTENT_LENGTH"))
76 except (ValueError, TypeError):
77 content_length = 0
78 self._stream = LimitedStream(self.environ["wsgi.input"], content_length)
79 self._read_started = False
80 self.resolver_match = None
81
82 def _get_scheme(self):
83 return self.environ.get("wsgi.url_scheme")
84
85 @cached_property
86 def GET(self):
87 # The WSGI spec says 'QUERY_STRING' may be absent.
88 raw_query_string = get_bytes_from_wsgi(self.environ, "QUERY_STRING", "")
89 return QueryDict(raw_query_string, encoding=self._encoding)
90
91 def _get_post(self):
92 if not hasattr(self, "_post"):
93 self._load_post_and_files()
94 return self._post
95
96 def _set_post(self, post):
97 self._post = post
98
99 @cached_property
100 def COOKIES(self):
101 raw_cookie = get_str_from_wsgi(self.environ, "HTTP_COOKIE", "")
102 return parse_cookie(raw_cookie)
103
104 @property
105 def FILES(self):
106 if not hasattr(self, "_files"):
107 self._load_post_and_files()
108 return self._files
109
110 POST = property(_get_post, _set_post)
111
112
113 class WSGIHandler(base.BaseHandler):
114 request_class = WSGIRequest
115
116 def __init__(self, *args, **kwargs):
117 super().__init__(*args, **kwargs)
118 self.load_middleware()
119
120 def __call__(self, environ, start_response):
121 set_script_prefix(get_script_name(environ))
122 signals.request_started.send(sender=self.__class__, environ=environ)
123 request = self.request_class(environ)
124 response = self.get_response(request)
125
126 response._handler_class = self.__class__
127
128 status = "%d %s" % (response.status_code, response.reason_phrase)
129 response_headers = [
130 *response.items(),
131 *(("Set-Cookie", c.output(header="")) for c in response.cookies.values()),
132 ]
133 start_response(status, response_headers)
134 if getattr(response, "file_to_stream", None) is not None and environ.get(
135 "wsgi.file_wrapper"
136 ):
137 # If `wsgi.file_wrapper` is used the WSGI server does not call
138 # .close on the response, but on the file wrapper. Patch it to use
139 # response.close instead which takes care of closing all files.
140 response.file_to_stream.close = response.close
141 response = environ["wsgi.file_wrapper"](
142 response.file_to_stream, response.block_size
143 )
144 return response
145
146
147 def get_path_info(environ):
148 """Return the HTTP request's PATH_INFO as a string."""
149 path_info = get_bytes_from_wsgi(environ, "PATH_INFO", "/")
150
151 return repercent_broken_unicode(path_info).decode()
152
153
154 def get_script_name(environ):
155 """
156 Return the equivalent of the HTTP request's SCRIPT_NAME environment
157 variable. If Apache mod_rewrite is used, return what would have been
158 the script name prior to any rewriting (so it's the script name as seen
159 from the client's perspective), unless the FORCE_SCRIPT_NAME setting is
160 set (to anything).
161 """
162 if settings.FORCE_SCRIPT_NAME is not None:
163 return settings.FORCE_SCRIPT_NAME
164
165 # If Apache's mod_rewrite had a whack at the URL, Apache set either
166 # SCRIPT_URL or REDIRECT_URL to the full resource URL before applying any
167 # rewrites. Unfortunately not every web server (lighttpd!) passes this
168 # information through all the time, so FORCE_SCRIPT_NAME, above, is still
169 # needed.
170 script_url = get_bytes_from_wsgi(environ, "SCRIPT_URL", "") or get_bytes_from_wsgi(
171 environ, "REDIRECT_URL", ""
172 )
173
174 if script_url:
175 if b"//" in script_url:
176 # mod_wsgi squashes multiple successive slashes in PATH_INFO,
177 # do the same with script_url before manipulating paths (#17133).
178 script_url = _slashes_re.sub(b"/", script_url)
179 path_info = get_bytes_from_wsgi(environ, "PATH_INFO", "")
180 script_name = script_url.removesuffix(path_info)
181 else:
182 script_name = get_bytes_from_wsgi(environ, "SCRIPT_NAME", "")
183
184 return script_name.decode()
185
186
187 def get_bytes_from_wsgi(environ, key, default):
188 """
189 Get a value from the WSGI environ dictionary as bytes.
190
191 key and default should be strings.
192 """
193 value = environ.get(key, default)
194 # Non-ASCII values in the WSGI environ are arbitrarily decoded with
195 # ISO-8859-1. This is wrong for Django websites where UTF-8 is the default.
196 # Re-encode to recover the original bytestring.
197 return value.encode("iso-8859-1")
198
199
200 def get_str_from_wsgi(environ, key, default):
201 """
202 Get a value from the WSGI environ dictionary as str.
203
204 key and default should be str objects.
205 """
206 value = get_bytes_from_wsgi(environ, key, default)
207 return value.decode(errors="replace")