Code

Ticket #6256: 6256-2.diff

File 6256-2.diff, 2.0 KB (added by Karen Tracey <kmtracey@…>, 6 years ago)

Better patch that doesn't corrupt binary data.

Line 
1Index: django/http/__init__.py
2===================================================================
3--- django/http/__init__.py     (revision 7397)
4+++ django/http/__init__.py     (working copy)
5@@ -9,6 +9,36 @@
6 except ImportError:
7     from cgi import parse_qsl
8 
9+from email.parser import Parser
10+try:
11+    from email.feedparser import FeedParser
12+    class ParserClass(Parser):
13+        # Copy of Python's Parser's parse patched to properly deal with CRLF
14+        # sequences that happen to fall at an 8192-byte boundary (see
15+        # http://bugs.python.org/issue1555570)
16+        def parse(self, fp, headersonly=False):
17+            """Create a message structure from the data in a file.
18+   
19+            Reads all the data from the file and returns the root of the message
20+            structure.  Optional headersonly is a flag specifying whether to stop
21+            parsing after reading the headers or not.  The default is False,
22+            meaning it parses the entire contents of the file.
23+            """
24+            feedparser = FeedParser(self._class)
25+            if headersonly:
26+                feedparser._set_headersonly()
27+            while True:
28+                data = fp.read(8192)
29+                if not data:
30+                    break
31+                if data[-1] == '\r':
32+                    # Don't split a CRLF.
33+                    data += fp.read(1)
34+                feedparser.feed(data)
35+            return feedparser.close()
36+except ImportError:
37+    ParserClass = Parser
38+
39 from django.utils.datastructures import MultiValueDict, FileDict
40 from django.utils.encoding import smart_str, iri_to_uri, force_unicode
41 
42@@ -108,7 +138,7 @@
43     from cgi import parse_header
44     raw_message = '\r\n'.join(['%s:%s' % pair for pair in header_dict.items()])
45     raw_message += '\r\n\r\n' + post_data
46-    msg = email.message_from_string(raw_message)
47+    msg = ParserClass().parsestr(raw_message)
48     POST = QueryDict('', mutable=True)
49     FILES = MultiValueDict()
50     for submessage in msg.get_payload():