blob: baf9379f537a52eba04713ee6aaea76f84b738ed [file] [log] [blame]
Guido van Rossum01ca3361992-07-13 14:28:59 +00001# Various tools used by MIME-reading or MIME-writing programs.
2
3
Guido van Rossumb6775db1994-08-01 11:34:53 +00004import os
Guido van Rossum01ca3361992-07-13 14:28:59 +00005import rfc822
Guido van Rossumb6775db1994-08-01 11:34:53 +00006import string
7import tempfile
Guido van Rossum01ca3361992-07-13 14:28:59 +00008
9
10# A derived class of rfc822.Message that knows about MIME headers and
11# contains some hooks for decoding encoded and multipart messages.
12
13class Message(rfc822.Message):
14
Guido van Rossum87555821995-08-07 20:13:56 +000015 def __init__(self, fp, seekable = 1):
16 rfc822.Message.__init__(self, fp, seekable)
Guido van Rossum01ca3361992-07-13 14:28:59 +000017 self.encodingheader = \
Guido van Rossum43245361995-08-29 19:25:11 +000018 self.getheader('content-transfer-encoding')
Guido van Rossum01ca3361992-07-13 14:28:59 +000019 self.typeheader = \
20 self.getheader('content-type')
21 self.parsetype()
22 self.parseplist()
Guido van Rossum01ca3361992-07-13 14:28:59 +000023
24 def parsetype(self):
25 str = self.typeheader
26 if str == None:
27 str = 'text/plain'
28 if ';' in str:
29 i = string.index(str, ';')
30 self.plisttext = str[i:]
31 str = str[:i]
32 else:
33 self.plisttext = ''
34 fields = string.splitfields(str, '/')
35 for i in range(len(fields)):
36 fields[i] = string.lower(string.strip(fields[i]))
37 self.type = string.joinfields(fields, '/')
38 self.maintype = fields[0]
39 self.subtype = string.joinfields(fields[1:], '/')
40
41 def parseplist(self):
42 str = self.plisttext
43 self.plist = []
44 while str[:1] == ';':
45 str = str[1:]
46 if ';' in str:
47 # XXX Should parse quotes!
48 end = string.index(str, ';')
49 else:
50 end = len(str)
51 f = str[:end]
52 if '=' in f:
53 i = string.index(f, '=')
54 f = string.lower(string.strip(f[:i])) + \
55 '=' + string.strip(f[i+1:])
56 self.plist.append(string.strip(f))
Guido van Rossumeacce121996-01-25 18:07:08 +000057 str = str[end:]
Guido van Rossum01ca3361992-07-13 14:28:59 +000058
59 def getplist(self):
60 return self.plist
61
62 def getparam(self, name):
63 name = string.lower(name) + '='
64 n = len(name)
65 for p in self.plist:
66 if p[:n] == name:
67 return rfc822.unquote(p[n:])
68 return None
69
70 def getencoding(self):
71 if self.encodingheader == None:
72 return '7bit'
Guido van Rossumb6775db1994-08-01 11:34:53 +000073 return string.lower(self.encodingheader)
Guido van Rossum01ca3361992-07-13 14:28:59 +000074
75 def gettype(self):
76 return self.type
77
78 def getmaintype(self):
79 return self.maintype
80
81 def getsubtype(self):
82 return self.subtype
83
84
85
86
87# Utility functions
88# -----------------
89
90
91# Return a random string usable as a multipart boundary.
92# The method used is so that it is *very* unlikely that the same
93# string of characters will every occur again in the Universe,
94# so the caller needn't check the data it is packing for the
95# occurrence of the boundary.
96#
97# The boundary contains dots so you have to quote it in the header.
98
99_prefix = None
100
101def choose_boundary():
Guido van Rossum8460b941996-05-28 22:59:58 +0000102 global _prefix
Guido van Rossum01ca3361992-07-13 14:28:59 +0000103 import time
104 import rand
105 if _prefix == None:
106 import socket
107 import os
108 hostid = socket.gethostbyname(socket.gethostname())
Guido van Rossum0c8cf881996-08-26 16:40:20 +0000109 try:
110 uid = `os.getuid()`
111 except:
112 uid = '1'
113 try:
114 pid = `os.getpid()`
115 except:
116 pid = '1'
Guido van Rossum01ca3361992-07-13 14:28:59 +0000117 seed = `rand.rand()`
118 _prefix = hostid + '.' + uid + '.' + pid
Guido van Rossumfea2af11993-01-04 09:16:51 +0000119 timestamp = `int(time.time())`
Guido van Rossum01ca3361992-07-13 14:28:59 +0000120 seed = `rand.rand()`
121 return _prefix + '.' + timestamp + '.' + seed
Guido van Rossumb6775db1994-08-01 11:34:53 +0000122
123
124# Subroutines for decoding some common content-transfer-types
125
126# XXX This requires that uudecode and mmencode are in $PATH
127
128def decode(input, output, encoding):
129 if decodetab.has_key(encoding):
130 pipethrough(input, decodetab[encoding], output)
131 else:
132 raise ValueError, \
133 'unknown Content-Transfer-Encoding: %s' % encoding
134
135def encode(input, output, encoding):
136 if encodetab.has_key(encoding):
137 pipethrough(input, encodetab[encoding], output)
138 else:
139 raise ValueError, \
140 'unknown Content-Transfer-Encoding: %s' % encoding
141
142uudecode_pipe = '''(
143TEMP=/tmp/@uu.$$
144sed "s%^begin [0-7][0-7]* .*%begin 600 $TEMP%" | uudecode
145cat $TEMP
146rm $TEMP
147)'''
148
149decodetab = {
150 'uuencode': uudecode_pipe,
151 'x-uuencode': uudecode_pipe,
152 'quoted-printable': 'mmencode -u -q',
153 'base64': 'mmencode -u -b',
154}
155
156encodetab = {
157 'x-uuencode': 'uuencode tempfile',
158 'uuencode': 'uuencode tempfile',
159 'quoted-printable': 'mmencode -q',
160 'base64': 'mmencode -b',
161}
162
163def pipeto(input, command):
164 pipe = os.popen(command, 'w')
165 copyliteral(input, pipe)
166 pipe.close()
167
168def pipethrough(input, command, output):
169 tempname = tempfile.mktemp()
170 try:
171 temp = open(tempname, 'w')
172 except IOError:
173 print '*** Cannot create temp file', `tempname`
174 return
175 copyliteral(input, temp)
176 temp.close()
177 pipe = os.popen(command + ' <' + tempname, 'r')
178 copybinary(pipe, output)
179 pipe.close()
180 os.unlink(tempname)
181
182def copyliteral(input, output):
183 while 1:
184 line = input.readline()
185 if not line: break
186 output.write(line)
187
188def copybinary(input, output):
189 BUFSIZE = 8192
190 while 1:
191 line = input.read(BUFSIZE)
192 if not line: break
193 output.write(line)