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