-
-
Notifications
You must be signed in to change notification settings - Fork 62
/
multipart.py
1911 lines (1569 loc) · 70.2 KB
/
multipart.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import with_statement, absolute_import, print_function
from six import (
binary_type,
text_type,
PY3,
)
from .decoders import *
from .exceptions import *
try:
from urlparse import parse_qs
except ImportError:
from urllib.parse import parse_qs
import os
import re
import sys
import shutil
import logging
import tempfile
from io import BytesIO
from numbers import Number
# Unique missing object.
_missing = object()
# States for the querystring parser.
STATE_BEFORE_FIELD = 0
STATE_FIELD_NAME = 1
STATE_FIELD_DATA = 2
# States for the multipart parser
STATE_START = 0
STATE_START_BOUNDARY = 1
STATE_HEADER_FIELD_START = 2
STATE_HEADER_FIELD = 3
STATE_HEADER_VALUE_START = 4
STATE_HEADER_VALUE = 5
STATE_HEADER_VALUE_ALMOST_DONE = 6
STATE_HEADERS_ALMOST_DONE = 7
STATE_PART_DATA_START = 8
STATE_PART_DATA = 9
STATE_PART_DATA_END = 10
STATE_END = 11
STATES = [
"START",
"START_BOUNDARY", "HEADER_FEILD_START", "HEADER_FIELD", "HEADER_VALUE_START", "HEADER_VALUE",
"HEADER_VALUE_ALMOST_DONE", "HEADRES_ALMOST_DONE", "PART_DATA_START", "PART_DATA", "PART_DATA_END", "END"
]
# Flags for the multipart parser.
FLAG_PART_BOUNDARY = 1
FLAG_LAST_BOUNDARY = 2
# Get constants. Since iterating over a str on Python 2 gives you a 1-length
# string, but iterating over a bytes object on Python 3 gives you an integer,
# we need to save these constants.
CR = b'\r'[0]
LF = b'\n'[0]
COLON = b':'[0]
SPACE = b' '[0]
HYPHEN = b'-'[0]
AMPERSAND = b'&'[0]
SEMICOLON = b';'[0]
LOWER_A = b'a'[0]
LOWER_Z = b'z'[0]
NULL = b'\x00'[0]
# Lower-casing a character is different, because of the difference between
# str on Py2, and bytes on Py3. Same with getting the ordinal value of a byte,
# and joining a list of bytes together.
# These functions abstract that.
if PY3: # pragma: no cover
lower_char = lambda c: c | 0x20
ord_char = lambda c: c
join_bytes = lambda b: bytes(list(b))
else: # pragma: no cover
lower_char = lambda c: c.lower()
ord_char = lambda c: ord(c)
join_bytes = lambda b: b''.join(list(b))
# These are regexes for parsing header values.
SPECIAL_CHARS = re.escape(b'()<>@,;:\\"/[]?={} \t')
QUOTED_STR = br'"(?:\\.|[^"])*"'
VALUE_STR = br'(?:[^' + SPECIAL_CHARS + br']+|' + QUOTED_STR + br')'
OPTION_RE_STR = (
br'(?:;|^)\s*([^' + SPECIAL_CHARS + br']+)\s*=\s*(' + VALUE_STR + br')'
)
OPTION_RE = re.compile(OPTION_RE_STR)
QUOTE = b'"'[0]
def parse_options_header(value):
"""
Parses a Content-Type header into a value in the following format:
(content_type, {parameters})
"""
if not value:
return (b'', {})
# If we are passed a string, we assume that it conforms to WSGI and does
# not contain any code point that's not in latin-1.
if isinstance(value, text_type): # pragma: no cover
value = value.encode('latin-1')
# If we have no options, return the string as-is.
if b';' not in value:
return (value.lower().strip(), {})
# Split at the first semicolon, to get our value and then options.
ctype, rest = value.split(b';', 1)
options = {}
# Parse the options.
for match in OPTION_RE.finditer(rest):
key = match.group(1).lower()
value = match.group(2)
if value[0] == QUOTE and value[-1] == QUOTE:
# Unquote the value.
value = value[1:-1]
value = value.replace(b'\\\\', b'\\').replace(b'\\"', b'"')
# If the value is a filename, we need to fix a bug on IE6 that sends
# the full file path instead of the filename.
if key == b'filename':
if value[1:3] == b':\\' or value[:2] == b'\\\\':
value = value.split(b'\\')[-1]
options[key] = value
return ctype, options
class Field(object):
"""A Field object represents a (parsed) form field. It represents a single
field with a corresponding name and value.
The name that a :class:`Field` will be instantiated with is the same name
that would be found in the following HTML::
<input name="name_goes_here" type="text"/>
This class defines two methods, :meth:`on_data` and :meth:`on_end`, that
will be called when data is written to the Field, and when the Field is
finalized, respectively.
:param name: the name of the form field
"""
def __init__(self, name):
self._name = name
self._value = []
# We cache the joined version of _value for speed.
self._cache = _missing
@classmethod
def from_value(klass, name, value):
"""Create an instance of a :class:`Field`, and set the corresponding
value - either None or an actual value. This method will also
finalize the Field itself.
:param name: the name of the form field
:param value: the value of the form field - either a bytestring or
None
"""
f = klass(name)
if value is None:
f.set_none()
else:
f.write(value)
f.finalize()
return f
def write(self, data):
"""Write some data into the form field.
:param data: a bytestring
"""
return self.on_data(data)
def on_data(self, data):
"""This method is a callback that will be called whenever data is
written to the Field.
:param data: a bytestring
"""
self._value.append(data)
self._cache = _missing
return len(data)
def on_end(self):
"""This method is called whenever the Field is finalized.
"""
if self._cache is _missing:
self._cache = b''.join(self._value)
def finalize(self):
"""Finalize the form field.
"""
self.on_end()
def close(self):
"""Close the Field object. This will free any underlying cache.
"""
# Free our value array.
if self._cache is _missing:
self._cache = b''.join(self._value)
del self._value
def set_none(self):
"""Some fields in a querystring can possibly have a value of None - for
example, the string "foo&bar=&baz=asdf" will have a field with the
name "foo" and value None, one with name "bar" and value "", and one
with name "baz" and value "asdf". Since the write() interface doesn't
support writing None, this function will set the field value to None.
"""
self._cache = None
@property
def field_name(self):
"""This property returns the name of the field."""
return self._name
@property
def value(self):
"""This property returns the value of the form field."""
if self._cache is _missing:
self._cache = b''.join(self._value)
return self._cache
def __eq__(self, other):
if isinstance(other, Field):
return (
self.field_name == other.field_name and
self.value == other.value
)
else:
return NotImplemented
def __repr__(self):
if len(self.value) > 97:
# We get the repr, and then insert three dots before the final
# quote.
v = repr(self.value[:97])[:-1] + "...'"
else:
v = repr(self.value)
return "%s(field_name=%r, value=%s)" % (
self.__class__.__name__,
self.field_name,
v
)
class File(object):
"""This class represents an uploaded file. It handles writing file data to
either an in-memory file or a temporary file on-disk, if the optional
threshold is passed.
There are some options that can be passed to the File to change behavior
of the class. Valid options are as follows:
.. list-table::
:widths: 15 5 5 30
:header-rows: 1
* - Name
- Type
- Default
- Description
* - UPLOAD_DIR
- `str`
- None
- The directory to store uploaded files in. If this is None, a
temporary file will be created in the system's standard location.
* - UPLOAD_DELETE_TMP
- `bool`
- True
- Delete automatically created TMP file
* - UPLOAD_KEEP_FILENAME
- `bool`
- False
- Whether or not to keep the filename of the uploaded file. If True,
then the filename will be converted to a safe representation (e.g.
by removing any invalid path segments), and then saved with the
same name). Otherwise, a temporary name will be used.
* - UPLOAD_KEEP_EXTENSIONS
- `bool`
- False
- Whether or not to keep the uploaded file's extension. If False, the
file will be saved with the default temporary extension (usually
".tmp"). Otherwise, the file's extension will be maintained. Note
that this will properly combine with the UPLOAD_KEEP_FILENAME
setting.
* - MAX_MEMORY_FILE_SIZE
- `int`
- 1 MiB
- The maximum number of bytes of a File to keep in memory. By
default, the contents of a File are kept into memory until a certain
limit is reached, after which the contents of the File are written
to a temporary file. This behavior can be disabled by setting this
value to an appropriately large value (or, for example, infinity,
such as `float('inf')`.
:param file_name: The name of the file that this :class:`File` represents
:param field_name: The field name that uploaded this file. Note that this
can be None, if, for example, the file was uploaded
with Content-Type application/octet-stream
:param config: The configuration for this File. See above for valid
configuration keys and their corresponding values.
"""
def __init__(self, file_name, field_name=None, config={}):
# Save configuration, set other variables default.
self.logger = logging.getLogger(__name__)
self._config = config
self._in_memory = True
self._bytes_written = 0
self._fileobj = BytesIO()
# Save the provided field/file name.
self._field_name = field_name
self._file_name = file_name
# Our actual file name is None by default, since, depending on our
# config, we may not actually use the provided name.
self._actual_file_name = None
# Split the extension from the filename.
if file_name is not None:
base, ext = os.path.splitext(file_name)
self._file_base = base
self._ext = ext
@property
def field_name(self):
"""The form field associated with this file. May be None if there isn't
one, for example when we have an application/octet-stream upload.
"""
return self._field_name
@property
def file_name(self):
"""The file name given in the upload request.
"""
return self._file_name
@property
def actual_file_name(self):
"""The file name that this file is saved as. Will be None if it's not
currently saved on disk.
"""
return self._actual_file_name
@property
def file_object(self):
"""The file object that we're currently writing to. Note that this
will either be an instance of a :class:`io.BytesIO`, or a regular file
object.
"""
return self._fileobj
@property
def size(self):
"""The total size of this file, counted as the number of bytes that
currently have been written to the file.
"""
return self._bytes_written
@property
def in_memory(self):
"""A boolean representing whether or not this file object is currently
stored in-memory or on-disk.
"""
return self._in_memory
def flush_to_disk(self):
"""If the file is already on-disk, do nothing. Otherwise, copy from
the in-memory buffer to a disk file, and then reassign our internal
file object to this new disk file.
Note that if you attempt to flush a file that is already on-disk, a
warning will be logged to this module's logger.
"""
if not self._in_memory:
self.logger.warning(
"Trying to flush to disk when we're not in memory"
)
return
# Go back to the start of our file.
self._fileobj.seek(0)
# Open a new file.
new_file = self._get_disk_file()
# Copy the file objects.
shutil.copyfileobj(self._fileobj, new_file)
# Seek to the new position in our new file.
new_file.seek(self._bytes_written)
# Reassign the fileobject.
old_fileobj = self._fileobj
self._fileobj = new_file
# We're no longer in memory.
self._in_memory = False
# Close the old file object.
old_fileobj.close()
def _get_disk_file(self):
"""This function is responsible for getting a file object on-disk for us.
"""
self.logger.info("Opening a file on disk")
file_dir = self._config.get('UPLOAD_DIR')
keep_filename = self._config.get('UPLOAD_KEEP_FILENAME', False)
keep_extensions = self._config.get('UPLOAD_KEEP_EXTENSIONS', False)
delete_tmp = self._config.get('UPLOAD_DELETE_TMP', True)
# If we have a directory and are to keep the filename...
if file_dir is not None and keep_filename:
self.logger.info("Saving with filename in: %r", file_dir)
# Build our filename.
# TODO: what happens if we don't have a filename?
fname = self._file_base
if keep_extensions:
fname = fname + self._ext
path = os.path.join(file_dir, fname)
try:
self.logger.info("Opening file: %r", path)
tmp_file = open(path, 'w+b')
except (IOError, OSError) as e:
tmp_file = None
self.logger.exception("Error opening temporary file")
raise FileError("Error opening temporary file: %r" % path)
else:
# Build options array.
# Note that on Python 3, tempfile doesn't support byte names. We
# encode our paths using the default filesystem encoding.
options = {}
if keep_extensions:
ext = self._ext
if isinstance(ext, binary_type):
ext = ext.decode(sys.getfilesystemencoding())
options['suffix'] = ext
if file_dir is not None:
d = file_dir
if isinstance(d, binary_type):
d = d.decode(sys.getfilesystemencoding())
options['dir'] = d
options['delete'] = delete_tmp
# Create a temporary (named) file with the appropriate settings.
self.logger.info("Creating a temporary file with options: %r",
options)
try:
tmp_file = tempfile.NamedTemporaryFile(**options)
except (IOError, OSError):
self.logger.exception("Error creating named temporary file")
raise FileError("Error creating named temporary file")
fname = tmp_file.name
# Encode filename as bytes.
if isinstance(fname, text_type):
fname = fname.encode(sys.getfilesystemencoding())
self._actual_file_name = fname
return tmp_file
def write(self, data):
"""Write some data to the File.
:param data: a bytestring
"""
return self.on_data(data)
def on_data(self, data):
"""This method is a callback that will be called whenever data is
written to the File.
:param data: a bytestring
"""
pos = self._fileobj.tell()
bwritten = self._fileobj.write(data)
# true file objects write returns None
if bwritten is None:
bwritten = self._fileobj.tell() - pos
# If the bytes written isn't the same as the length, just return.
if bwritten != len(data):
self.logger.warning("bwritten != len(data) (%d != %d)", bwritten,
len(data))
return bwritten
# Keep track of how many bytes we've written.
self._bytes_written += bwritten
# If we're in-memory and are over our limit, we create a file.
if (self._in_memory and
self._config.get('MAX_MEMORY_FILE_SIZE') is not None and
(self._bytes_written >
self._config.get('MAX_MEMORY_FILE_SIZE'))):
self.logger.info("Flushing to disk")
self.flush_to_disk()
# Return the number of bytes written.
return bwritten
def on_end(self):
"""This method is called whenever the Field is finalized.
"""
# Flush the underlying file object
self._fileobj.flush()
def finalize(self):
"""Finalize the form file. This will not close the underlying file,
but simply signal that we are finished writing to the File.
"""
self.on_end()
def close(self):
"""Close the File object. This will actually close the underlying
file object (whether it's a :class:`io.BytesIO` or an actual file
object).
"""
self._fileobj.close()
def __repr__(self):
return "%s(file_name=%r, field_name=%r)" % (
self.__class__.__name__,
self.file_name,
self.field_name
)
class BaseParser(object):
"""This class is the base class for all parsers. It contains the logic for
calling and adding callbacks.
A callback can be one of two different forms. "Notification callbacks" are
callbacks that are called when something happens - for example, when a new
part of a multipart message is encountered by the parser. "Data callbacks"
are called when we get some sort of data - for example, part of the body of
a multipart chunk. Notification callbacks are called with no parameters,
whereas data callbacks are called with three, as follows::
data_callback(data, start, end)
The "data" parameter is a bytestring (i.e. "foo" on Python 2, or b"foo" on
Python 3). "start" and "end" are integer indexes into the "data" string
that represent the data of interest. Thus, in a data callback, the slice
`data[start:end]` represents the data that the callback is "interested in".
The callback is not passed a copy of the data, since copying severely hurts
performance.
"""
def __init__(self):
self.logger = logging.getLogger(__name__)
def callback(self, name, data=None, start=None, end=None):
"""This function calls a provided callback with some data. If the
callback is not set, will do nothing.
:param name: The name of the callback to call (as a string).
:param data: Data to pass to the callback. If None, then it is
assumed that the callback is a notification callback,
and no parameters are given.
:param end: An integer that is passed to the data callback.
:param start: An integer that is passed to the data callback.
"""
name = "on_" + name
func = self.callbacks.get(name)
if func is None:
return
# Depending on whether we're given a buffer...
if data is not None:
# Don't do anything if we have start == end.
if start is not None and start == end:
return
self.logger.debug("Calling %s with data[%d:%d]", name, start, end)
func(data, start, end)
else:
self.logger.debug("Calling %s with no data", name)
func()
def set_callback(self, name, new_func):
"""Update the function for a callback. Removes from the callbacks dict
if new_func is None.
:param name: The name of the callback to call (as a string).
:param new_func: The new function for the callback. If None, then the
callback will be removed (with no error if it does not
exist).
"""
if new_func is None:
self.callbacks.pop('on_' + name, None)
else:
self.callbacks['on_' + name] = new_func
def close(self):
pass # pragma: no cover
def finalize(self):
pass # pragma: no cover
def __repr__(self):
return "%s()" % self.__class__.__name__
class OctetStreamParser(BaseParser):
"""This parser parses an octet-stream request body and calls callbacks when
incoming data is received. Callbacks are as follows:
.. list-table::
:widths: 15 10 30
:header-rows: 1
* - Callback Name
- Parameters
- Description
* - on_start
- None
- Called when the first data is parsed.
* - on_data
- data, start, end
- Called for each data chunk that is parsed.
* - on_end
- None
- Called when the parser is finished parsing all data.
:param callbacks: A dictionary of callbacks. See the documentation for
:class:`BaseParser`.
:param max_size: The maximum size of body to parse. Defaults to infinity -
i.e. unbounded.
"""
def __init__(self, callbacks={}, max_size=float('inf')):
super(OctetStreamParser, self).__init__()
self.callbacks = callbacks
self._started = False
if not isinstance(max_size, Number) or max_size < 1:
raise ValueError("max_size must be a positive number, not %r" %
max_size)
self.max_size = max_size
self._current_size = 0
def write(self, data):
"""Write some data to the parser, which will perform size verification,
and then pass the data to the underlying callback.
:param data: a bytestring
"""
if not self._started:
self.callback('start')
self._started = True
# Truncate data length.
data_len = len(data)
if (self._current_size + data_len) > self.max_size:
# We truncate the length of data that we are to process.
new_size = int(self.max_size - self._current_size)
self.logger.warning("Current size is %d (max %d), so truncating "
"data length from %d to %d",
self._current_size, self.max_size, data_len,
new_size)
data_len = new_size
# Increment size, then callback, in case there's an exception.
self._current_size += data_len
self.callback('data', data, 0, data_len)
return data_len
def finalize(self):
"""Finalize this parser, which signals to that we are finished parsing,
and sends the on_end callback.
"""
self.callback('end')
def __repr__(self):
return "%s()" % self.__class__.__name__
class QuerystringParser(BaseParser):
"""This is a streaming querystring parser. It will consume data, and call
the callbacks given when it has data.
.. list-table::
:widths: 15 10 30
:header-rows: 1
* - Callback Name
- Parameters
- Description
* - on_field_start
- None
- Called when a new field is encountered.
* - on_field_name
- data, start, end
- Called when a portion of a field's name is encountered.
* - on_field_data
- data, start, end
- Called when a portion of a field's data is encountered.
* - on_field_end
- None
- Called when the end of a field is encountered.
* - on_end
- None
- Called when the parser is finished parsing all data.
:param callbacks: A dictionary of callbacks. See the documentation for
:class:`BaseParser`.
:param strict_parsing: Whether or not to parse the body strictly. Defaults
to False. If this is set to True, then the behavior
of the parser changes as the following: if a field
has a value with an equal sign (e.g. "foo=bar", or
"foo="), it is always included. If a field has no
equals sign (e.g. "...&name&..."), it will be
treated as an error if 'strict_parsing' is True,
otherwise included. If an error is encountered,
then a
:class:`multipart.exceptions.QuerystringParseError`
will be raised.
:param max_size: The maximum size of body to parse. Defaults to infinity -
i.e. unbounded.
"""
def __init__(self, callbacks={}, strict_parsing=False,
max_size=float('inf')):
super(QuerystringParser, self).__init__()
self.state = STATE_BEFORE_FIELD
self._found_sep = False
self.callbacks = callbacks
# Max-size stuff
if not isinstance(max_size, Number) or max_size < 1:
raise ValueError("max_size must be a positive number, not %r" %
max_size)
self.max_size = max_size
self._current_size = 0
# Should parsing be strict?
self.strict_parsing = strict_parsing
def write(self, data):
"""Write some data to the parser, which will perform size verification,
parse into either a field name or value, and then pass the
corresponding data to the underlying callback. If an error is
encountered while parsing, a QuerystringParseError will be raised. The
"offset" attribute of the raised exception will be set to the offset in
the input data chunk (NOT the overall stream) that caused the error.
:param data: a bytestring
"""
# Handle sizing.
data_len = len(data)
if (self._current_size + data_len) > self.max_size:
# We truncate the length of data that we are to process.
new_size = int(self.max_size - self._current_size)
self.logger.warning("Current size is %d (max %d), so truncating "
"data length from %d to %d",
self._current_size, self.max_size, data_len,
new_size)
data_len = new_size
l = 0
try:
l = self._internal_write(data, data_len)
finally:
self._current_size += l
return l
def _internal_write(self, data, length):
state = self.state
strict_parsing = self.strict_parsing
found_sep = self._found_sep
i = 0
while i < length:
ch = data[i]
# Depending on our state...
if state == STATE_BEFORE_FIELD:
# If the 'found_sep' flag is set, we've already encountered
# and skipped a single seperator. If so, we check our strict
# parsing flag and decide what to do. Otherwise, we haven't
# yet reached a seperator, and thus, if we do, we need to skip
# it as it will be the boundary between fields that's supposed
# to be there.
if ch == AMPERSAND or ch == SEMICOLON:
if found_sep:
# If we're parsing strictly, we disallow blank chunks.
if strict_parsing:
e = QuerystringParseError(
"Skipping duplicate ampersand/semicolon at "
"%d" % i
)
e.offset = i
raise e
else:
self.logger.debug("Skipping duplicate ampersand/"
"semicolon at %d", i)
else:
# This case is when we're skipping the (first)
# seperator between fields, so we just set our flag
# and continue on.
found_sep = True
else:
# Emit a field-start event, and go to that state. Also,
# reset the "found_sep" flag, for the next time we get to
# this state.
self.callback('field_start')
i -= 1
state = STATE_FIELD_NAME
found_sep = False
elif state == STATE_FIELD_NAME:
# Try and find a seperator - we ensure that, if we do, we only
# look for the equal sign before it.
sep_pos = data.find(b'&', i)
if sep_pos == -1:
sep_pos = data.find(b';', i)
# See if we can find an equals sign in the remaining data. If
# so, we can immedately emit the field name and jump to the
# data state.
if sep_pos != -1:
equals_pos = data.find(b'=', i, sep_pos)
else:
equals_pos = data.find(b'=', i)
if equals_pos != -1:
# Emit this name.
self.callback('field_name', data, i, equals_pos)
# Jump i to this position. Note that it will then have 1
# added to it below, which means the next iteration of this
# loop will inspect the character after the equals sign.
i = equals_pos
state = STATE_FIELD_DATA
else:
# No equals sign found.
if not strict_parsing:
# See also comments in the STATE_FIELD_DATA case below.
# If we found the seperator, we emit the name and just
# end - there's no data callback at all (not even with
# a blank value).
if sep_pos != -1:
self.callback('field_name', data, i, sep_pos)
self.callback('field_end')
i = sep_pos - 1
state = STATE_BEFORE_FIELD
else:
# Otherwise, no seperator in this block, so the
# rest of this chunk must be a name.
self.callback('field_name', data, i, length)
i = length
else:
# We're parsing strictly. If we find a seperator,
# this is an error - we require an equals sign.
if sep_pos != -1:
e = QuerystringParseError(
"When strict_parsing is True, we require an "
"equals sign in all field chunks. Did not "
"find one in the chunk that starts at %d" %
(i,)
)
e.offset = i
raise e
# No seperator in the rest of this chunk, so it's just
# a field name.
self.callback('field_name', data, i, length)
i = length
elif state == STATE_FIELD_DATA:
# Try finding either an ampersand or a semicolon after this
# position.
sep_pos = data.find(b'&', i)
if sep_pos == -1:
sep_pos = data.find(b';', i)
# If we found it, callback this bit as data and then go back
# to expecting to find a field.
if sep_pos != -1:
self.callback('field_data', data, i, sep_pos)
self.callback('field_end')
# Note that we go to the seperator, which brings us to the
# "before field" state. This allows us to properly emit
# "field_start" events only when we actually have data for
# a field of some sort.
i = sep_pos - 1
state = STATE_BEFORE_FIELD
# Otherwise, emit the rest as data and finish.
else:
self.callback('field_data', data, i, length)
i = length
else: # pragma: no cover (error case)
msg = "Reached an unknown state %d at %d" % (state, i)
self.logger.warning(msg)
e = QuerystringParseError(msg)
e.offset = i
raise e
i += 1
self.state = state
self._found_sep = found_sep
return len(data)
def finalize(self):
"""Finalize this parser, which signals to that we are finished parsing,
if we're still in the middle of a field, an on_field_end callback, and
then the on_end callback.
"""
# If we're currently in the middle of a field, we finish it.
if self.state == STATE_FIELD_DATA:
self.callback('field_end')
self.callback('end')
def __repr__(self):
return "%s(keep_blank_values=%r, strict_parsing=%r, max_size=%r)" % (
self.__class__.__name__,
self.keep_blank_values, self.strict_parsing, self.max_size
)
class MultipartParser(BaseParser):
"""This class is a streaming multipart/form-data parser.
.. list-table::
:widths: 15 10 30
:header-rows: 1
* - Callback Name
- Parameters
- Description
* - on_part_begin
- None
- Called when a new part of the multipart message is encountered.
* - on_part_data
- data, start, end
- Called when a portion of a part's data is encountered.
* - on_part_end
- None
- Called when the end of a part is reached.
* - on_header_begin
- None
- Called when we've found a new header in a part of a multipart
message
* - on_header_field
- data, start, end
- Called each time an additional portion of a header is read (i.e. the
part of the header that is before the colon; the "Foo" in
"Foo: Bar").
* - on_header_value
- data, start, end
- Called when we get data for a header.
* - on_header_end
- None
- Called when the current header is finished - i.e. we've reached the
newline at the end of the header.
* - on_headers_finished
- None
- Called when all headers are finished, and before the part data
starts.
* - on_end
- None
- Called when the parser is finished parsing all data.