]> git.phdru.name Git - mimedecode.git/blob - mimedecode.py
Cleanup: Fix flake8 E128 continuation line under-indented for visual indent
[mimedecode.git] / mimedecode.py
1 #! /usr/bin/env python
2 """Decode MIME message"""
3
4 import sys, os
5 import subprocess
6 from mimedecode_version import __version__, \
7     __author__, __copyright__, __license__
8 if sys.version_info[0] >= 3:
9     # Replace email.message._formatparam with _formatparam from Python 2.7
10     # to avoid re-encoding non-ascii params.
11     import formatparam_27
12
13 me = os.path.basename(sys.argv[0])
14
15
16 def version(exit=1):
17     sys.stdout.write("""\
18 Broytman mimedecode.py version %s, %s
19 """ % (__version__, __copyright__))
20     if exit: sys.exit(0)
21
22 def usage(code=0, errormsg=''):
23     version(0)
24     sys.stdout.write("""\
25 Usage: %s [-h|--help] [-V|--version] [-cCDP] [-H|--host=hostname] [-f charset] [-d header1[,h2,...]|*[,-h1,...]] [-p header1[,h2,h3,...]:param1[,p2,p3,...]] [-r header1[,h2,...]|*[,-h1,...]] [-R header1[,h2,h3,...]:param1[,p2,p3,...]] [--set-header header:value] [--set-param header:param=value] [-Bbeit mask] [--save-headers|body|message mask] [-O dest_dir] [-o output_file] [input_file [output_file]]
26 """ % me)
27     if errormsg:
28         sys.stderr.write(errormsg + os.linesep)
29     sys.exit(code)
30
31
32 def output_headers(msg):
33     unix_from = msg.get_unixfrom()
34     if unix_from:
35         output(unix_from)
36         output(os.linesep)
37     for key, value in msg.items():
38         output(key)
39         output(": ")
40         value = value.split(';', 1)
41         output(value[0])
42         if len(value) == 2:
43             output(";")
44             output(_decode_header(value[1], strip=False))
45         output(os.linesep)
46     output(os.linesep) # End of headers
47
48
49 def recode_if_needed(s, charset):
50     if bytes is str: # Python2
51         if isinstance(s, bytes) and \
52                 charset and charset.lower() != g.default_encoding:
53             s = s.decode(charset, "replace").\
54                 encode(g.default_encoding, "replace")
55     else: # Python3
56         if isinstance(s, bytes):
57             s = s.decode(charset, "replace")
58     return s
59
60
61 def _decode_header(s, strip=True):
62     """Return a decoded string according to RFC 2047.
63     NOTE: This is almost the same as email.Utils.decode.
64     """
65     import email.header
66
67     L = email.header.decode_header(s)
68     if not isinstance(L, list):
69         # s wasn't decoded
70         return s
71
72     rtn = []
73     for atom, charset in L:
74         atom = recode_if_needed(atom, charset or g.default_encoding)
75         if strip:
76             atom = atom.strip()
77         rtn.append(atom)
78
79     # Now that we've decoded everything, we just need to join all the parts
80     # together into the final string.
81     return ' '.join(rtn)
82
83 def decode_header(msg, header):
84     "Decode mail header (if exists) and put it back, if it was encoded"
85
86     if header in msg:
87         value = msg[header]
88         new_value = _decode_header(value)
89         if new_value != value: # do not bother to touch msg if not changed
90             set_header(msg, header, new_value)
91
92
93 def decode_header_param(msg, header, param):
94     "Decode mail header's parameter (if exists) and put it back, if it was encoded"
95
96     if header in msg:
97         value = msg.get_param(param, header=header)
98         if value:
99             if isinstance(value, tuple):
100                 new_value = recode_if_needed(value[2], value[0])
101             else:
102                 new_value = _decode_header(value)
103             if new_value != value: # do not bother to touch msg if not changed
104                 msg.set_param(param, new_value, header)
105
106
107 def _get_exceptions(list):
108     return [x[1:].lower() for x in list[1:] if x[0]=='-']
109
110 def _decode_headers_params(msg, header, decode_all_params, param_list):
111     if decode_all_params:
112         params = msg.get_params(header=header)
113         if params:
114             for param, value in params:
115                 if param not in param_list:
116                     decode_header_param(msg, header, param)
117     else:
118         for param in param_list:
119             decode_header_param(msg, header, param)
120
121 def _remove_headers_params(msg, header, remove_all_params, param_list):
122     if remove_all_params:
123         params = msg.get_params(header=header)
124         if params:
125             if param_list:
126                 for param, value in params:
127                     if param not in param_list:
128                         msg.del_param(param, header)
129             else:
130                 value = msg[header]
131                 if value is None: # No such header
132                     return
133                 if ';' not in value: # There are no parameters
134                     return
135                 del msg[header] # Delete all such headers
136                 # Get the value without parameters and set it back
137                 msg[header] = value.split(';')[0].strip()
138     else:
139         for param in param_list:
140             msg.del_param(param, header)
141
142 def decode_headers(msg):
143     "Decode message headers according to global options"
144
145     for header_list in g.remove_headers:
146         header_list = header_list.split(',')
147         if header_list[0] == '*': # Remove all headers except listed
148             header_list = _get_exceptions(header_list)
149             for header in msg.keys():
150                 if header.lower() not in header_list:
151                     del msg[header]
152         else: # Remove listed headers
153             for header in header_list:
154                 del msg[header]
155
156     for header_list, param_list in g.remove_headers_params:
157         header_list = header_list.split(',')
158         param_list = param_list.split(',')
159         remove_all_params = param_list[0] == '*' # Remove all params except listed
160         if remove_all_params:
161             param_list = _get_exceptions(param_list)
162         if header_list[0] == '*': # Remove for all headers except listed
163             header_list = _get_exceptions(header_list)
164             for header in msg.keys():
165                 if header.lower() not in header_list:
166                     _remove_headers_params(msg, header, remove_all_params, param_list)
167         else: # Decode for listed headers
168             for header in header_list:
169                 _remove_headers_params(msg, header, remove_all_params, param_list)
170
171     for header_list in g.decode_headers:
172         header_list = header_list.split(',')
173         if header_list[0] == '*': # Decode all headers except listed
174             header_list = _get_exceptions(header_list)
175             for header in msg.keys():
176                 if header.lower() not in header_list:
177                     decode_header(msg, header)
178         else: # Decode listed headers
179             for header in header_list:
180                 decode_header(msg, header)
181
182     for header_list, param_list in g.decode_header_params:
183         header_list = header_list.split(',')
184         param_list = param_list.split(',')
185         decode_all_params = param_list[0] == '*' # Decode all params except listed
186         if decode_all_params:
187             param_list = _get_exceptions(param_list)
188         if header_list[0] == '*': # Decode for all headers except listed
189             header_list = _get_exceptions(header_list)
190             for header in msg.keys():
191                 if header.lower() not in header_list:
192                     _decode_headers_params(msg, header, decode_all_params, param_list)
193         else: # Decode for listed headers
194             for header in header_list:
195                 _decode_headers_params(msg, header, decode_all_params, param_list)
196
197
198 def set_header(msg, header, value):
199     "Replace header"
200
201     if header in msg:
202         msg.replace_header(header, value)
203     else:
204         msg[header] = value
205
206
207 def set_content_type(msg, newtype, charset=None):
208     msg.set_type(newtype)
209
210     if charset:
211         msg.set_param("charset", charset, "Content-Type")
212
213
214 caps = None # Globally stored mailcap database; initialized only if needed
215
216 def decode_body(msg, s):
217     "Decode body to plain text using first copiousoutput filter from mailcap"
218
219     import mailcap, tempfile
220
221     global caps
222     if caps is None:
223         caps = mailcap.getcaps()
224
225     content_type = msg.get_content_type()
226     if content_type.startswith('text/'):
227         charset = msg.get_content_charset()
228     else:
229         charset = None
230     filename = tempfile.mktemp()
231     command = None
232
233     entries = mailcap.lookup(caps, content_type, "view")
234     for entry in entries:
235         if 'copiousoutput' in entry:
236             if 'test' in entry:
237                 test = mailcap.subst(entry['test'], content_type, filename)
238                 if test and os.system(test) != 0:
239                     continue
240             command = mailcap.subst(entry["view"], content_type, filename)
241             break
242
243     if not command:
244         return s
245
246     outfile = open(filename, 'wb')
247     if charset and bytes is not str and isinstance(s, bytes):  # Python3
248         s = s.decode(charset, "replace")
249     if not isinstance(s, bytes):
250         s = s.encode(g.default_encoding, "replace")
251     outfile.write(s)
252     outfile.close()
253
254     pipe = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
255     new_s = pipe.stdout.read()
256     pipe.stdout.close()
257     if pipe.wait() == 0: # result=0, Ok
258         s = new_s
259         if bytes is not str and isinstance(s, bytes):  # Python3
260             s = s.decode(g.default_encoding, "replace")
261         if charset and not isinstance(s, bytes):
262             s = s.encode(charset, "replace")
263         set_content_type(msg, "text/plain")
264         msg["X-MIME-Autoconverted"] = "from %s to text/plain by %s id %s" % (content_type, g.host_name, command.split()[0])
265     else:
266         msg["X-MIME-Autoconverted"] = "failed conversion from %s to text/plain by %s id %s" % (content_type, g.host_name, command.split()[0])
267     os.remove(filename)
268
269     return s
270
271
272 def recode_charset(msg, s):
273     "Recode charset of the message to the default charset"
274
275     save_charset = charset = msg.get_content_charset()
276     if charset and charset.lower() != g.default_encoding:
277         s = recode_if_needed(s, charset)
278         content_type = msg.get_content_type()
279         set_content_type(msg, content_type, g.default_encoding)
280         msg["X-MIME-Autoconverted"] = "from %s to %s by %s id %s" % (save_charset, g.default_encoding, g.host_name, me)
281     return s
282
283
284 def totext(msg, instring):
285     "Convert instring content to text"
286
287     # Decode body and recode charset
288     s = decode_body(msg, instring)
289     if g.recode_charset:
290         s = recode_charset(msg, s)
291
292     output_headers(msg)
293     output(s)
294     return s
295
296
297 mimetypes = None
298
299 def _guess_extension(ctype):
300     global mimetypes
301     if mimetypes is None:
302         import mimetypes
303         mimetypes.init()
304         user_mime_type = os.path.expanduser('~/.mime.types')
305         if os.path.exists(user_mime_type):
306             mimetypes._db.read(user_mime_type)
307     return mimetypes.guess_extension(ctype)
308
309 def _save_message(msg, outstring, save_headers=False, save_body=False):
310     for header, param in (
311         ("Content-Disposition", "filename"),
312         ("Content-Type", "name"),
313     ):
314         fname = msg.get_param(param, header=header)
315         if fname:
316             if isinstance(fname, tuple):
317                 fname = fname[2] # Do not recode if it isn't recoded yet
318             try:
319                     for forbidden in chr(0), '/', '\\':
320                         if forbidden in fname:
321                             raise ValueError
322             except ValueError:
323                 continue
324             fname = '-' + fname
325             break
326     else:
327         fname = ''
328     g.save_counter += 1
329     fname = str(g.save_counter) + fname
330     if '.' not in fname:
331         ext = _guess_extension(msg.get_content_type())
332         if ext: fname += ext
333
334     global output
335     save_output = output
336     outfile = open_output_file(fname)
337     def _output_bytes(s):
338         if not isinstance(s, bytes):
339             s = s.encode(g.default_encoding, "replace")
340         outfile.write(s)
341     output = _output_bytes
342     if save_headers:
343         output_headers(msg)
344     if save_body:
345         output(outstring)
346     outfile.close()
347     output = save_output
348
349
350 def decode_part(msg):
351     "Decode one part of the message"
352
353     decode_headers(msg)
354
355     # Test all mask lists and find what to do with this content type
356     masks = []
357     ctype = msg.get_content_type()
358     if ctype:
359         masks.append(ctype)
360         mtype = ctype.split('/')[0]
361         masks.append(mtype + '/*')
362     masks.append('*/*')
363
364     left_binary = False
365     for content_type in masks:
366         if content_type in g.totext_mask or \
367            content_type in g.decoded_binary_mask:
368             break
369         elif content_type in g.binary_mask:
370             left_binary = True
371             break
372         elif content_type in g.fully_ignore_mask:
373             return
374
375     encoding = msg["Content-Transfer-Encoding"]
376     if left_binary or encoding in (None, '', '7bit', '8bit', 'binary'):
377         outstring = msg.get_payload()
378     else: # Decode from transfer ecoding to text or binary form
379         outstring = msg.get_payload(decode=1)
380         set_header(msg, "Content-Transfer-Encoding", "8bit")
381         msg["X-MIME-Autoconverted"] = "from %s to 8bit by %s id %s" % (encoding, g.host_name, me)
382
383     for content_type in masks:
384         if content_type in g.totext_mask:
385             outstring = totext(msg, outstring)
386             break
387         elif content_type in g.binary_mask or \
388                 content_type in g.decoded_binary_mask:
389             output_headers(msg)
390             output(outstring)
391             break
392         elif content_type in g.ignore_mask:
393             output_headers(msg)
394             output("%sMessage body of type %s skipped.%s" % (os.linesep, ctype, os.linesep))
395             break
396         elif content_type in g.error_mask:
397             break
398     else:
399         # Neither content type nor masks were listed - decode by default
400         outstring = totext(msg, outstring)
401
402     for content_type in masks:
403         if content_type in g.save_headers_mask:
404             _save_message(msg, outstring, save_headers=True, save_body=False)
405         if content_type in g.save_body_mask:
406             _save_message(msg, outstring, save_headers=False, save_body=True)
407         if content_type in g.save_message_mask:
408             _save_message(msg, outstring, save_headers=True, save_body=True)
409
410     for content_type in masks:
411         if content_type in g.error_mask:
412             raise ValueError("content type %s prohibited" % ctype)
413
414 def decode_multipart(msg):
415     "Decode multipart"
416
417     decode_headers(msg)
418     boundary = msg.get_boundary()
419
420     masks = []
421     ctype = msg.get_content_type()
422     if ctype:
423         masks.append(ctype)
424         mtype = ctype.split('/')[0]
425         masks.append(mtype + '/*')
426     masks.append('*/*')
427
428     for content_type in masks:
429         if content_type in g.fully_ignore_mask:
430             return
431         elif content_type in g.ignore_mask:
432             output_headers(msg)
433             output("%sMessage body of type %s skipped.%s" % (os.linesep, ctype, os.linesep))
434             if boundary:
435                 output("%s--%s--%s" % (os.linesep, boundary, os.linesep))
436             return
437
438     for content_type in masks:
439         if content_type in g.save_body_mask or \
440                 content_type in g.save_message_mask:
441             _out_l = []
442             first_subpart = True
443             for subpart in msg.get_payload():
444                 if first_subpart:
445                     first_subpart = False
446                 else:
447                     _out_l.append(os.linesep)
448                 _out_l.append("--%s%s" % (boundary, os.linesep))
449                 _out_l.append(subpart.as_string())
450             _out_l.append("%s--%s--%s" % (os.linesep, boundary, os.linesep))
451             outstring = ''.join(_out_l)
452             break
453     else:
454         outstring = None
455
456     for content_type in masks:
457         if content_type in g.save_headers_mask:
458             _save_message(msg, outstring, save_headers=True, save_body=False)
459         if content_type in g.save_body_mask:
460             _save_message(msg, outstring, save_headers=False, save_body=True)
461         if content_type in g.save_message_mask:
462             _save_message(msg, outstring, save_headers=True, save_body=True)
463
464     for content_type in masks:
465         if content_type in g.error_mask:
466             raise ValueError("content type %s prohibited" % ctype)
467
468     output_headers(msg)
469
470     if msg.preamble: # Preserve the first part, it is probably not a RFC822-message
471         output(msg.preamble) # Usually it is just a few lines of text (MIME warning)
472     if msg.preamble is not None:
473         output(os.linesep)
474
475     first_subpart = True
476     for subpart in msg.get_payload():
477         if boundary:
478             if first_subpart:
479                 first_subpart = False
480             else:
481                 output(os.linesep)
482             output("--%s%s" % (boundary, os.linesep))
483
484         # Recursively decode all parts of the subpart
485         decode_message(subpart)
486
487     if boundary:
488         output("%s--%s--%s" % (os.linesep, boundary, os.linesep))
489
490     if msg.epilogue:
491         output(msg.epilogue)
492
493
494 def decode_message(msg):
495     "Decode message"
496
497     if msg.is_multipart():
498         decode_multipart(msg)
499     elif len(msg): # Simple one-part message (there are headers) - decode it
500         decode_part(msg)
501     else: # Not a message, just text - copy it literally
502         output(msg.as_string())
503
504
505 def open_output_file(filename):
506     fullpath = os.path.abspath(os.path.join(g.destination_dir, filename))
507     full_dir = os.path.dirname(fullpath)
508     create = not os.path.isdir(full_dir)
509     if create:
510         os.makedirs(full_dir)
511     try:
512         return open(fullpath, 'wb')
513     except:
514         if create:
515             os.removedirs(full_dir)
516
517
518 class GlobalOptions:
519     from m_lib.defenc import default_encoding
520     recode_charset = 1 # recode charset of message body
521
522     host_name = None
523
524     # A list of headers to decode
525     decode_headers = ["From", "To", "Cc", "Reply-To", "Mail-Followup-To",
526                       "Subject"]
527
528     # A list of headers parameters to decode
529     decode_header_params = [
530         ("Content-Type", "name"),
531         ("Content-Disposition", "filename"),
532     ]
533
534     # A list of headers to remove
535     remove_headers = []
536     # A list of headers parameters to remove
537     remove_headers_params = []
538
539     # A list of header/value pairs to set
540     set_header_value = []
541     # A list of header/parameter/value triples to set
542     set_header_param = []
543
544     totext_mask = [] # A list of content-types to decode
545     binary_mask = [] # A list of content-types to pass through
546     decoded_binary_mask = [] # A list of content-types to pass through (content-transfer-decoded)
547     ignore_mask = [] # Ignore (do not decode and do not include into output) but output a warning instead of the body
548     fully_ignore_mask = [] # Completely ignore - no headers, no body, no warning
549     error_mask = []  # Raise error if encounter one of these
550
551     save_counter = 0
552     save_headers_mask = []
553     save_body_mask = []
554     save_message_mask = []
555
556     input_filename = None
557     output_filename = None
558     destination_dir = os.curdir
559
560 g = GlobalOptions
561
562
563 def get_opts():
564     from getopt import getopt, GetoptError
565
566     try:
567         options, arguments = getopt(
568             sys.argv[1:],
569             'hVcCDPH:f:d:p:r:R:b:B:e:I:i:t:O:o:',
570             ['help', 'version', 'host=',
571              'save-headers=', 'save-body=', 'save-message=',
572              'set-header=', 'set-param='])
573     except GetoptError:
574         usage(1)
575
576     for option, value in options:
577         if option in ('-h', '--help'):
578             usage()
579         elif option in ('-V', '--version'):
580             version()
581         elif option == '-c':
582             g.recode_charset = 1
583         elif option == '-C':
584             g.recode_charset = 0
585         elif option in ('-H', '--host'):
586             g.host_name = value
587         elif option == '-f':
588             g.default_encoding = value
589         elif option == '-d':
590             if value.startswith('*'):
591                 g.decode_headers = []
592             g.decode_headers.append(value)
593         elif option == '-D':
594             g.decode_headers = []
595         elif option == '-p':
596             g.decode_header_params.append(value.split(':', 1))
597         elif option == '-P':
598             g.decode_header_params = []
599         elif option == '-r':
600             g.remove_headers.append(value)
601         elif option == '-R':
602             g.remove_headers_params.append(value.split(':', 1))
603         elif option == '--set-header':
604             g.set_header_value.append(value.split(':', 1))
605         elif option == '--set-param':
606             header, value = value.split(':', 1)
607             if '=' in value:
608                 param, value = value.split('=', 1)
609             else:
610                 param, value = value.split(':', 1)
611             g.set_header_param.append((header, param, value))
612         elif option == '-t':
613             g.totext_mask.append(value)
614         elif option == '-B':
615             g.binary_mask.append(value)
616         elif option == '-b':
617             g.decoded_binary_mask.append(value)
618         elif option == '-I':
619             g.fully_ignore_mask.append(value)
620         elif option == '-i':
621             g.ignore_mask.append(value)
622         elif option == '-e':
623             g.error_mask.append(value)
624         elif option == '--save-headers':
625             g.save_headers_mask.append(value)
626         elif option == '--save-body':
627             g.save_body_mask.append(value)
628         elif option == '--save-message':
629             g.save_message_mask.append(value)
630         elif option == '-O':
631             g.destination_dir = value
632         elif option == '-o':
633             g.output_filename = value
634         else:
635             usage(1)
636
637     return arguments
638
639
640 if __name__ == "__main__":
641     arguments = get_opts()
642
643     la = len(arguments)
644     if la == 0:
645         g.input_filename = '-'
646         infile = sys.stdin
647         if g.output_filename:
648             outfile = open_output_file(g.output_filename)
649         else:
650             g.output_filename = '-'
651             outfile = sys.stdout
652     elif la in (1, 2):
653         if (arguments[0] == '-'):
654             g.input_filename = '-'
655             infile = sys.stdin
656         else:
657             g.input_filename = arguments[0]
658             infile = open(arguments[0], 'r')
659         if la == 1:
660             if g.output_filename:
661                 outfile = open_output_file(g.output_filename)
662             else:
663                 g.output_filename = '-'
664                 outfile = sys.stdout
665         elif la == 2:
666             if g.output_filename:
667                 usage(1, 'Too many output filenames')
668             if (arguments[1] == '-'):
669                 g.output_filename = '-'
670                 outfile = sys.stdout
671             else:
672                 g.output_filename = arguments[1]
673                 outfile = open_output_file(g.output_filename)
674     else:
675         usage(1, 'Too many arguments')
676
677     if (infile is sys.stdin) and sys.stdin.isatty():
678         if (outfile is sys.stdout) and sys.stdout.isatty():
679             usage()
680         usage(1, 'Filtering from console is forbidden')
681
682     if not g.host_name:
683         import socket
684         g.host_name = socket.gethostname()
685
686     g.outfile = outfile
687     if hasattr(outfile, 'buffer'):
688         def output_bytes(s):
689             if not isinstance(s, bytes):
690                 s = s.encode(g.default_encoding, "replace")
691             outfile.buffer.write(s)
692         output = output_bytes
693     else:
694         output = outfile.write
695
696     import email
697     msg = email.message_from_file(infile)
698
699     for header, value in g.set_header_value:
700         set_header(msg, header, value)
701
702     for header, param, value in g.set_header_param:
703         if header in msg:
704             msg.set_param(param, value, header)
705
706     try:
707         decode_message(msg)
708     finally:
709         infile.close()
710         outfile.close()