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