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