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