]> code.delx.au - offlineimap/blob - offlineimap/imaplibutil.py
23ba654cb3e5ec217d328f1b1727d12ef08b5a25
[offlineimap] / offlineimap / imaplibutil.py
1 # imaplib utilities
2 # Copyright (C) 2002-2007 John Goerzen
3 # <jgoerzen@complete.org>
4 #
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 2 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program; if not, write to the Free Software
17 # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 import re, string, types, binascii, socket, time, random, subprocess, sys, os
20 from offlineimap.ui import UIBase
21 from imaplib import *
22
23 # Import the symbols we need that aren't exported by default
24 from imaplib import IMAP4_PORT, IMAP4_SSL_PORT, InternalDate, Mon2num
25
26
27 class IMAP4_Tunnel(IMAP4):
28 """IMAP4 client class over a tunnel
29
30 Instantiate with: IMAP4_Tunnel(tunnelcmd)
31
32 tunnelcmd -- shell command to generate the tunnel.
33 The result will be in PREAUTH stage."""
34
35 def __init__(self, tunnelcmd):
36 IMAP4.__init__(self, tunnelcmd)
37
38 def open(self, host, port):
39 """The tunnelcmd comes in on host!"""
40 self.process = subprocess.Popen(host, shell=True, close_fds=True,
41 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
42 (self.outfd, self.infd) = (self.process.stdin, self.process.stdout)
43
44 def read(self, size):
45 retval = ''
46 while len(retval) < size:
47 retval += self.infd.read(size - len(retval))
48 return retval
49
50 def readline(self):
51 return self.infd.readline()
52
53 def send(self, data):
54 self.outfd.write(data)
55
56 def shutdown(self):
57 self.infd.close()
58 self.outfd.close()
59 self.process.wait()
60
61 class sslwrapper:
62 def __init__(self, sslsock):
63 self.sslsock = sslsock
64 self.readbuf = ''
65
66 def write(self, s):
67 return self.sslsock.write(s)
68
69 def _read(self, n):
70 return self.sslsock.read(n)
71
72 def read(self, n):
73 if len(self.readbuf):
74 # Return the stuff in readbuf, even if less than n.
75 # It might contain the rest of the line, and if we try to
76 # read more, might block waiting for data that is not
77 # coming to arrive.
78 bytesfrombuf = min(n, len(self.readbuf))
79 retval = self.readbuf[:bytesfrombuf]
80 self.readbuf = self.readbuf[bytesfrombuf:]
81 return retval
82 retval = self._read(n)
83 if len(retval) > n:
84 self.readbuf = retval[n:]
85 return retval[:n]
86 return retval
87
88 def readline(self):
89 retval = ''
90 while 1:
91 linebuf = self.read(1024)
92 nlindex = linebuf.find("\n")
93 if nlindex != -1:
94 retval += linebuf[:nlindex + 1]
95 self.readbuf = linebuf[nlindex + 1:] + self.readbuf
96 return retval
97 else:
98 retval += linebuf
99
100 def new_mesg(self, s, secs=None):
101 if secs is None:
102 secs = time.time()
103 tm = time.strftime('%M:%S', time.localtime(secs))
104 UIBase.getglobalui().debug('imap', ' %s.%02d %s' % (tm, (secs*100)%100, s))
105
106 class WrappedIMAP4_SSL(IMAP4_SSL):
107 def open(self, host = '', port = IMAP4_SSL_PORT):
108 IMAP4_SSL.open(self, host, port)
109 self.sslobj = sslwrapper(self.sslobj)
110
111 def readline(self):
112 return self.sslobj.readline()
113
114 def new_open(self, host = '', port = IMAP4_PORT):
115 """Setup connection to remote server on "host:port"
116 (default: localhost:standard IMAP4 port).
117 This connection will be used by the routines:
118 read, readline, send, shutdown.
119 """
120 self.host = host
121 self.port = port
122 res = socket.getaddrinfo(host, port, socket.AF_UNSPEC,
123 socket.SOCK_STREAM)
124
125 # Try each address returned by getaddrinfo in turn until we
126 # manage to connect to one.
127 # Try all the addresses in turn until we connect()
128 last_error = 0
129 for remote in res:
130 af, socktype, proto, canonname, sa = remote
131 self.sock = socket.socket(af, socktype, proto)
132 last_error = self.sock.connect_ex(sa)
133 if last_error == 0:
134 break
135 else:
136 self.sock.close()
137 if last_error != 0:
138 # FIXME
139 raise socket.error(last_error)
140 self.file = self.sock.makefile('rb')
141
142 def new_open_ssl(self, host = '', port = IMAP4_SSL_PORT):
143 """Setup connection to remote server on "host:port".
144 (default: localhost:standard IMAP4 SSL port).
145 This connection will be used by the routines:
146 read, readline, send, shutdown.
147 """
148 self.host = host
149 self.port = port
150 #This connects to the first ip found ipv4/ipv6
151 #Added by Adriaan Peeters <apeeters@lashout.net> based on a socket
152 #example from the python documentation:
153 #http://www.python.org/doc/lib/socket-example.html
154 res = socket.getaddrinfo(host, port, socket.AF_UNSPEC,
155 socket.SOCK_STREAM)
156 # Try all the addresses in turn until we connect()
157 last_error = 0
158 for remote in res:
159 af, socktype, proto, canonname, sa = remote
160 self.sock = socket.socket(af, socktype, proto)
161 last_error = self.sock.connect_ex(sa)
162 if last_error == 0:
163 break
164 else:
165 self.sock.close()
166 if last_error != 0:
167 # FIXME
168 raise socket.error(last_error)
169 if sys.version_info[0] <= 2 and sys.version_info[1] <= 2:
170 self.sslobj = socket.ssl(self.sock, self.keyfile, self.certfile)
171 else:
172 self.sslobj = socket.ssl(self.sock._sock, self.keyfile, self.certfile)
173 self.sslobj = sslwrapper(self.sslobj)
174
175 mustquote = re.compile(r"[^\w!#$%&'+,.:;<=>?^`|~-]")
176
177 def Internaldate2epoch(resp):
178 """Convert IMAP4 INTERNALDATE to UT.
179
180 Returns seconds since the epoch.
181 """
182
183 mo = InternalDate.match(resp)
184 if not mo:
185 return None
186
187 mon = Mon2num[mo.group('mon')]
188 zonen = mo.group('zonen')
189
190 day = int(mo.group('day'))
191 year = int(mo.group('year'))
192 hour = int(mo.group('hour'))
193 min = int(mo.group('min'))
194 sec = int(mo.group('sec'))
195 zoneh = int(mo.group('zoneh'))
196 zonem = int(mo.group('zonem'))
197
198 # INTERNALDATE timezone must be subtracted to get UT
199
200 zone = (zoneh*60 + zonem)*60
201 if zonen == '-':
202 zone = -zone
203
204 tt = (year, mon, day, hour, min, sec, -1, -1, -1)
205
206 return time.mktime(tt)