]> git.phdru.name Git - mimedecode.git/blob - mimedecode.py
Documentation update
[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 header1[,h2,...]|*[,-h1,...]] [-R header1[,h2,h3,...]:param1[,p2,p3,...]] [--set-header header:value] [--set-param header:param=value] [-Bbeit mask] [--save-headers|body|message mask] [-O dest_dir] [-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(g.default_encoding, "replace")
39
40 def recode_if_needed(s, charset):
41     if charset and charset.lower() <> g.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 _remove_headers_params(msg, header, remove_all_params, param_list):
112     if remove_all_params:
113         params = msg.get_params(header=header)
114         if params:
115             if param_list:
116                 for param, value in params:
117                     if param not in param_list:
118                         msg.del_param(param, header)
119             else:
120                 value = msg[header]
121                 if value is None: # No such header
122                     return
123                 if ';' not in value: # There are no parameters
124                     return
125                 del msg[header] # Delete all such headers
126                 # Get the value without parameters and set it back
127                 msg[header] = value.split(';')[0].strip()
128     else:
129         for param in param_list:
130             msg.del_param(param, header)
131
132 def decode_headers(msg):
133     "Decode message headers according to global options"
134
135     for header_list in g.remove_headers:
136         header_list = header_list.split(',')
137         if header_list[0] == '*': # Remove all headers except listed
138             header_list = _get_exceptions(header_list)
139             for header in msg.keys():
140                 if header.lower() not in header_list:
141                     del msg[header]
142         else: # Remove listed headers
143             for header in header_list:
144                 del msg[header]
145
146     for header_list, param_list in g.remove_headers_params:
147         header_list = header_list.split(',')
148         param_list = param_list.split(',')
149         remove_all_params = param_list[0] == '*' # Remove all params except listed
150         if remove_all_params:
151             param_list = _get_exceptions(param_list)
152         if header_list[0] == '*': # Remove for all headers except listed
153             header_list = _get_exceptions(header_list)
154             for header in msg.keys():
155                 if header.lower() not in header_list:
156                     _remove_headers_params(msg, header, remove_all_params, param_list)
157         else: # Decode for listed headers
158             for header in header_list:
159                 _remove_headers_params(msg, header, remove_all_params, param_list)
160
161     for header_list in g.decode_headers:
162         header_list = header_list.split(',')
163         if header_list[0] == '*': # Decode all headers except listed
164             header_list = _get_exceptions(header_list)
165             for header in msg.keys():
166                 if header.lower() not in header_list:
167                     decode_header(msg, header)
168         else: # Decode listed headers
169             for header in header_list:
170                 decode_header(msg, header)
171
172     for header_list, param_list in g.decode_header_params:
173         header_list = header_list.split(',')
174         param_list = param_list.split(',')
175         decode_all_params = param_list[0] == '*' # Decode all params except listed
176         if decode_all_params:
177             param_list = _get_exceptions(param_list)
178         if header_list[0] == '*': # Decode for all headers except listed
179             header_list = _get_exceptions(header_list)
180             for header in msg.keys():
181                 if header.lower() not in header_list:
182                     _decode_headers_params(msg, header, decode_all_params, param_list)
183         else: # Decode for listed headers
184             for header in header_list:
185                 _decode_headers_params(msg, header, decode_all_params, param_list)
186
187
188 def set_header(msg, header, value):
189     "Replace header"
190
191     if msg.has_key(header):
192         msg.replace_header(header, value)
193     else:
194         msg[header] = value
195
196
197 def set_content_type(msg, newtype, charset=None):
198     msg.set_type(newtype)
199
200     if charset:
201         msg.set_param("charset", charset, "Content-Type")
202
203
204 caps = None # Globally stored mailcap database; initialized only if needed
205
206 def decode_body(msg, s):
207     "Decode body to plain text using first copiousoutput filter from mailcap"
208
209     import mailcap, tempfile
210
211     global caps
212     if caps is None:
213         caps = mailcap.getcaps()
214
215     content_type = msg.get_content_type()
216     filename = tempfile.mktemp()
217     command = None
218
219     entries = mailcap.lookup(caps, content_type, "view")
220     for entry in entries:
221         if entry.has_key('copiousoutput'):
222             if entry.has_key('test'):
223                 test = mailcap.subst(entry['test'], content_type, filename)
224                 if test and os.system(test) != 0:
225                     continue
226             command = mailcap.subst(entry["view"], content_type, filename)
227             break
228
229     if not command:
230         return s
231
232     file = open(filename, 'w')
233     file.write(s)
234     file.close()
235
236     pipe = os.popen(command, 'r')
237     s = pipe.read()
238     pipe.close()
239     os.remove(filename)
240
241     set_content_type(msg, "text/plain")
242     msg["X-MIME-Autoconverted"] = "from %s to text/plain by %s id %s" % (content_type, g.host_name, command.split()[0])
243
244     return s
245
246
247 def recode_charset(msg, s):
248     "Recode charset of the message to the default charset"
249
250     save_charset = charset = msg.get_content_charset()
251     if charset and charset.lower() <> g.default_encoding:
252         s = recode_if_needed(s, charset)
253         content_type = msg.get_content_type()
254         set_content_type(msg, content_type, g.default_encoding)
255         msg["X-MIME-Autoconverted"] = "from %s to %s by %s id %s" % (save_charset, g.default_encoding, g.host_name, me)
256     return s
257
258
259 def totext(msg, instring):
260     "Convert instring content to text"
261
262     # Decode body and recode charset
263     s = decode_body(msg, instring)
264     if g.recode_charset:
265         s = recode_charset(msg, s)
266
267     output_headers(msg)
268     output(s)
269     return s
270
271
272 def _save_message(msg, outstring, save_headers=False, save_body=False):
273     for header, param in (
274         ("Content-Disposition", "filename"),
275         ("Content-Type", "name"),
276     ):
277         fname = msg.get_param(param, header=header)
278         if fname:
279             fname = '-' + fname
280             break
281     else:
282         fname = ''
283     g.save_counter += 1
284     fname = str(g.save_counter) + fname
285
286     global output
287     save_output = output
288     outfile = open(os.path.join(g.destination_dir, fname), 'w')
289     output = outfile.write
290     if save_headers:
291         output_headers(msg)
292     if save_body:
293         output(outstring)
294     outfile.close()
295     output = save_output
296
297
298 def decode_part(msg):
299     "Decode one part of the message"
300
301     decode_headers(msg)
302
303     # Test all mask lists and find what to do with this content type
304     masks = []
305     ctype = msg.get_content_type()
306     if ctype:
307         masks.append(ctype)
308     mtype = msg.get_content_maintype()
309     if mtype:
310         masks.append(mtype + '/*')
311     masks.append('*/*')
312
313     left_binary = False
314     for content_type in masks:
315         if content_type in g.binary_mask:
316             left_binary = True
317             break
318
319     encoding = msg["Content-Transfer-Encoding"]
320     if left_binary or encoding in (None, '', '7bit', '8bit', 'binary'):
321         outstring = msg.get_payload()
322     else: # Decode from transfer ecoding to text or binary form
323         outstring = msg.get_payload(decode=1)
324         set_header(msg, "Content-Transfer-Encoding", "8bit")
325         msg["X-MIME-Autoconverted"] = "from %s to 8bit by %s id %s" % (encoding, g.host_name, me)
326
327     for content_type in masks:
328         if content_type in g.totext_mask:
329             outstring = totext(msg, outstring)
330             break
331         elif content_type in g.binary_mask or \
332              content_type in g.decoded_binary_mask:
333             output_headers(msg)
334             output(outstring)
335             break
336         elif content_type in g.ignore_mask:
337             output_headers(msg)
338             output("\nMessage body of type %s skipped.\n" % ctype)
339             break
340         elif content_type in g.error_mask:
341             raise ValueError, "content type %s prohibited" % ctype
342     else:
343         # Neither content type nor masks were listed - decode by default
344         outstring = totext(msg, outstring)
345
346     for content_type in masks:
347         if content_type in g.save_headers_mask:
348             _save_message(msg, outstring, save_headers=True, save_body=False)
349         elif content_type in g.save_body_mask:
350             _save_message(msg, outstring, save_headers=False, save_body=True)
351         elif content_type in g.save_message_mask:
352             _save_message(msg, outstring, save_headers=True, save_body=True)
353
354 def decode_multipart(msg):
355     "Decode multipart"
356
357     decode_headers(msg)
358     output_headers(msg)
359
360     if msg.preamble: # Preserve the first part, it is probably not a RFC822-message
361         output(msg.preamble) # Usually it is just a few lines of text (MIME warning)
362     if msg.preamble is not None:
363         output("\n")
364
365     first_subpart = True
366     boundary = msg.get_boundary()
367
368     for subpart in msg.get_payload():
369         if boundary:
370             if first_subpart:
371                 first_subpart = False
372             else:
373                 output("\n")
374             output("--%s\n" % boundary)
375
376         # Recursively decode all parts of the subpart
377         decode_message(subpart)
378
379     if boundary:
380         output("\n--%s--\n" % boundary)
381
382     if msg.epilogue:
383         output(msg.epilogue)
384
385
386 def decode_message(msg):
387     "Decode message"
388
389     if msg.is_multipart():
390         decode_multipart(msg)
391     elif len(msg): # Simple one-part message (there are headers) - decode it
392         decode_part(msg)
393     else: # Not a message, just text - copy it literally
394         output(msg.as_string())
395
396
397 class GlobalOptions:
398     from m_lib.defenc import default_encoding
399     recode_charset = 1 # recode charset of message body
400
401     host_name = None
402
403     # A list of headers to decode
404     decode_headers = ["From", "To", "Cc", "Reply-To", "Mail-Followup-To",
405                       "Subject"]
406
407     # A list of headers parameters to decode
408     decode_header_params = [
409         ("Content-Type", "name"),
410         ("Content-Disposition", "filename"),
411     ]
412
413     # A list of headers to remove
414     remove_headers = []
415     # A list of headers parameters to remove
416     remove_headers_params = []
417
418     # A list of header/value pairs to set
419     set_header_value = []
420     # A list of header/parameter/value triples to set
421     set_header_param = []
422
423     totext_mask = [] # A list of content-types to decode
424     binary_mask = [] # A list of content-types to pass through
425     decoded_binary_mask = [] # A list of content-types to pass through (content-transfer-decoded)
426     ignore_mask = [] # Ignore (skip, do not decode and do not include into output)
427     error_mask = []  # Raise error if encounter one of these
428
429     save_counter = 0
430     save_headers_mask = []
431     save_body_mask = []
432     save_message_mask = []
433
434     input_filename = None
435     output_filename = None
436     destination_dir = os.curdir
437
438 g = GlobalOptions
439
440
441 def get_opts():
442     from getopt import getopt, GetoptError
443
444     try:
445         options, arguments = getopt(sys.argv[1:],
446             'hVcCDPH:f:d:p:r:R:b:B:e:i:t:O:o:',
447             ['help', 'version', 'host=',
448              'save-headers=', 'save-body=', 'save-message=',
449              'set-header=', 'set-param='])
450     except GetoptError:
451         usage(1)
452
453     for option, value in options:
454         if option in ('-h', '--help'):
455             usage()
456         elif option in ('-V', '--version'):
457             version()
458         elif option == '-c':
459             g.recode_charset = 1
460         elif option == '-C':
461             g.recode_charset = 0
462         elif option in ('-H', '--host'):
463             g.host_name = value
464         elif option == '-f':
465             g.default_encoding = value
466         elif option == '-d':
467             if value.startswith('*'):
468                 g.decode_headers = []
469             g.decode_headers.append(value)
470         elif option == '-D':
471             g.decode_headers = []
472         elif option == '-p':
473             g.decode_header_params.append(value.split(':', 1))
474         elif option == '-P':
475             g.decode_header_params = []
476         elif option == '-r':
477             g.remove_headers.append(value)
478         elif option == '-R':
479             g.remove_headers_params.append(value.split(':', 1))
480         elif option == '--set-header':
481             g.set_header_value.append(value.split(':', 1))
482         elif option == '--set-param':
483             header, value = value.split(':', 1)
484             if '=' in value:
485                 param, value = value.split('=', 1)
486             else:
487                 param, value = value.split(':', 1)
488             g.set_header_param.append((header, param, value))
489         elif option == '-t':
490             g.totext_mask.append(value)
491         elif option == '-B':
492             g.binary_mask.append(value)
493         elif option == '-b':
494             g.decoded_binary_mask.append(value)
495         elif option == '-i':
496             g.ignore_mask.append(value)
497         elif option == '-e':
498             g.error_mask.append(value)
499         elif option == '--save-headers':
500             g.save_headers_mask.append(value)
501         elif option == '--save-body':
502             g.save_body_mask.append(value)
503         elif option == '--save-message':
504             g.save_message_mask.append(value)
505         elif option == '-O':
506             g.destination_dir = value
507         elif option == '-o':
508             g.output_filename = value
509         else:
510             usage(1)
511
512     return arguments
513
514
515 if __name__ == "__main__":
516     arguments = get_opts()
517
518     la = len(arguments)
519     if la == 0:
520         g.input_filename = '-'
521         infile = sys.stdin
522         if g.output_filename:
523             outfile = open(os.path.join(g.destination_dir, g.output_filename), 'w')
524         else:
525             g.output_filename = '-'
526             outfile = sys.stdout
527     elif la in (1, 2):
528         if (arguments[0] == '-'):
529             g.input_filename = '-'
530             infile = sys.stdin
531         else:
532             g.input_filename = arguments[0]
533             infile = open(arguments[0], 'r')
534         if la == 1:
535             if g.output_filename:
536                 outfile = open(os.path.join(g.destination_dir, g.output_filename), 'w')
537             else:
538                 g.output_filename = '-'
539                 outfile = sys.stdout
540         elif la == 2:
541             if g.output_filename:
542                 usage(1, 'Too many output filenames')
543             if (arguments[1] == '-'):
544                 g.output_filename = '-'
545                 outfile = sys.stdout
546             else:
547                 g.output_filename = arguments[1]
548                 outfile = open(os.path.join(g.destination_dir, g.output_filename), 'w')
549     else:
550         usage(1, 'Too many arguments')
551
552     if (infile is sys.stdin) and sys.stdin.isatty():
553         if (outfile is sys.stdout) and sys.stdout.isatty():
554             usage()
555         usage(1, 'Filtering from console is forbidden')
556
557     if not g.host_name:
558         import socket
559         g.host_name = socket.gethostname()
560
561     g.outfile = outfile
562     output = outfile.write
563
564     msg = email.message_from_file(infile)
565
566     for header, value in g.set_header_value:
567         msg[header] = value
568
569     for header, param, value in g.set_header_param:
570         if header in msg:
571             msg.set_param(param, value, header)
572
573     try:
574         decode_message(msg)
575     finally:
576         infile.close()
577         outfile.close()