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