]> git.phdru.name Git - mimedecode.git/blob - mimedecode.py
Use != instead of <> for Python 3 compatibility
[mimedecode.git] / mimedecode.py
1 #! /usr/bin/env python
2 """Decode MIME message"""
3
4 import sys, os
5 from mimedecode_version import __version__, \
6     __author__, __copyright__, __license__
7
8 me = os.path.basename(sys.argv[0])
9
10
11 def version(exit=1):
12     sys.stdout.write("""\
13 Broytman mimedecode.py version %s, %s
14 """ % (__version__, __copyright__))
15     if exit: sys.exit(0)
16
17 def usage(code=0, errormsg=''):
18     version(0)
19     sys.stdout.write("""\
20         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]]
21 """ % me)
22     if errormsg:
23         sys.stderr.write(errormsg + os.linesep)
24     sys.exit(code)
25
26
27 def output_headers(msg):
28     unix_from = msg.get_unixfrom()
29     if unix_from:
30         output(unix_from + os.linesep)
31     for key, value in msg.items():
32         output("%s: %s%s" % (key, value, os.linesep))
33     output(os.linesep) # End of headers
34
35
36 def recode_if_needed(s, charset):
37     if charset and charset.lower() != g.default_encoding:
38         s = unicode(s, charset, "replace").encode(g.default_encoding, "replace")
39     return s
40
41
42 def _decode_header(s):
43     """Return a decoded string according to RFC 2047.
44     NOTE: This is almost the same as email.Utils.decode.
45     """
46     import email.Header
47
48     L = email.Header.decode_header(s)
49     if not isinstance(L, list):
50         # s wasn't decoded
51         return s
52
53     rtn = []
54     for atom, charset in L:
55         if charset is None:
56             rtn.append(atom)
57         else:
58             rtn.append(recode_if_needed(atom, charset))
59         rtn.append(' ')
60     del rtn[-1] # remove the last space
61
62     # Now that we've decoded everything, we just need to join all the parts
63     # together into the final string.
64     return ''.join(rtn)
65
66 def decode_header(msg, header):
67     "Decode mail header (if exists) and put it back, if it was encoded"
68
69     if msg.has_key(header):
70         value = msg[header]
71         new_value = _decode_header(value)
72         if new_value != value: # do not bother to touch msg if not changed
73             set_header(msg, header, new_value)
74
75
76 def decode_header_param(msg, header, param):
77     "Decode mail header's parameter (if exists) and put it back, if it was encoded"
78
79     if msg.has_key(header):
80         value = msg.get_param(param, header=header)
81         if value:
82             if isinstance(value, tuple):
83                 new_value = recode_if_needed(value[2], value[0])
84             else:
85                 new_value = _decode_header(value)
86             if new_value != value: # do not bother to touch msg if not changed
87                 msg.set_param(param, new_value, header)
88
89
90 def _get_exceptions(list):
91     return [x[1:].lower() for x in list[1:] if x[0]=='-']
92
93 def _decode_headers_params(msg, header, decode_all_params, param_list):
94     if decode_all_params:
95         params = msg.get_params(header=header)
96         if params:
97             for param, value in params:
98                 if param not in param_list:
99                     decode_header_param(msg, header, param)
100     else:
101         for param in param_list:
102             decode_header_param(msg, header, param)
103
104 def _remove_headers_params(msg, header, remove_all_params, param_list):
105     if remove_all_params:
106         params = msg.get_params(header=header)
107         if params:
108             if param_list:
109                 for param, value in params:
110                     if param not in param_list:
111                         msg.del_param(param, header)
112             else:
113                 value = msg[header]
114                 if value is None: # No such header
115                     return
116                 if ';' not in value: # There are no parameters
117                     return
118                 del msg[header] # Delete all such headers
119                 # Get the value without parameters and set it back
120                 msg[header] = value.split(';')[0].strip()
121     else:
122         for param in param_list:
123             msg.del_param(param, header)
124
125 def decode_headers(msg):
126     "Decode message headers according to global options"
127
128     for header_list in g.remove_headers:
129         header_list = header_list.split(',')
130         if header_list[0] == '*': # Remove all headers except listed
131             header_list = _get_exceptions(header_list)
132             for header in msg.keys():
133                 if header.lower() not in header_list:
134                     del msg[header]
135         else: # Remove listed headers
136             for header in header_list:
137                 del msg[header]
138
139     for header_list, param_list in g.remove_headers_params:
140         header_list = header_list.split(',')
141         param_list = param_list.split(',')
142         remove_all_params = param_list[0] == '*' # Remove all params except listed
143         if remove_all_params:
144             param_list = _get_exceptions(param_list)
145         if header_list[0] == '*': # Remove for all headers except listed
146             header_list = _get_exceptions(header_list)
147             for header in msg.keys():
148                 if header.lower() not in header_list:
149                     _remove_headers_params(msg, header, remove_all_params, param_list)
150         else: # Decode for listed headers
151             for header in header_list:
152                 _remove_headers_params(msg, header, remove_all_params, param_list)
153
154     for header_list in g.decode_headers:
155         header_list = header_list.split(',')
156         if header_list[0] == '*': # Decode all headers except listed
157             header_list = _get_exceptions(header_list)
158             for header in msg.keys():
159                 if header.lower() not in header_list:
160                     decode_header(msg, header)
161         else: # Decode listed headers
162             for header in header_list:
163                 decode_header(msg, header)
164
165     for header_list, param_list in g.decode_header_params:
166         header_list = header_list.split(',')
167         param_list = param_list.split(',')
168         decode_all_params = param_list[0] == '*' # Decode all params except listed
169         if decode_all_params:
170             param_list = _get_exceptions(param_list)
171         if header_list[0] == '*': # Decode for all headers except listed
172             header_list = _get_exceptions(header_list)
173             for header in msg.keys():
174                 if header.lower() not in header_list:
175                     _decode_headers_params(msg, header, decode_all_params, param_list)
176         else: # Decode for listed headers
177             for header in header_list:
178                 _decode_headers_params(msg, header, decode_all_params, param_list)
179
180
181 def set_header(msg, header, value):
182     "Replace header"
183
184     if msg.has_key(header):
185         msg.replace_header(header, value)
186     else:
187         msg[header] = value
188
189
190 def set_content_type(msg, newtype, charset=None):
191     msg.set_type(newtype)
192
193     if charset:
194         msg.set_param("charset", charset, "Content-Type")
195
196
197 caps = None # Globally stored mailcap database; initialized only if needed
198
199 def decode_body(msg, s):
200     "Decode body to plain text using first copiousoutput filter from mailcap"
201
202     import mailcap, tempfile
203
204     global caps
205     if caps is None:
206         caps = mailcap.getcaps()
207
208     content_type = msg.get_content_type()
209     filename = tempfile.mktemp()
210     command = None
211
212     entries = mailcap.lookup(caps, content_type, "view")
213     for entry in entries:
214         if entry.has_key('copiousoutput'):
215             if entry.has_key('test'):
216                 test = mailcap.subst(entry['test'], content_type, filename)
217                 if test and os.system(test) != 0:
218                     continue
219             command = mailcap.subst(entry["view"], content_type, filename)
220             break
221
222     if not command:
223         return s
224
225     outfile = open(filename, 'wb')
226     outfile.write(s)
227     outfile.close()
228
229     pipe = os.popen(command, 'r')
230     s = pipe.read()
231     pipe.close()
232     os.remove(filename)
233
234     set_content_type(msg, "text/plain")
235     msg["X-MIME-Autoconverted"] = "from %s to text/plain by %s id %s" % (content_type, g.host_name, command.split()[0])
236
237     return s
238
239
240 def recode_charset(msg, s):
241     "Recode charset of the message to the default charset"
242
243     save_charset = charset = msg.get_content_charset()
244     if charset and charset.lower() != g.default_encoding:
245         s = recode_if_needed(s, charset)
246         content_type = msg.get_content_type()
247         set_content_type(msg, content_type, g.default_encoding)
248         msg["X-MIME-Autoconverted"] = "from %s to %s by %s id %s" % (save_charset, g.default_encoding, g.host_name, me)
249     return s
250
251
252 def totext(msg, instring):
253     "Convert instring content to text"
254
255     # Decode body and recode charset
256     s = decode_body(msg, instring)
257     if g.recode_charset:
258         s = recode_charset(msg, s)
259
260     output_headers(msg)
261     output(s)
262     return s
263
264
265 mimetypes = None
266
267 def _guess_extension(ctype):
268     global mimetypes
269     if mimetypes is None:
270         import mimetypes
271         mimetypes.init()
272         user_mime_type = os.path.expanduser('~/.mime.types')
273         if os.path.exists(user_mime_type):
274             mimetypes._db.read(user_mime_type)
275     return mimetypes.guess_extension(ctype)
276
277 def _save_message(msg, outstring, save_headers=False, save_body=False):
278     for header, param in (
279         ("Content-Disposition", "filename"),
280         ("Content-Type", "name"),
281     ):
282         fname = msg.get_param(param, header=header)
283         if fname:
284             if isinstance(fname, tuple):
285                 fname = fname[2] # Do not recode if it isn't recoded yet
286             try:
287                     for forbidden in chr(0), '/', '\\':
288                         if forbidden in fname:
289                             raise ValueError
290             except ValueError:
291                 continue
292             fname = '-' + fname
293             break
294     else:
295         fname = ''
296     g.save_counter += 1
297     fname = str(g.save_counter) + fname
298     if '.' not in fname:
299         ext = _guess_extension(msg.get_content_type())
300         if ext: fname += ext
301
302     global output
303     save_output = output
304     outfile = open_output_file(fname)
305     output = outfile.write
306     if save_headers:
307         output_headers(msg)
308     if save_body:
309         output(outstring)
310     outfile.close()
311     output = save_output
312
313
314 def decode_part(msg):
315     "Decode one part of the message"
316
317     decode_headers(msg)
318
319     # Test all mask lists and find what to do with this content type
320     masks = []
321     ctype = msg.get_content_type()
322     if ctype:
323         masks.append(ctype)
324         mtype = ctype.split('/')[0]
325         masks.append(mtype + '/*')
326     masks.append('*/*')
327
328     left_binary = False
329     for content_type in masks:
330         if content_type in g.totext_mask or \
331            content_type in g.decoded_binary_mask:
332             break
333         elif content_type in g.binary_mask:
334             left_binary = True
335             break
336         elif content_type in g.fully_ignore_mask:
337             return
338
339     encoding = msg["Content-Transfer-Encoding"]
340     if left_binary or encoding in (None, '', '7bit', '8bit', 'binary'):
341         outstring = msg.get_payload()
342     else: # Decode from transfer ecoding to text or binary form
343         outstring = msg.get_payload(decode=1)
344         set_header(msg, "Content-Transfer-Encoding", "8bit")
345         msg["X-MIME-Autoconverted"] = "from %s to 8bit by %s id %s" % (encoding, g.host_name, me)
346
347     for content_type in masks:
348         if content_type in g.totext_mask:
349             outstring = totext(msg, outstring)
350             break
351         elif content_type in g.binary_mask or \
352              content_type in g.decoded_binary_mask:
353             output_headers(msg)
354             output(outstring)
355             break
356         elif content_type in g.ignore_mask:
357             output_headers(msg)
358             output("%sMessage body of type %s skipped.%s" % (os.linesep, ctype, os.linesep))
359             break
360         elif content_type in g.error_mask:
361             break
362     else:
363         # Neither content type nor masks were listed - decode by default
364         outstring = totext(msg, outstring)
365
366     for content_type in masks:
367         if content_type in g.save_headers_mask:
368             _save_message(msg, outstring, save_headers=True, save_body=False)
369         if content_type in g.save_body_mask:
370             _save_message(msg, outstring, save_headers=False, save_body=True)
371         if content_type in g.save_message_mask:
372             _save_message(msg, outstring, save_headers=True, save_body=True)
373
374     for content_type in masks:
375         if content_type in g.error_mask:
376             raise ValueError, "content type %s prohibited" % ctype
377
378 def decode_multipart(msg):
379     "Decode multipart"
380
381     decode_headers(msg)
382     boundary = msg.get_boundary()
383
384     masks = []
385     ctype = msg.get_content_type()
386     if ctype:
387         masks.append(ctype)
388         mtype = ctype.split('/')[0]
389         masks.append(mtype + '/*')
390     masks.append('*/*')
391
392     for content_type in masks:
393         if content_type in g.fully_ignore_mask:
394             return
395         elif content_type in g.ignore_mask:
396             output_headers(msg)
397             output("%sMessage body of type %s skipped.%s" % (os.linesep, ctype, os.linesep))
398             if boundary:
399                 output("%s--%s--%s" % (os.linesep, boundary, os.linesep))
400             return
401
402     for content_type in masks:
403         if content_type in g.save_body_mask or \
404                 content_type in g.save_message_mask:
405             _out_l = []
406             first_subpart = True
407             for subpart in msg.get_payload():
408                 if first_subpart:
409                     first_subpart = False
410                 else:
411                     _out_l.append(os.linesep)
412                 _out_l.append("--%s%s" % (boundary, os.linesep))
413                 _out_l.append(subpart.as_string())
414             _out_l.append("%s--%s--%s" % (os.linesep, boundary, os.linesep))
415             outstring = ''.join(_out_l)
416             break
417     else:
418         outstring = None
419
420     for content_type in masks:
421         if content_type in g.save_headers_mask:
422             _save_message(msg, outstring, save_headers=True, save_body=False)
423         if content_type in g.save_body_mask:
424             _save_message(msg, outstring, save_headers=False, save_body=True)
425         if content_type in g.save_message_mask:
426             _save_message(msg, outstring, save_headers=True, save_body=True)
427
428     for content_type in masks:
429         if content_type in g.error_mask:
430             raise ValueError, "content type %s prohibited" % ctype
431
432     output_headers(msg)
433
434     if msg.preamble: # Preserve the first part, it is probably not a RFC822-message
435         output(msg.preamble) # Usually it is just a few lines of text (MIME warning)
436     if msg.preamble is not None:
437         output(os.linesep)
438
439     first_subpart = True
440     for subpart in msg.get_payload():
441         if boundary:
442             if first_subpart:
443                 first_subpart = False
444             else:
445                 output(os.linesep)
446             output("--%s%s" % (boundary, os.linesep))
447
448         # Recursively decode all parts of the subpart
449         decode_message(subpart)
450
451     if boundary:
452         output("%s--%s--%s" % (os.linesep, boundary, os.linesep))
453
454     if msg.epilogue:
455         output(msg.epilogue)
456
457
458 def decode_message(msg):
459     "Decode message"
460
461     if msg.is_multipart():
462         decode_multipart(msg)
463     elif len(msg): # Simple one-part message (there are headers) - decode it
464         decode_part(msg)
465     else: # Not a message, just text - copy it literally
466         output(msg.as_string())
467
468
469 def open_output_file(filename):
470     fullpath = os.path.abspath(os.path.join(g.destination_dir, filename))
471     full_dir = os.path.dirname(fullpath)
472     create = not os.path.isdir(full_dir)
473     if create:
474         os.makedirs(full_dir)
475     try:
476         return open(fullpath, 'wb')
477     except:
478         if create:
479             os.removedirs(full_dir)
480
481
482 class GlobalOptions:
483     from m_lib.defenc import default_encoding
484     recode_charset = 1 # recode charset of message body
485
486     host_name = None
487
488     # A list of headers to decode
489     decode_headers = ["From", "To", "Cc", "Reply-To", "Mail-Followup-To",
490                       "Subject"]
491
492     # A list of headers parameters to decode
493     decode_header_params = [
494         ("Content-Type", "name"),
495         ("Content-Disposition", "filename"),
496     ]
497
498     # A list of headers to remove
499     remove_headers = []
500     # A list of headers parameters to remove
501     remove_headers_params = []
502
503     # A list of header/value pairs to set
504     set_header_value = []
505     # A list of header/parameter/value triples to set
506     set_header_param = []
507
508     totext_mask = [] # A list of content-types to decode
509     binary_mask = [] # A list of content-types to pass through
510     decoded_binary_mask = [] # A list of content-types to pass through (content-transfer-decoded)
511     ignore_mask = [] # Ignore (do not decode and do not include into output) but output a warning instead of the body
512     fully_ignore_mask = [] # Completely ignore - no headers, no body, no warning
513     error_mask = []  # Raise error if encounter one of these
514
515     save_counter = 0
516     save_headers_mask = []
517     save_body_mask = []
518     save_message_mask = []
519
520     input_filename = None
521     output_filename = None
522     destination_dir = os.curdir
523
524 g = GlobalOptions
525
526
527 def get_opts():
528     from getopt import getopt, GetoptError
529
530     try:
531         options, arguments = getopt(sys.argv[1:],
532             'hVcCDPH:f:d:p:r:R:b:B:e:I:i:t:O:o:',
533             ['help', 'version', 'host=',
534              'save-headers=', 'save-body=', 'save-message=',
535              'set-header=', 'set-param='])
536     except GetoptError:
537         usage(1)
538
539     for option, value in options:
540         if option in ('-h', '--help'):
541             usage()
542         elif option in ('-V', '--version'):
543             version()
544         elif option == '-c':
545             g.recode_charset = 1
546         elif option == '-C':
547             g.recode_charset = 0
548         elif option in ('-H', '--host'):
549             g.host_name = value
550         elif option == '-f':
551             g.default_encoding = value
552         elif option == '-d':
553             if value.startswith('*'):
554                 g.decode_headers = []
555             g.decode_headers.append(value)
556         elif option == '-D':
557             g.decode_headers = []
558         elif option == '-p':
559             g.decode_header_params.append(value.split(':', 1))
560         elif option == '-P':
561             g.decode_header_params = []
562         elif option == '-r':
563             g.remove_headers.append(value)
564         elif option == '-R':
565             g.remove_headers_params.append(value.split(':', 1))
566         elif option == '--set-header':
567             g.set_header_value.append(value.split(':', 1))
568         elif option == '--set-param':
569             header, value = value.split(':', 1)
570             if '=' in value:
571                 param, value = value.split('=', 1)
572             else:
573                 param, value = value.split(':', 1)
574             g.set_header_param.append((header, param, value))
575         elif option == '-t':
576             g.totext_mask.append(value)
577         elif option == '-B':
578             g.binary_mask.append(value)
579         elif option == '-b':
580             g.decoded_binary_mask.append(value)
581         elif option == '-I':
582             g.fully_ignore_mask.append(value)
583         elif option == '-i':
584             g.ignore_mask.append(value)
585         elif option == '-e':
586             g.error_mask.append(value)
587         elif option == '--save-headers':
588             g.save_headers_mask.append(value)
589         elif option == '--save-body':
590             g.save_body_mask.append(value)
591         elif option == '--save-message':
592             g.save_message_mask.append(value)
593         elif option == '-O':
594             g.destination_dir = value
595         elif option == '-o':
596             g.output_filename = value
597         else:
598             usage(1)
599
600     return arguments
601
602
603 if __name__ == "__main__":
604     arguments = get_opts()
605
606     la = len(arguments)
607     if la == 0:
608         g.input_filename = '-'
609         infile = sys.stdin
610         if g.output_filename:
611             outfile = open_output_file(g.output_filename)
612         else:
613             g.output_filename = '-'
614             outfile = sys.stdout
615     elif la in (1, 2):
616         if (arguments[0] == '-'):
617             g.input_filename = '-'
618             infile = sys.stdin
619         else:
620             g.input_filename = arguments[0]
621             infile = open(arguments[0], 'r')
622         if la == 1:
623             if g.output_filename:
624                 outfile = open_output_file(g.output_filename)
625             else:
626                 g.output_filename = '-'
627                 outfile = sys.stdout
628         elif la == 2:
629             if g.output_filename:
630                 usage(1, 'Too many output filenames')
631             if (arguments[1] == '-'):
632                 g.output_filename = '-'
633                 outfile = sys.stdout
634             else:
635                 g.output_filename = arguments[1]
636                 outfile = open_output_file(g.output_filename)
637     else:
638         usage(1, 'Too many arguments')
639
640     if (infile is sys.stdin) and sys.stdin.isatty():
641         if (outfile is sys.stdout) and sys.stdout.isatty():
642             usage()
643         usage(1, 'Filtering from console is forbidden')
644
645     if not g.host_name:
646         import socket
647         g.host_name = socket.gethostname()
648
649     g.outfile = outfile
650     output = outfile.write
651
652     import email
653     msg = email.message_from_file(infile)
654
655     for header, value in g.set_header_value:
656         set_header(msg, header, value)
657
658     for header, param, value in g.set_header_param:
659         if header in msg:
660             msg.set_param(param, value, header)
661
662     try:
663         decode_message(msg)
664     finally:
665         infile.close()
666         outfile.close()