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