]> git.phdru.name Git - mimedecode.git/blob - mimedecode.py
Decode parameters on output
[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     filename = tempfile.mktemp()
222     command = None
223
224     entries = mailcap.lookup(caps, content_type, "view")
225     for entry in entries:
226         if 'copiousoutput' in entry:
227             if 'test' in entry:
228                 test = mailcap.subst(entry['test'], content_type, filename)
229                 if test and os.system(test) != 0:
230                     continue
231             command = mailcap.subst(entry["view"], content_type, filename)
232             break
233
234     if not command:
235         return s
236
237     outfile = open(filename, 'wb')
238     if not isinstance(s, bytes):
239         s = s.encode(g.default_encoding, "replace")
240     outfile.write(s)
241     outfile.close()
242
243     pipe = os.popen(command, 'r')
244     s = pipe.read()
245     pipe.close()
246     os.remove(filename)
247
248     set_content_type(msg, "text/plain")
249     msg["X-MIME-Autoconverted"] = "from %s to text/plain by %s id %s" % (content_type, g.host_name, command.split()[0])
250
251     return s
252
253
254 def recode_charset(msg, s):
255     "Recode charset of the message to the default charset"
256
257     save_charset = charset = msg.get_content_charset()
258     if charset and charset.lower() != g.default_encoding:
259         s = recode_if_needed(s, charset)
260         content_type = msg.get_content_type()
261         set_content_type(msg, content_type, g.default_encoding)
262         msg["X-MIME-Autoconverted"] = "from %s to %s by %s id %s" % (save_charset, g.default_encoding, g.host_name, me)
263     return s
264
265
266 def totext(msg, instring):
267     "Convert instring content to text"
268
269     # Decode body and recode charset
270     s = decode_body(msg, instring)
271     if g.recode_charset:
272         s = recode_charset(msg, s)
273
274     output_headers(msg)
275     output(s)
276     return s
277
278
279 mimetypes = None
280
281 def _guess_extension(ctype):
282     global mimetypes
283     if mimetypes is None:
284         import mimetypes
285         mimetypes.init()
286         user_mime_type = os.path.expanduser('~/.mime.types')
287         if os.path.exists(user_mime_type):
288             mimetypes._db.read(user_mime_type)
289     return mimetypes.guess_extension(ctype)
290
291 def _save_message(msg, outstring, save_headers=False, save_body=False):
292     for header, param in (
293         ("Content-Disposition", "filename"),
294         ("Content-Type", "name"),
295     ):
296         fname = msg.get_param(param, header=header)
297         if fname:
298             if isinstance(fname, tuple):
299                 fname = fname[2] # Do not recode if it isn't recoded yet
300             try:
301                     for forbidden in chr(0), '/', '\\':
302                         if forbidden in fname:
303                             raise ValueError
304             except ValueError:
305                 continue
306             fname = '-' + fname
307             break
308     else:
309         fname = ''
310     g.save_counter += 1
311     fname = str(g.save_counter) + fname
312     if '.' not in fname:
313         ext = _guess_extension(msg.get_content_type())
314         if ext: fname += ext
315
316     global output
317     save_output = output
318     outfile = open_output_file(fname)
319     def _output_bytes(s):
320         if not isinstance(s, bytes):
321             s = s.encode(g.default_encoding, "replace")
322         outfile.write(s)
323     output = _output_bytes
324     if save_headers:
325         output_headers(msg)
326     if save_body:
327         output(outstring)
328     outfile.close()
329     output = save_output
330
331
332 def decode_part(msg):
333     "Decode one part of the message"
334
335     decode_headers(msg)
336
337     # Test all mask lists and find what to do with this content type
338     masks = []
339     ctype = msg.get_content_type()
340     if ctype:
341         masks.append(ctype)
342         mtype = ctype.split('/')[0]
343         masks.append(mtype + '/*')
344     masks.append('*/*')
345
346     left_binary = False
347     for content_type in masks:
348         if content_type in g.totext_mask or \
349            content_type in g.decoded_binary_mask:
350             break
351         elif content_type in g.binary_mask:
352             left_binary = True
353             break
354         elif content_type in g.fully_ignore_mask:
355             return
356
357     encoding = msg["Content-Transfer-Encoding"]
358     if left_binary or encoding in (None, '', '7bit', '8bit', 'binary'):
359         outstring = msg.get_payload()
360     else: # Decode from transfer ecoding to text or binary form
361         outstring = msg.get_payload(decode=1)
362         set_header(msg, "Content-Transfer-Encoding", "8bit")
363         msg["X-MIME-Autoconverted"] = "from %s to 8bit by %s id %s" % (encoding, g.host_name, me)
364
365     for content_type in masks:
366         if content_type in g.totext_mask:
367             outstring = totext(msg, outstring)
368             break
369         elif content_type in g.binary_mask or \
370              content_type in g.decoded_binary_mask:
371             output_headers(msg)
372             output(outstring)
373             break
374         elif content_type in g.ignore_mask:
375             output_headers(msg)
376             output("%sMessage body of type %s skipped.%s" % (os.linesep, ctype, os.linesep))
377             break
378         elif content_type in g.error_mask:
379             break
380     else:
381         # Neither content type nor masks were listed - decode by default
382         outstring = totext(msg, outstring)
383
384     for content_type in masks:
385         if content_type in g.save_headers_mask:
386             _save_message(msg, outstring, save_headers=True, save_body=False)
387         if content_type in g.save_body_mask:
388             _save_message(msg, outstring, save_headers=False, save_body=True)
389         if content_type in g.save_message_mask:
390             _save_message(msg, outstring, save_headers=True, save_body=True)
391
392     for content_type in masks:
393         if content_type in g.error_mask:
394             raise ValueError("content type %s prohibited" % ctype)
395
396 def decode_multipart(msg):
397     "Decode multipart"
398
399     decode_headers(msg)
400     boundary = msg.get_boundary()
401
402     masks = []
403     ctype = msg.get_content_type()
404     if ctype:
405         masks.append(ctype)
406         mtype = ctype.split('/')[0]
407         masks.append(mtype + '/*')
408     masks.append('*/*')
409
410     for content_type in masks:
411         if content_type in g.fully_ignore_mask:
412             return
413         elif content_type in g.ignore_mask:
414             output_headers(msg)
415             output("%sMessage body of type %s skipped.%s" % (os.linesep, ctype, os.linesep))
416             if boundary:
417                 output("%s--%s--%s" % (os.linesep, boundary, os.linesep))
418             return
419
420     for content_type in masks:
421         if content_type in g.save_body_mask or \
422                 content_type in g.save_message_mask:
423             _out_l = []
424             first_subpart = True
425             for subpart in msg.get_payload():
426                 if first_subpart:
427                     first_subpart = False
428                 else:
429                     _out_l.append(os.linesep)
430                 _out_l.append("--%s%s" % (boundary, os.linesep))
431                 _out_l.append(subpart.as_string())
432             _out_l.append("%s--%s--%s" % (os.linesep, boundary, os.linesep))
433             outstring = ''.join(_out_l)
434             break
435     else:
436         outstring = None
437
438     for content_type in masks:
439         if content_type in g.save_headers_mask:
440             _save_message(msg, outstring, save_headers=True, save_body=False)
441         if content_type in g.save_body_mask:
442             _save_message(msg, outstring, save_headers=False, save_body=True)
443         if content_type in g.save_message_mask:
444             _save_message(msg, outstring, save_headers=True, save_body=True)
445
446     for content_type in masks:
447         if content_type in g.error_mask:
448             raise ValueError("content type %s prohibited" % ctype)
449
450     output_headers(msg)
451
452     if msg.preamble: # Preserve the first part, it is probably not a RFC822-message
453         output(msg.preamble) # Usually it is just a few lines of text (MIME warning)
454     if msg.preamble is not None:
455         output(os.linesep)
456
457     first_subpart = True
458     for subpart in msg.get_payload():
459         if boundary:
460             if first_subpart:
461                 first_subpart = False
462             else:
463                 output(os.linesep)
464             output("--%s%s" % (boundary, os.linesep))
465
466         # Recursively decode all parts of the subpart
467         decode_message(subpart)
468
469     if boundary:
470         output("%s--%s--%s" % (os.linesep, boundary, os.linesep))
471
472     if msg.epilogue:
473         output(msg.epilogue)
474
475
476 def decode_message(msg):
477     "Decode message"
478
479     if msg.is_multipart():
480         decode_multipart(msg)
481     elif len(msg): # Simple one-part message (there are headers) - decode it
482         decode_part(msg)
483     else: # Not a message, just text - copy it literally
484         output(msg.as_string())
485
486
487 def open_output_file(filename):
488     fullpath = os.path.abspath(os.path.join(g.destination_dir, filename))
489     full_dir = os.path.dirname(fullpath)
490     create = not os.path.isdir(full_dir)
491     if create:
492         os.makedirs(full_dir)
493     try:
494         return open(fullpath, 'wb')
495     except:
496         if create:
497             os.removedirs(full_dir)
498
499
500 class GlobalOptions:
501     from m_lib.defenc import default_encoding
502     recode_charset = 1 # recode charset of message body
503
504     host_name = None
505
506     # A list of headers to decode
507     decode_headers = ["From", "To", "Cc", "Reply-To", "Mail-Followup-To",
508                       "Subject"]
509
510     # A list of headers parameters to decode
511     decode_header_params = [
512         ("Content-Type", "name"),
513         ("Content-Disposition", "filename"),
514     ]
515
516     # A list of headers to remove
517     remove_headers = []
518     # A list of headers parameters to remove
519     remove_headers_params = []
520
521     # A list of header/value pairs to set
522     set_header_value = []
523     # A list of header/parameter/value triples to set
524     set_header_param = []
525
526     totext_mask = [] # A list of content-types to decode
527     binary_mask = [] # A list of content-types to pass through
528     decoded_binary_mask = [] # A list of content-types to pass through (content-transfer-decoded)
529     ignore_mask = [] # Ignore (do not decode and do not include into output) but output a warning instead of the body
530     fully_ignore_mask = [] # Completely ignore - no headers, no body, no warning
531     error_mask = []  # Raise error if encounter one of these
532
533     save_counter = 0
534     save_headers_mask = []
535     save_body_mask = []
536     save_message_mask = []
537
538     input_filename = None
539     output_filename = None
540     destination_dir = os.curdir
541
542 g = GlobalOptions
543
544
545 def get_opts():
546     from getopt import getopt, GetoptError
547
548     try:
549         options, arguments = getopt(sys.argv[1:],
550             'hVcCDPH:f:d:p:r:R:b:B:e:I:i:t:O:o:',
551             ['help', 'version', 'host=',
552              'save-headers=', 'save-body=', 'save-message=',
553              'set-header=', 'set-param='])
554     except GetoptError:
555         usage(1)
556
557     for option, value in options:
558         if option in ('-h', '--help'):
559             usage()
560         elif option in ('-V', '--version'):
561             version()
562         elif option == '-c':
563             g.recode_charset = 1
564         elif option == '-C':
565             g.recode_charset = 0
566         elif option in ('-H', '--host'):
567             g.host_name = value
568         elif option == '-f':
569             g.default_encoding = value
570         elif option == '-d':
571             if value.startswith('*'):
572                 g.decode_headers = []
573             g.decode_headers.append(value)
574         elif option == '-D':
575             g.decode_headers = []
576         elif option == '-p':
577             g.decode_header_params.append(value.split(':', 1))
578         elif option == '-P':
579             g.decode_header_params = []
580         elif option == '-r':
581             g.remove_headers.append(value)
582         elif option == '-R':
583             g.remove_headers_params.append(value.split(':', 1))
584         elif option == '--set-header':
585             g.set_header_value.append(value.split(':', 1))
586         elif option == '--set-param':
587             header, value = value.split(':', 1)
588             if '=' in value:
589                 param, value = value.split('=', 1)
590             else:
591                 param, value = value.split(':', 1)
592             g.set_header_param.append((header, param, value))
593         elif option == '-t':
594             g.totext_mask.append(value)
595         elif option == '-B':
596             g.binary_mask.append(value)
597         elif option == '-b':
598             g.decoded_binary_mask.append(value)
599         elif option == '-I':
600             g.fully_ignore_mask.append(value)
601         elif option == '-i':
602             g.ignore_mask.append(value)
603         elif option == '-e':
604             g.error_mask.append(value)
605         elif option == '--save-headers':
606             g.save_headers_mask.append(value)
607         elif option == '--save-body':
608             g.save_body_mask.append(value)
609         elif option == '--save-message':
610             g.save_message_mask.append(value)
611         elif option == '-O':
612             g.destination_dir = value
613         elif option == '-o':
614             g.output_filename = value
615         else:
616             usage(1)
617
618     return arguments
619
620
621 if __name__ == "__main__":
622     arguments = get_opts()
623
624     la = len(arguments)
625     if la == 0:
626         g.input_filename = '-'
627         infile = sys.stdin
628         if g.output_filename:
629             outfile = open_output_file(g.output_filename)
630         else:
631             g.output_filename = '-'
632             outfile = sys.stdout
633     elif la in (1, 2):
634         if (arguments[0] == '-'):
635             g.input_filename = '-'
636             infile = sys.stdin
637         else:
638             g.input_filename = arguments[0]
639             infile = open(arguments[0], 'r')
640         if la == 1:
641             if g.output_filename:
642                 outfile = open_output_file(g.output_filename)
643             else:
644                 g.output_filename = '-'
645                 outfile = sys.stdout
646         elif la == 2:
647             if g.output_filename:
648                 usage(1, 'Too many output filenames')
649             if (arguments[1] == '-'):
650                 g.output_filename = '-'
651                 outfile = sys.stdout
652             else:
653                 g.output_filename = arguments[1]
654                 outfile = open_output_file(g.output_filename)
655     else:
656         usage(1, 'Too many arguments')
657
658     if (infile is sys.stdin) and sys.stdin.isatty():
659         if (outfile is sys.stdout) and sys.stdout.isatty():
660             usage()
661         usage(1, 'Filtering from console is forbidden')
662
663     if not g.host_name:
664         import socket
665         g.host_name = socket.gethostname()
666
667     g.outfile = outfile
668     if hasattr(outfile, 'buffer'):
669         def output_bytes(s):
670             if not isinstance(s, bytes):
671                 s = s.encode(g.default_encoding, "replace")
672             outfile.buffer.write(s)
673         output = output_bytes
674     else:
675         output = outfile.write
676
677     import email
678     msg = email.message_from_file(infile)
679
680     for header, value in g.set_header_value:
681         set_header(msg, header, value)
682
683     for header, param, value in g.set_header_param:
684         if header in msg:
685             msg.set_param(param, value, header)
686
687     try:
688         decode_message(msg)
689     finally:
690         infile.close()
691         outfile.close()