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