multipart.html


001| '''Parse MIME Multipart text.
001| 
001| Classes:
001|     MimeHeader (tuple)
001| 
001| Functions:
001|     parse_multipart_form
001| 
001| '''

002| ####################################################################################################
003| from goodies import typename
004| from logger import logger
005| ####################################################################################################
006| Log = logger('MultiPart')
007| 
008| EOL  = ord('\n')
009| CR   = ord('\r')
010| DASH = ord('-')
011| 
012| #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
013| class MimeHeader (tuple):
014|     '''\
014| MIME Header class. Parses text to a defined tuple.
014| 
014| Expected text has the syntax:
014|     <name>: <text> [; name=value [; ...]]
014| 
014| Created tuple is:
014|     (name, text, fields)
014| 
014| Properties:
014|     name        -field name
014|     text        -field text
014|     fields      -dictionary of name:value pairs
014| 
014| Methods:
014|     str(obj)    -printable version
014|     repr(obj)   -debugging version
014| '''

015|     def __new__ (cls, text:str):
016|         '''New MimeHeader instance.'''
017| 
018|         # Split text into name and value parts...
019|         parts = text.partition(': ')
020|         if parts[1] != ': ':
021|             ValueError(f'Invalid MIME Header (no ": "): "{text}"')
022| 
023|         # Split the value into fields...
024|         subparts = parts[2].split('; ')
025|         value = subparts[0]
026| 
027|         fields = {}
028|         for subp in subparts[1:]:
029|             # Split field into name and value...
030|             key,val = subp.split('=', maxsplit=1)
031|             # Add field; remove any surrounding double-quotes...
032|             fields[key] = val.strip('"')
033| 
034|         # Delegate creating new instance to tuple...
035|         return super().__new__(cls, (parts[0], value, fields))
036| 
037|     @property
038|     def name (self): return self[0]
039| 
040|     @property
041|     def text (self): return self[1]
042| 
043|     @property
044|     def fields (self): return self[2]
045| 
046|     def __str__ (self):
047|         return f'{self.name}: {self.text}'
048| 
049|     def __repr__ (self):
050|         return f'<{typename(self)} @{id(self):08x}>'
051| 
052| 
053| ##================================================================================================##
054| def parse_multipart_form (content_type:str, byte_string:bytes) -> tuple:
055|     '''\
055| Parse Multipart Form Data.
055| 
055| Arguments:
055|     content_type    -content header text
055|     byte_string     -form data bytes
055| 
055| Returns:
055|     tuple: (form, filename, filetype, filedata)
055| 
055|     Note: the last three field will be None if no file data.
055| '''

056|     form = {}               # form data to be returned
057|     parthdrs = {}           # temp dictionary for part headers
058|     content = []            # buffer for building file content
059|     buf = []                # temp buff for building strings
060|     state = 'prefix'        # current state
061|     boundary = None         # part separator string
062| 
063|     # Parse the content-type header to get the multipart boundary...
064|     ix = content_type.index('boundary=') + len('boundary=')
065|     boundary = content_type[ix:].lstrip('-')
066|     Log.debug(f'Boundary: "{boundary}"')
067| 
068|     # Iterate over the bytes of the data...
069|     for bx in byte_string:
070|         Log.trace(f'{state}: ({bx}) buflen={len(buf)}')
071| 
072|         if state == 'prefix':
073|             # Accumulate dashes...
074|             if bx == DASH:
075|                 buf.append(bx)
076|                 continue
077|             # Not a dash; separator text begins...
078|             if len(buf) < 6:
079|                 raise SyntaxError(f'Expected six hyphens, not {len(buf)}.')
080|             # Add first separator character to buffer...
081|             buf = [bx]
082|             state = 'sep'
083|             continue
084| 
085|         if state == 'sep':
086|             # End of separator...
087|             if bx == EOL:
088|                 sep_str = ''.join(chr(b) for b in buf)
089|                 if not sep_str.startswith(boundary):
090|                     raise SyntaxError(f'Invalid Separator: "{sep_str}"')
091|                 buf = []
092|                 parthdrs = {}
093|                 state = 'part.start'
094|                 continue
095|             # Ignore CR characters...
096|             if bx == CR:
097|                 continue
098|             # Add separator character to buffer...
099|             buf.append(bx)
100|             continue
101| 
102|         if state == 'part.start':
103|             # Blank line (instead of header text)...
104|             if bx == EOL:
105|                 # End of part headers...
106|                 Log.debug('Content')
107|                 content = []
108|                 state = 'part.data'
109|                 continue
110|             # Ignore CR characters...
111|             if bx == CR:
112|                 continue
113|             # Add first part header character to buffer...
114|             buf = [bx]
115|             state = 'part.hdr'
116|             continue
117| 
118|         if state == 'part.hdr':
119|             # Handle end of line...
120|             if bx == EOL:
121|                 txt = ''.join(chr(b) for b in buf)
122|                 Log.trace(f'Part-Header: {txt}')
123|                 hdr = MimeHeader(txt)
124|                 Log.debug(hdr)
125|                 parthdrs[hdr.name.lower()] = hdr
126|                 state = 'part.start'
127|                 continue
128|             # Ignore CR characters...
129|             if bx == CR:
130|                 continue
131|             # Add part header character to buffer...
132|             buf.append(bx)
133|             continue
134| 
135|         if state == 'part.data':
136|             # A dash might mean a separator...
137|             if bx == DASH:
138|                 buf = [bx]
139|                 state = 'test.prefix'
140|                 continue
141|             # Add content byte to buffer...
142|             content.append(bx)
143|             continue
144| 
145|         if state == 'test.prefix':
146|             # Not a dash; start of separator...
147|             if bx != DASH:
148|                 # Not a separator; add to content and resume...
149|                 if len(buf) != 6:
150|                     # Not a separator...
151|                     content.extend(buf)
152|                     content.append(bx)
153|                     state = 'part.data'
154|                     continue
155|                 # Got 6 dashes; might be a separator...
156|                 buf = [bx]
157|                 state = 'test.sep'
158|                 continue
159|             # Add character to possible prefix string...
160|             buf.append(bx)
161|             continue
162| 
163|         if state == 'test.sep':
164|             # End of line; test separator...
165|             if bx == EOL:
166|                 txt = (''.join(chr(c) for c in buf)).strip()
167|                 if txt != boundary:
168|                     # Not a separator...
169|                     content.extend(buf)
170|                     content.append(bx)
171|                     state = 'part.data'
172|                     continue
173|                 # It is a separator; get disposition header...
174|                 cdisp = parthdrs['content-disposition']
175|                 name = cdisp.fields['name']
176|                 # Add file content (bytes) to form (strip trailing CR-LF)...
177|                 form[name] = bytes(content[0:-2])
178|                 # Add the disposition header...
179|                 form[f'{name}.disp'] = cdisp
180|                 # If content-type header provided...
181|                 if 'content-type' in parthdrs:
182|                     # Add to form...
183|                     form[f'{name}.type'] = parthdrs['content-type']
184|                 # Get ready for next part...
185|                 buf = []
186|                 parthdrs = {}
187|                 state = 'part.start'
188|                 continue
189|             # Add to separator string...
190|             buf.append(bx)
191|             continue
192| 
193|     Log.debug()
194| 
195|     # Extract the filename, filetype, and file data for convenience...
196|     filedata, filename, filetype = None,None,None
197|     for name in form:
198|         if name == 'fn':
199|             filedata = form['fn']
200|             filetype = form['fn.type'].text
201|             filename = form['fn.disp'].fields['filename']
202|             Log.info(f'filename: {filename}')
203|             Log.info(f'filetype: {filetype}')
204|             Log.info(f'filesize: {len(filedata)}')
205|             if filetype.startswith('text'):
206|                 filedata = str(filedata, encoding='utf8')
207|             continue
208| 
209|         # Also convert simple fields from bytes to strings...
210|         if '.' not in name:
211|             txt = form[name]
212|             if isinstance(txt,bytes):
213|                 form[name] = str(txt, encoding='utf8')
214| 
215|     form['fn.name'] = filename
216|     return (form, filename, filetype, filedata)
217| 
218| 
219| ####################################################################################################
220| '''eof'''
221|