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