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