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