]> git.phdru.name Git - mimedecode.git/blob - mimedecode.py
ANNOUNCE: forbid filtering from console to console
[mimedecode.git] / mimedecode.py
1 #! /usr/bin/env python
2 """Decode MIME message"""
3
4
5 from mimedecode_version import __version__, __author__, __copyright__, __license__
6
7
8 import sys, os
9 import email
10
11 try:
12     from cStringIO import StringIO
13 except ImportError:
14     from StringIO import StringIO
15
16
17 import socket
18 host_name = socket.gethostname()
19
20 me = os.path.basename(sys.argv[0])
21
22
23 def version(exit=1):
24     sys.stdout.write("""\
25 Broytman mimedecode.py version %s, %s
26 """ % (__version__, __copyright__))
27     if exit: sys.exit(0)
28
29
30 def usage(code=0, errormsg=''):
31     version(0)
32     sys.stdout.write("""\
33 Usage: %s [-h|--help] [-V|--version] [-cCDP] [-f charset] [-d header] [-p header:param] [-beit mask] [-o output_file] [input_file [output_file]]
34 """ % me)
35     if errormsg:
36         sys.stderr.write(errormsg + '\n')
37     sys.exit(code)
38
39
40 def output(s):
41     gopts.outfile.write(s)
42
43 def output_headers(msg):
44     unix_from = msg.get_unixfrom()
45     if unix_from:
46         output(unix_from + '\n')
47     for key, value in msg.items():
48         output("%s: %s\n" % (key, value))
49     output("\n") # End of headers
50
51
52 def recode(s, charset):
53     return unicode(s, charset, "replace").encode(gopts.default_encoding, "replace")
54
55
56 def recode2(s, charset):
57     if charset and charset.lower() <> gopts.default_encoding:
58         s = recode(s, charset)
59     return s
60
61
62 def _decode_header(s):
63     """Return a decoded string according to RFC 2047.
64     NOTE: This is almost the same as email.Utils.decode.
65     """
66     from types import ListType
67     import email.Header
68
69     L = email.Header.decode_header(s)
70     if not isinstance(L, ListType):
71         # s wasn't decoded
72         return s
73
74     rtn = []
75     for atom, charset in L:
76         if charset is None:
77             rtn.append(atom)
78         else:
79             rtn.append(recode2(atom, charset))
80         rtn.append(' ')
81     del rtn[-1] # remove the last space
82
83     # Now that we've decoded everything, we just need to join all the parts
84     # together into the final string.
85     return ''.join(rtn)
86
87
88 def decode_header(msg, header):
89     "Decode mail header (if exists) and put it back, if it was encoded"
90
91     if msg.has_key(header):
92         value = msg[header]
93         new_value = _decode_header(value)
94         if new_value <> value: # do not bother to touch msg if not changed
95             set_header(msg, header, new_value)
96
97
98 def _decode_header_param(s):
99     return recode2(s[2], s[0])
100
101
102 def decode_header_param(msg, header, param):
103     "Decode mail header's parameter (if exists) and put it back, if it was encoded"
104
105     if msg.has_key(header):
106         value = msg.get_param(param, header=header)
107         if value:
108             from types import TupleType
109             if isinstance(value, TupleType):
110                 new_value = _decode_header_param(value)
111             else:
112                 new_value = _decode_header(value)
113             if new_value <> value: # do not bother to touch msg if not changed
114                 msg.set_param(param, new_value, header)
115
116
117 def decode_headers(msg):
118     "Decode message headers according to global options"
119
120     for header in gopts.decode_headers:
121         decode_header(msg, header)
122
123     for header, param in gopts.decode_header_params:
124         decode_header_param(msg, header, param)
125
126
127 def set_header(msg, header, value):
128     "Replace header"
129
130     if msg.has_key(header):
131         msg.replace_header(header, value)
132     else:
133         msg[header] = value
134
135
136 def set_content_type(msg, newtype, charset=None):
137     msg.set_type(newtype)
138
139     if charset:
140         msg.set_param("charset", charset, "Content-Type")
141
142
143
144 caps = None # Globally stored mailcap database; initialized only if needed
145
146 def decode_body(msg, s):
147     "Decode body to plain text using first copiousoutput filter from mailcap"
148
149     import mailcap, tempfile
150
151     global caps
152     if caps is None:
153         caps = mailcap.getcaps()
154
155     content_type = msg.get_content_type()
156     filename = tempfile.mktemp()
157     command = None
158
159     entries = mailcap.lookup(caps, content_type, "view")
160     for entry in entries:
161         if entry.has_key('copiousoutput'):
162             if entry.has_key('test'):
163                 test = mailcap.subst(entry['test'], content_type, filename)
164                 if test and os.system(test) != 0:
165                     continue
166             command = mailcap.subst(entry["view"], content_type, filename)
167             break
168
169     if not command:
170         return s
171
172     file = open(filename, 'w')
173     file.write(s)
174     file.close()
175
176     pipe = os.popen(command, 'r')
177     s = pipe.read()
178     pipe.close()
179     os.remove(filename)
180
181     set_content_type(msg, "text/plain")
182     msg["X-MIME-Autoconverted"] = "from %s to text/plain by %s id %s" % (content_type, host_name, command.split()[0])
183
184     return s
185
186
187 def recode_charset(msg, s):
188     "Recode charset of the message to the default charset"
189
190     save_charset = charset = msg.get_content_charset()
191     if charset and charset.lower() <> gopts.default_encoding:
192         s = recode2(s, charset)
193         content_type = msg.get_content_type()
194         set_content_type(msg, content_type, gopts.default_encoding)
195         msg["X-MIME-Autoconverted"] = "from %s to %s by %s id %s" % (save_charset, gopts.default_encoding, host_name, me)
196     return s
197
198
199 def totext(msg, instring):
200     "Convert instring content to text"
201
202     if msg.is_multipart(): # Recursively decode all parts of the multipart message
203         newfile = StringIO(str(msg))
204         newfile.seek(0)
205         decode_file(newfile)
206         return
207
208     # Decode body and recode charset
209     s = decode_body(msg, instring)
210     if gopts.recode_charset:
211         s = recode_charset(msg, s)
212
213     output_headers(msg)
214     output(s)
215
216
217 def decode_part(msg):
218     "Decode one part of the message"
219
220     decode_headers(msg)
221     encoding = msg["Content-Transfer-Encoding"]
222
223     if encoding in (None, '', '7bit', '8bit', 'binary'):
224         outstring = str(msg.get_payload())
225     else: # Decode from transfer ecoding to text or binary form
226         outstring = str(msg.get_payload(decode=1))
227         set_header(msg, "Content-Transfer-Encoding", "8bit")
228         msg["X-MIME-Autoconverted"] = "from %s to 8bit by %s id %s" % (encoding, host_name, me)
229
230     # Test all mask lists and find what to do with this content type
231     masks = []
232     ctype = msg.get_content_type()
233     if ctype:
234         masks.append(ctype)
235     mtype = msg.get_content_maintype()
236     if mtype:
237         masks.append(mtype + '/*')
238     masks.append('*/*')
239
240     for content_type in masks:
241         if content_type in gopts.totext_mask:
242             totext(msg, outstring)
243             return
244         elif content_type in gopts.binary_mask:
245             output_headers(msg)
246             output(outstring)
247             return
248         elif content_type in gopts.ignore_mask:
249             output_headers(msg)
250             output("\nMessage body of type `%s' skipped.\n" % content_type)
251             return
252         elif content_type in gopts.error_mask:
253             raise ValueError, "content type `%s' prohibited" % content_type
254
255     # Neither content type nor masks were listed - decode by default
256     totext(msg, outstring)
257
258
259 def decode_file(infile):
260     "Decode the entire message"
261
262     msg = email.message_from_file(infile)
263     boundary = msg.get_boundary()
264
265     if msg.is_multipart():
266         decode_headers(msg)
267         output_headers(msg)
268
269         if msg.preamble: # Preserve the first part, it is probably not a RFC822-message
270             output(msg.preamble) # Usually it is just a few lines of text (MIME warning)
271
272         for subpart in msg.get_payload():
273             output("\n--%s\n" % boundary)
274             decode_part(subpart)
275
276         output("\n--%s--\n" % boundary)
277
278         if msg.epilogue:
279             output(msg.epilogue)
280
281     else:
282         if msg.has_key("Content-Type"): # Simple one-part message - decode it
283             decode_part(msg)
284
285         else: # Not a message, just text - copy it literally
286             output(str(msg))
287
288
289 class GlobalOptions:
290     from m_lib.defenc import default_encoding
291     recode_charset = 1 # recode charset of message body
292
293     decode_headers = ["From", "Subject"] # A list of headers to decode
294     decode_header_params = [
295         ("Content-Type", "name"),
296         ("Content-Disposition", "filename"),
297     ] # A list of headers' parameters to decode
298
299     totext_mask = [] # A list of content-types to decode
300     binary_mask = [] # A list to pass through
301     ignore_mask = [] # Ignore (skip, do not decode and do not include into output)
302     error_mask = []  # Raise error if encounter one of these
303
304     input_filename = None
305     output_filename = None
306
307 gopts = GlobalOptions
308
309
310 def get_opt():
311     from getopt import getopt, GetoptError
312
313     try:
314         options, arguments = getopt(sys.argv[1:], 'hVcCDPf:d:p:b:e:i:t:o:',
315             ['help', 'version'])
316     except GetoptError:
317         usage(1)
318
319     for option, value in options:
320         if option == '-h':
321             usage()
322         elif option == '--help':
323             usage()
324         elif option == '-V':
325             version()
326         elif option == '--version':
327             version()
328         elif option == '-c':
329             gopts.recode_charset = 1
330         elif option == '-C':
331             gopts.recode_charset = 0
332         elif option == '-f':
333             gopts.default_encoding = value
334         elif option == '-d':
335             gopts.decode_headers.append(value)
336         elif option == '-D':
337             gopts.decode_headers = []
338         elif option == '-p':
339             gopts.decode_header_params.append(value.split(':', 1))
340         elif option == '-P':
341             gopts.decode_header_params = []
342         elif option == '-t':
343             gopts.totext_mask.append(value)
344         elif option == '-b':
345             gopts.binary_mask.append(value)
346         elif option == '-i':
347             gopts.ignore_mask.append(value)
348         elif option == '-e':
349             gopts.error_mask.append(value)
350         elif option == '-o':
351             gopts.output_filename = value
352         else:
353             usage(1)
354
355     return arguments
356
357
358 if __name__ == "__main__":
359     arguments = get_opt()
360
361     la = len(arguments)
362     if la == 0:
363         gopts.input_filename = '-'
364         gopts.output_filename = '-'
365         infile = sys.stdin
366         outfile = sys.stdout
367     elif la in (1, 2):
368         if (arguments[0] == '-'):
369             gopts.input_filename = '-'
370             infile = sys.stdin
371         else:
372             gopts.input_filename = arguments[0]
373             infile = open(arguments[0], 'r')
374         if la == 1:
375             if gopts.output_filename:
376                 outfile = open(gopts.output_filename, 'w')
377             else:
378                 gopts.output_filename = '-'
379                 outfile = sys.stdout
380         elif la == 2:
381             if gopts.output_filename:
382                 usage(1, 'Too many output filenames')
383             if (arguments[1] == '-'):
384                 gopts.output_filename = '-'
385                 outfile = sys.stdout
386             else:
387                 gopts.output_filename = arguments[1]
388                 outfile = open(arguments[1], 'w')
389     else:
390         usage(1, 'Too many arguments')
391
392     if (infile is sys.stdin) and (outfile is sys.stdout) and \
393             sys.stdin.isatty() and sys.stdout.isatty():
394         usage(1, 'Filtering from console to console is forbidden')
395
396     gopts.outfile = outfile
397     decode_file(infile)
398
399     infile.close()
400     outfile.close()