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