]> git.phdru.name Git - mimedecode.git/blob - mimedecode.py
Change option -d to decode all headers with exceptions
[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 header1[,h2,...]|*[,-h1,...]] [-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: # No such header
106             continue
107         if ';' not in value: # There are no parameters
108             continue
109         del msg[header] # Delete all such headers
110         # Get the value without parameters and set it back
111         msg[header] = value.split(';')[0].strip()
112
113     for header, param in gopts.remove_header_params:
114         msg.del_param(param, header)
115
116     for header_list in gopts.decode_headers:
117         header_list = header_list.split(',')
118         if header_list[0] == '*': # Decode all headers except listed
119             header_list = [h[1:].lower() for h in header_list[1:] if h[0]=='-']
120             for header in msg.keys():
121                 if header.lower() not in header_list:
122                     decode_header(msg, header)
123         else: # Decode listed hiders
124             for header in header_list:
125                 decode_header(msg, header)
126
127     for header, param in gopts.decode_header_params:
128         decode_header_param(msg, header, param)
129
130
131 def set_header(msg, header, value):
132     "Replace header"
133
134     if msg.has_key(header):
135         msg.replace_header(header, value)
136     else:
137         msg[header] = value
138
139
140 def set_content_type(msg, newtype, charset=None):
141     msg.set_type(newtype)
142
143     if charset:
144         msg.set_param("charset", charset, "Content-Type")
145
146
147 caps = None # Globally stored mailcap database; initialized only if needed
148
149 def decode_body(msg, s):
150     "Decode body to plain text using first copiousoutput filter from mailcap"
151
152     import mailcap, tempfile
153
154     global caps
155     if caps is None:
156         caps = mailcap.getcaps()
157
158     content_type = msg.get_content_type()
159     filename = tempfile.mktemp()
160     command = None
161
162     entries = mailcap.lookup(caps, content_type, "view")
163     for entry in entries:
164         if entry.has_key('copiousoutput'):
165             if entry.has_key('test'):
166                 test = mailcap.subst(entry['test'], content_type, filename)
167                 if test and os.system(test) != 0:
168                     continue
169             command = mailcap.subst(entry["view"], content_type, filename)
170             break
171
172     if not command:
173         return s
174
175     file = open(filename, 'w')
176     file.write(s)
177     file.close()
178
179     pipe = os.popen(command, 'r')
180     s = pipe.read()
181     pipe.close()
182     os.remove(filename)
183
184     set_content_type(msg, "text/plain")
185     msg["X-MIME-Autoconverted"] = "from %s to text/plain by %s id %s" % (content_type, gopts.host_name, command.split()[0])
186
187     return s
188
189
190 def recode_charset(msg, s):
191     "Recode charset of the message to the default charset"
192
193     save_charset = charset = msg.get_content_charset()
194     if charset and charset.lower() <> gopts.default_encoding:
195         s = recode_if_needed(s, charset)
196         content_type = msg.get_content_type()
197         set_content_type(msg, content_type, gopts.default_encoding)
198         msg["X-MIME-Autoconverted"] = "from %s to %s by %s id %s" % (save_charset, gopts.default_encoding, gopts.host_name, me)
199     return s
200
201
202 def totext(msg, instring):
203     "Convert instring content to text"
204
205     # Decode body and recode charset
206     s = decode_body(msg, instring)
207     if gopts.recode_charset:
208         s = recode_charset(msg, s)
209
210     output_headers(msg)
211     output(s)
212
213
214 def decode_part(msg):
215     "Decode one part of the message"
216
217     decode_headers(msg)
218     encoding = msg["Content-Transfer-Encoding"]
219
220     if encoding in (None, '', '7bit', '8bit', 'binary'):
221         outstring = str(msg.get_payload())
222     else: # Decode from transfer ecoding to text or binary form
223         outstring = str(msg.get_payload(decode=1))
224         set_header(msg, "Content-Transfer-Encoding", "8bit")
225         msg["X-MIME-Autoconverted"] = "from %s to 8bit by %s id %s" % (encoding, gopts.host_name, me)
226
227     # Test all mask lists and find what to do with this content type
228     masks = []
229     ctype = msg.get_content_type()
230     if ctype:
231         masks.append(ctype)
232     mtype = msg.get_content_maintype()
233     if mtype:
234         masks.append(mtype + '/*')
235     masks.append('*/*')
236
237     for content_type in masks:
238         if content_type in gopts.totext_mask:
239             totext(msg, outstring)
240             return
241         elif content_type in gopts.binary_mask:
242             output_headers(msg)
243             output(outstring)
244             return
245         elif content_type in gopts.ignore_mask:
246             output_headers(msg)
247             output("\nMessage body of type `%s' skipped.\n" % content_type)
248             return
249         elif content_type in gopts.error_mask:
250             raise ValueError, "content type `%s' prohibited" % content_type
251
252     # Neither content type nor masks were listed - decode by default
253     totext(msg, outstring)
254
255
256 def decode_multipart(msg):
257     "Decode multipart"
258
259     decode_headers(msg)
260     output_headers(msg)
261
262     if msg.preamble: # Preserve the first part, it is probably not a RFC822-message
263         output(msg.preamble) # Usually it is just a few lines of text (MIME warning)
264
265     boundary = msg.get_boundary()
266
267     for subpart in msg.get_payload():
268         if boundary:
269             output("\n--%s\n" % boundary)
270
271         # Recursively decode all parts of the subpart
272         decode_message(subpart)
273
274     if boundary:
275         output("\n--%s--\n" % boundary)
276
277     if msg.epilogue:
278         output(msg.epilogue)
279
280
281 def decode_message(msg):
282     "Decode message"
283
284     if msg.is_multipart():
285         decode_multipart(msg)
286     elif len(msg): # Simple one-part message (there are headers) - decode it
287         decode_part(msg)
288     else: # Not a message, just text - copy it literally
289         output(msg.as_string())
290
291
292 class GlobalOptions:
293     from m_lib.defenc import default_encoding
294     recode_charset = 1 # recode charset of message body
295
296     host_name = None
297
298     # A list of headers to decode
299     decode_headers = ["From", "To", "Cc", "Reply-To", "Mail-Followup-To",
300                       "Subject"]
301
302     # A list of headers parameters to decode
303     decode_header_params = [
304         ("Content-Type", "name"),
305         ("Content-Disposition", "filename"),
306     ]
307
308     # A list of headers to remove
309     remove_headers = []
310     # A list of headers parameters to remove
311     remove_header_params = []
312     # A list of headers to be stripped of all parameters
313     remove_all_params = []
314
315     totext_mask = [] # A list of content-types to decode
316     binary_mask = [] # A list to pass through
317     ignore_mask = [] # Ignore (skip, do not decode and do not include into output)
318     error_mask = []  # Raise error if encounter one of these
319
320     input_filename = None
321     output_filename = None
322
323 gopts = GlobalOptions
324
325
326 def get_opt():
327     from getopt import getopt, GetoptError
328
329     try:
330         options, arguments = getopt(sys.argv[1:],
331             'hVcCDPH:f:d:p:r:R:b:e:i:t:o:',
332             ['help', 'version', 'host=', 'remove-params='])
333     except GetoptError:
334         usage(1)
335
336     for option, value in options:
337         if option in ('-h', '--help'):
338             usage()
339         elif option in ('-V', '--version'):
340             version()
341         elif option == '-c':
342             gopts.recode_charset = 1
343         elif option == '-C':
344             gopts.recode_charset = 0
345         elif option in ('-H', '--host'):
346             gopts.host_name = value
347         elif option == '-f':
348             gopts.default_encoding = value
349         elif option == '-d':
350             if value.startswith('*'):
351                 gopts.decode_headers = []
352             gopts.decode_headers.append(value)
353         elif option == '-D':
354             gopts.decode_headers = []
355         elif option == '-p':
356             gopts.decode_header_params.append(value.split(':', 1))
357         elif option == '-P':
358             gopts.decode_header_params = []
359         elif option == '-r':
360             gopts.remove_headers.append(value)
361         elif option == '-R':
362             gopts.remove_header_params.append(value.split(':', 1))
363         elif option == '--remove-params':
364             gopts.remove_all_params.append(value)
365         elif option == '-t':
366             gopts.totext_mask.append(value)
367         elif option == '-b':
368             gopts.binary_mask.append(value)
369         elif option == '-i':
370             gopts.ignore_mask.append(value)
371         elif option == '-e':
372             gopts.error_mask.append(value)
373         elif option == '-o':
374             gopts.output_filename = value
375         else:
376             usage(1)
377
378     return arguments
379
380
381 if __name__ == "__main__":
382     arguments = get_opt()
383
384     la = len(arguments)
385     if la == 0:
386         gopts.input_filename = '-'
387         infile = sys.stdin
388         if gopts.output_filename:
389             outfile = open(gopts.output_filename, 'w')
390         else:
391             gopts.output_filename = '-'
392             outfile = sys.stdout
393     elif la in (1, 2):
394         if (arguments[0] == '-'):
395             gopts.input_filename = '-'
396             infile = sys.stdin
397         else:
398             gopts.input_filename = arguments[0]
399             infile = open(arguments[0], 'r')
400         if la == 1:
401             if gopts.output_filename:
402                 outfile = open(gopts.output_filename, 'w')
403             else:
404                 gopts.output_filename = '-'
405                 outfile = sys.stdout
406         elif la == 2:
407             if gopts.output_filename:
408                 usage(1, 'Too many output filenames')
409             if (arguments[1] == '-'):
410                 gopts.output_filename = '-'
411                 outfile = sys.stdout
412             else:
413                 gopts.output_filename = arguments[1]
414                 outfile = open(arguments[1], 'w')
415     else:
416         usage(1, 'Too many arguments')
417
418     if (infile is sys.stdin) and sys.stdin.isatty():
419         if (outfile is sys.stdout) and sys.stdout.isatty():
420             usage()
421         usage(1, 'Filtering from console is forbidden')
422
423     if not gopts.host_name:
424         import socket
425         gopts.host_name = socket.gethostname()
426
427     gopts.outfile = outfile
428     output = outfile.write
429
430     try:
431         decode_message(email.message_from_file(infile))
432     finally:
433         infile.close()
434         outfile.close()