]> git.phdru.name Git - mimedecode.git/blob - mimedecode.py
Docs: TODO: setup.py: PyPy
[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__, __copyright__
9
10 if sys.version_info[0] >= 3:
11     # Replace email.message._formatparam with _formatparam from Python 2.7
12     # to avoid re-encoding non-ascii params.
13     import formatparam_27  # noqa: F401: Imported for its side effect
14
15 me = os.path.basename(sys.argv[0])
16
17
18 def version(exit=1):
19     sys.stdout.write("""\
20 Broytman mimedecode.py version %s, %s
21 """ % (__version__, __copyright__))
22     if exit:
23         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:
360             fname += ext
361
362     global output
363     save_output = output
364     outfile = open_output_file(fname)
365
366     def _output_bytes(s):
367         if not isinstance(s, bytes):
368             s = s.encode(g.default_encoding, "replace")
369         outfile.write(s)
370
371     output = _output_bytes
372     if save_headers:
373         output_headers(msg)
374     if save_body:
375         output(outstring)
376     outfile.close()
377     output = save_output
378
379
380 def decode_part(msg):
381     "Decode one part of the message"
382
383     decode_headers(msg)
384
385     # Test all mask lists and find what to do with this content type
386     masks = []
387     ctype = msg.get_content_type()
388     if ctype:
389         masks.append(ctype)
390         mtype = ctype.split('/')[0]
391         masks.append(mtype + '/*')
392     masks.append('*/*')
393
394     left_binary = False
395     for content_type in masks:
396         if content_type in g.totext_mask or \
397            content_type in g.decoded_binary_mask:
398             break
399         elif content_type in g.binary_mask:
400             left_binary = True
401             break
402         elif content_type in g.fully_ignore_mask:
403             return
404
405     encoding = msg["Content-Transfer-Encoding"]
406     if left_binary or encoding in (None, '', '7bit', '8bit', 'binary'):
407         outstring = msg.get_payload()
408     else:  # Decode from transfer ecoding to text or binary form
409         outstring = msg.get_payload(decode=1)
410         set_header(msg, "Content-Transfer-Encoding", "8bit")
411         msg["X-MIME-Autoconverted"] = \
412             "from %s to 8bit by %s id %s" % (encoding, g.host_name, me)
413
414     for content_type in masks:
415         if content_type in g.totext_mask:
416             outstring = totext(msg, outstring)
417             break
418         elif content_type in g.binary_mask or \
419                 content_type in g.decoded_binary_mask:
420             output_headers(msg)
421             output(outstring)
422             break
423         elif content_type in g.ignore_mask:
424             output_headers(msg)
425             output("%sMessage body of type %s skipped.%s"
426                    % (os.linesep, ctype, os.linesep))
427             break
428         elif content_type in g.error_mask:
429             break
430     else:
431         # Neither content type nor masks were listed - decode by default
432         outstring = totext(msg, outstring)
433
434     for content_type in masks:
435         if content_type in g.save_headers_mask:
436             _save_message(msg, outstring, save_headers=True, save_body=False)
437         if content_type in g.save_body_mask:
438             _save_message(msg, outstring, save_headers=False, save_body=True)
439         if content_type in g.save_message_mask:
440             _save_message(msg, outstring, save_headers=True, save_body=True)
441
442     for content_type in masks:
443         if content_type in g.error_mask:
444             raise ValueError("content type %s prohibited" % ctype)
445
446
447 def decode_multipart(msg):
448     "Decode multipart"
449
450     decode_headers(msg)
451     boundary = msg.get_boundary()
452
453     masks = []
454     ctype = msg.get_content_type()
455     if ctype:
456         masks.append(ctype)
457         mtype = ctype.split('/')[0]
458         masks.append(mtype + '/*')
459     masks.append('*/*')
460
461     for content_type in masks:
462         if content_type in g.fully_ignore_mask:
463             return
464         elif content_type in g.ignore_mask:
465             output_headers(msg)
466             output("%sMessage body of type %s skipped.%s"
467                    % (os.linesep, ctype, os.linesep))
468             if boundary:
469                 output("%s--%s--%s" % (os.linesep, boundary, os.linesep))
470             return
471
472     for content_type in masks:
473         if content_type in g.save_body_mask or \
474                 content_type in g.save_message_mask:
475             _out_l = []
476             first_subpart = True
477             for subpart in msg.get_payload():
478                 if first_subpart:
479                     first_subpart = False
480                 else:
481                     _out_l.append(os.linesep)
482                 _out_l.append("--%s%s" % (boundary, os.linesep))
483                 _out_l.append(subpart.as_string())
484             _out_l.append("%s--%s--%s" % (os.linesep, boundary, os.linesep))
485             outstring = ''.join(_out_l)
486             break
487     else:
488         outstring = None
489
490     for content_type in masks:
491         if content_type in g.save_headers_mask:
492             _save_message(msg, outstring, save_headers=True, save_body=False)
493         if content_type in g.save_body_mask:
494             _save_message(msg, outstring, save_headers=False, save_body=True)
495         if content_type in g.save_message_mask:
496             _save_message(msg, outstring, save_headers=True, save_body=True)
497
498     for content_type in masks:
499         if content_type in g.error_mask:
500             raise ValueError("content type %s prohibited" % ctype)
501
502     output_headers(msg)
503
504     # Preserve the first part, it is probably not a RFC822-message.
505     if msg.preamble:
506         # Usually it is just a few lines of text (MIME warning).
507         output(msg.preamble)
508     if msg.preamble is not None:
509         output(os.linesep)
510
511     first_subpart = True
512     for subpart in msg.get_payload():
513         if boundary:
514             if first_subpart:
515                 first_subpart = False
516             else:
517                 output(os.linesep)
518             output("--%s%s" % (boundary, os.linesep))
519
520         # Recursively decode all parts of the subpart
521         decode_message(subpart)
522
523     if boundary:
524         output("%s--%s--%s" % (os.linesep, boundary, os.linesep))
525
526     if msg.epilogue:
527         output(msg.epilogue)
528
529
530 def decode_message(msg):
531     "Decode message"
532
533     if msg.is_multipart():
534         decode_multipart(msg)
535     elif len(msg):  # Simple one-part message (there are headers) - decode it
536         decode_part(msg)
537     else:  # Not a message, just text - copy it literally
538         output(msg.as_string())
539
540
541 def open_output_file(filename):
542     fullpath = os.path.abspath(os.path.join(g.destination_dir, filename))
543     full_dir = os.path.dirname(fullpath)
544     create = not os.path.isdir(full_dir)
545     if create:
546         os.makedirs(full_dir)
547     try:
548         return open(fullpath, 'wb')
549     except Exception:
550         if create:
551             os.removedirs(full_dir)
552
553
554 class GlobalOptions:
555     from m_lib.defenc import default_encoding
556     recode_charset = 1  # recode charset of message body
557
558     host_name = None
559
560     # A list of headers to decode
561     decode_headers = ["From", "To", "Cc", "Reply-To", "Mail-Followup-To",
562                       "Subject"]
563
564     # A list of headers parameters to decode
565     decode_header_params = [
566         ("Content-Type", "name"),
567         ("Content-Disposition", "filename"),
568     ]
569
570     # A list of headers to remove
571     remove_headers = []
572     # A list of headers parameters to remove
573     remove_headers_params = []
574
575     # A list of header/value pairs to set
576     set_header_value = []
577     # A list of header/parameter/value triples to set
578     set_header_param = []
579
580     totext_mask = []  # A list of content-types to decode
581     binary_mask = []  # A list of content-types to pass through
582     # A list of content-types to pass through (content-transfer-decoded).
583     decoded_binary_mask = []
584     # Ignore (do not decode and do not include into output)
585     # but output a warning instead of the body.
586     ignore_mask = []
587     # Completely ignore - no headers, no body, no warning.
588     fully_ignore_mask = []
589     error_mask = []  # Raise error if encounter one of these
590
591     save_counter = 0
592     save_headers_mask = []
593     save_body_mask = []
594     save_message_mask = []
595
596     input_filename = None
597     output_filename = None
598     destination_dir = os.curdir
599
600
601 g = GlobalOptions
602
603
604 def get_opts():
605     from getopt import getopt, GetoptError
606
607     try:
608         options, arguments = getopt(
609             sys.argv[1:],
610             'hVcCDPH:f:d:p:r:R:b:B:e:I:i:t:O:o:',
611             ['help', 'version', 'host=',
612              'save-headers=', 'save-body=', 'save-message=',
613              'set-header=', 'set-param='])
614     except GetoptError:
615         usage(1)
616
617     for option, value in options:
618         if option in ('-h', '--help'):
619             usage()
620         elif option in ('-V', '--version'):
621             version()
622         elif option == '-c':
623             g.recode_charset = 1
624         elif option == '-C':
625             g.recode_charset = 0
626         elif option in ('-H', '--host'):
627             g.host_name = value
628         elif option == '-f':
629             g.default_encoding = value
630         elif option == '-d':
631             if value.startswith('*'):
632                 g.decode_headers = []
633             g.decode_headers.append(value)
634         elif option == '-D':
635             g.decode_headers = []
636         elif option == '-p':
637             g.decode_header_params.append(value.split(':', 1))
638         elif option == '-P':
639             g.decode_header_params = []
640         elif option == '-r':
641             g.remove_headers.append(value)
642         elif option == '-R':
643             g.remove_headers_params.append(value.split(':', 1))
644         elif option == '--set-header':
645             g.set_header_value.append(value.split(':', 1))
646         elif option == '--set-param':
647             header, value = value.split(':', 1)
648             if '=' in value:
649                 param, value = value.split('=', 1)
650             else:
651                 param, value = value.split(':', 1)
652             g.set_header_param.append((header, param, value))
653         elif option == '-t':
654             g.totext_mask.append(value)
655         elif option == '-B':
656             g.binary_mask.append(value)
657         elif option == '-b':
658             g.decoded_binary_mask.append(value)
659         elif option == '-I':
660             g.fully_ignore_mask.append(value)
661         elif option == '-i':
662             g.ignore_mask.append(value)
663         elif option == '-e':
664             g.error_mask.append(value)
665         elif option == '--save-headers':
666             g.save_headers_mask.append(value)
667         elif option == '--save-body':
668             g.save_body_mask.append(value)
669         elif option == '--save-message':
670             g.save_message_mask.append(value)
671         elif option == '-O':
672             g.destination_dir = value
673         elif option == '-o':
674             g.output_filename = value
675         else:
676             usage(1)
677
678     return arguments
679
680
681 if __name__ == "__main__":
682     arguments = get_opts()
683
684     la = len(arguments)
685     if la == 0:
686         g.input_filename = '-'
687         infile = sys.stdin
688         if g.output_filename:
689             outfile = open_output_file(g.output_filename)
690         else:
691             g.output_filename = '-'
692             outfile = sys.stdout
693     elif la in (1, 2):
694         if (arguments[0] == '-'):
695             g.input_filename = '-'
696             infile = sys.stdin
697         else:
698             g.input_filename = arguments[0]
699             infile = open(arguments[0], 'r')
700         if la == 1:
701             if g.output_filename:
702                 outfile = open_output_file(g.output_filename)
703             else:
704                 g.output_filename = '-'
705                 outfile = sys.stdout
706         elif la == 2:
707             if g.output_filename:
708                 usage(1, 'Too many output filenames')
709             if (arguments[1] == '-'):
710                 g.output_filename = '-'
711                 outfile = sys.stdout
712             else:
713                 g.output_filename = arguments[1]
714                 outfile = open_output_file(g.output_filename)
715     else:
716         usage(1, 'Too many arguments')
717
718     if (infile is sys.stdin) and sys.stdin.isatty():
719         if (outfile is sys.stdout) and sys.stdout.isatty():
720             usage()
721         usage(1, 'Filtering from console is forbidden')
722
723     if not g.host_name:
724         import socket
725         g.host_name = socket.gethostname()
726
727     g.outfile = outfile
728     if hasattr(outfile, 'buffer'):
729         def output_bytes(s):
730             if not isinstance(s, bytes):
731                 s = s.encode(g.default_encoding, "replace")
732             outfile.buffer.write(s)
733         output = output_bytes
734     else:
735         output = outfile.write
736
737     import email
738     msg = email.message_from_file(infile)
739
740     for header, value in g.set_header_value:
741         set_header(msg, header, value)
742
743     for header, param, value in g.set_header_param:
744         if header in msg:
745             msg.set_param(param, value, header)
746
747     try:
748         decode_message(msg)
749     finally:
750         infile.close()
751         outfile.close()