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