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|
019| parts = text.partition(': ')
020| if parts[1] != ': ':
021| ValueError(f'Invalid MIME Header (no ": "): "{text}"')
022|
023|
024| subparts = parts[2].split('; ')
025| value = subparts[0]
026|
027| fields = {}
028| for subp in subparts[1:]:
029|
030| key,val = subp.split('=', maxsplit=1)
031|
032| fields[key] = val.strip('"')
033|
034|
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 = {}
057| parthdrs = {}
058| content = []
059| buf = []
060| state = 'prefix'
061| boundary = None
062|
063|
064| ix = content_type.index('boundary=') + len('boundary=')
065| boundary = content_type[ix:].lstrip('-')
066| Log.debug(f'Boundary: "{boundary}"')
067|
068|
069| for bx in byte_string:
070| Log.trace(f'{state}: ({bx}) buflen={len(buf)}')
071|
072| if state == 'prefix':
073|
074| if bx == DASH:
075| buf.append(bx)
076| continue
077|
078| if len(buf) < 6:
079| raise SyntaxError(f'Expected six hyphens, not {len(buf)}.')
080|
081| buf = [bx]
082| state = 'sep'
083| continue
084|
085| if state == 'sep':
086|
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|
096| if bx == CR:
097| continue
098|
099| buf.append(bx)
100| continue
101|
102| if state == 'part.start':
103|
104| if bx == EOL:
105|
106| Log.debug('Content')
107| content = []
108| state = 'part.data'
109| continue
110|
111| if bx == CR:
112| continue
113|
114| buf = [bx]
115| state = 'part.hdr'
116| continue
117|
118| if state == 'part.hdr':
119|
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|
129| if bx == CR:
130| continue
131|
132| buf.append(bx)
133| continue
134|
135| if state == 'part.data':
136|
137| if bx == DASH:
138| buf = [bx]
139| state = 'test.prefix'
140| continue
141|
142| content.append(bx)
143| continue
144|
145| if state == 'test.prefix':
146|
147| if bx != DASH:
148|
149| if len(buf) != 6:
150|
151| content.extend(buf)
152| content.append(bx)
153| state = 'part.data'
154| continue
155|
156| buf = [bx]
157| state = 'test.sep'
158| continue
159|
160| buf.append(bx)
161| continue
162|
163| if state == 'test.sep':
164|
165| if bx == EOL:
166| txt = (''.join(chr(c) for c in buf)).strip()
167| if txt != boundary:
168|
169| content.extend(buf)
170| content.append(bx)
171| state = 'part.data'
172| continue
173|
174| cdisp = parthdrs['content-disposition']
175| name = cdisp.fields['name']
176|
177| form[name] = bytes(content[0:-2])
178|
179| form[f'{name}.disp'] = cdisp
180|
181| if 'content-type' in parthdrs:
182|
183| form[f'{name}.type'] = parthdrs['content-type']
184|
185| buf = []
186| parthdrs = {}
187| state = 'part.start'
188| continue
189|
190| buf.append(bx)
191| continue
192|
193| Log.debug()
194|
195|
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|
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|