blob: 8164ede97679c8bc427f32339438a2c96759e7bb [file] [log] [blame]
Benjamin Petersonbe17a112008-09-27 21:49:47 +00001"""Test script for ftplib module."""
2
Antoine Pitrouf988cd02009-11-17 20:21:14 +00003# Modified by Giampaolo Rodola' to test FTP class, IPv6 and TLS
4# environment
Benjamin Petersonbe17a112008-09-27 21:49:47 +00005
Guido van Rossumd8faa362007-04-27 19:54:29 +00006import ftplib
Benjamin Petersonbe17a112008-09-27 21:49:47 +00007import asyncore
8import asynchat
9import socket
10import io
Antoine Pitrouf988cd02009-11-17 20:21:14 +000011import errno
12import os
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +000013import time
Antoine Pitrouf988cd02009-11-17 20:21:14 +000014try:
15 import ssl
16except ImportError:
17 ssl = None
Guido van Rossumd8faa362007-04-27 19:54:29 +000018
19from unittest import TestCase
Benjamin Petersonee8712c2008-05-20 21:35:26 +000020from test import support
Benjamin Petersonbe17a112008-09-27 21:49:47 +000021from test.support import HOST
Victor Stinner45df8202010-04-28 22:31:17 +000022threading = support.import_module('threading')
Guido van Rossumd8faa362007-04-27 19:54:29 +000023
Benjamin Petersonbe17a112008-09-27 21:49:47 +000024# the dummy data returned by server over the data channel when
25# RETR, LIST and NLST commands are issued
26RETR_DATA = 'abcde12345\r\n' * 1000
27LIST_DATA = 'foo\r\nbar\r\n'
28NLST_DATA = 'foo\r\nbar\r\n'
Christian Heimes836baa52008-02-26 08:18:30 +000029
Christian Heimes836baa52008-02-26 08:18:30 +000030
Benjamin Petersonbe17a112008-09-27 21:49:47 +000031class DummyDTPHandler(asynchat.async_chat):
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +000032 dtp_conn_closed = False
Benjamin Petersonbe17a112008-09-27 21:49:47 +000033
34 def __init__(self, conn, baseclass):
35 asynchat.async_chat.__init__(self, conn)
36 self.baseclass = baseclass
37 self.baseclass.last_received_data = ''
38
39 def handle_read(self):
Giampaolo Rodolàf96482e2010-08-04 10:36:18 +000040 self.baseclass.last_received_data += self.recv(1024).decode('ascii')
Benjamin Petersonbe17a112008-09-27 21:49:47 +000041
42 def handle_close(self):
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +000043 # XXX: this method can be called many times in a row for a single
44 # connection, including in clear-text (non-TLS) mode.
45 # (behaviour witnessed with test_data_connection)
46 if not self.dtp_conn_closed:
47 self.baseclass.push('226 transfer complete')
48 self.close()
49 self.dtp_conn_closed = True
Benjamin Petersonbe17a112008-09-27 21:49:47 +000050
51 def push(self, what):
Giampaolo Rodolàf96482e2010-08-04 10:36:18 +000052 super(DummyDTPHandler, self).push(what.encode('ascii'))
Benjamin Petersonbe17a112008-09-27 21:49:47 +000053
Giampaolo Rodolàd930b632010-05-06 20:21:57 +000054 def handle_error(self):
55 raise
56
Benjamin Petersonbe17a112008-09-27 21:49:47 +000057
58class DummyFTPHandler(asynchat.async_chat):
59
Antoine Pitrouf988cd02009-11-17 20:21:14 +000060 dtp_handler = DummyDTPHandler
61
Benjamin Petersonbe17a112008-09-27 21:49:47 +000062 def __init__(self, conn):
63 asynchat.async_chat.__init__(self, conn)
64 self.set_terminator(b"\r\n")
65 self.in_buffer = []
66 self.dtp = None
67 self.last_received_cmd = None
68 self.last_received_data = ''
69 self.next_response = ''
Antoine Pitrou648bcd72009-11-27 13:23:26 +000070 self.rest = None
Benjamin Petersonbe17a112008-09-27 21:49:47 +000071 self.push('220 welcome')
72
73 def collect_incoming_data(self, data):
74 self.in_buffer.append(data)
75
76 def found_terminator(self):
77 line = b''.join(self.in_buffer).decode('ascii')
78 self.in_buffer = []
79 if self.next_response:
80 self.push(self.next_response)
81 self.next_response = ''
82 cmd = line.split(' ')[0].lower()
83 self.last_received_cmd = cmd
84 space = line.find(' ')
85 if space != -1:
86 arg = line[space + 1:]
87 else:
88 arg = ""
89 if hasattr(self, 'cmd_' + cmd):
90 method = getattr(self, 'cmd_' + cmd)
91 method(arg)
92 else:
93 self.push('550 command "%s" not understood.' %cmd)
94
95 def handle_error(self):
96 raise
97
98 def push(self, data):
99 asynchat.async_chat.push(self, data.encode('ascii') + b'\r\n')
100
101 def cmd_port(self, arg):
102 addr = list(map(int, arg.split(',')))
103 ip = '%d.%d.%d.%d' %tuple(addr[:4])
104 port = (addr[4] * 256) + addr[5]
105 s = socket.create_connection((ip, port), timeout=2)
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000106 self.dtp = self.dtp_handler(s, baseclass=self)
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000107 self.push('200 active data connection established')
108
109 def cmd_pasv(self, arg):
110 sock = socket.socket()
111 sock.bind((self.socket.getsockname()[0], 0))
112 sock.listen(5)
113 sock.settimeout(2)
114 ip, port = sock.getsockname()[:2]
115 ip = ip.replace('.', ','); p1 = port / 256; p2 = port % 256
116 self.push('227 entering passive mode (%s,%d,%d)' %(ip, p1, p2))
117 conn, addr = sock.accept()
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000118 self.dtp = self.dtp_handler(conn, baseclass=self)
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000119
120 def cmd_eprt(self, arg):
121 af, ip, port = arg.split(arg[0])[1:-1]
122 port = int(port)
123 s = socket.create_connection((ip, port), timeout=2)
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000124 self.dtp = self.dtp_handler(s, baseclass=self)
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000125 self.push('200 active data connection established')
126
127 def cmd_epsv(self, arg):
128 sock = socket.socket(socket.AF_INET6)
129 sock.bind((self.socket.getsockname()[0], 0))
130 sock.listen(5)
131 sock.settimeout(2)
132 port = sock.getsockname()[1]
133 self.push('229 entering extended passive mode (|||%d|)' %port)
134 conn, addr = sock.accept()
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000135 self.dtp = self.dtp_handler(conn, baseclass=self)
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000136
137 def cmd_echo(self, arg):
138 # sends back the received string (used by the test suite)
139 self.push(arg)
140
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000141 def cmd_noop(self, arg):
142 self.push('200 noop ok')
143
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000144 def cmd_user(self, arg):
145 self.push('331 username ok')
146
147 def cmd_pass(self, arg):
148 self.push('230 password ok')
149
150 def cmd_acct(self, arg):
151 self.push('230 acct ok')
152
153 def cmd_rnfr(self, arg):
154 self.push('350 rnfr ok')
155
156 def cmd_rnto(self, arg):
157 self.push('250 rnto ok')
158
159 def cmd_dele(self, arg):
160 self.push('250 dele ok')
161
162 def cmd_cwd(self, arg):
163 self.push('250 cwd ok')
164
165 def cmd_size(self, arg):
166 self.push('250 1000')
167
168 def cmd_mkd(self, arg):
169 self.push('257 "%s"' %arg)
170
171 def cmd_rmd(self, arg):
172 self.push('250 rmd ok')
173
174 def cmd_pwd(self, arg):
175 self.push('257 "pwd ok"')
176
177 def cmd_type(self, arg):
Giampaolo Rodolàf96482e2010-08-04 10:36:18 +0000178 self.push('200 type ok')
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000179
180 def cmd_quit(self, arg):
181 self.push('221 quit ok')
182 self.close()
183
184 def cmd_stor(self, arg):
185 self.push('125 stor ok')
186
Antoine Pitrou648bcd72009-11-27 13:23:26 +0000187 def cmd_rest(self, arg):
188 self.rest = arg
189 self.push('350 rest ok')
190
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000191 def cmd_retr(self, arg):
192 self.push('125 retr ok')
Antoine Pitrou648bcd72009-11-27 13:23:26 +0000193 if self.rest is not None:
194 offset = int(self.rest)
195 else:
196 offset = 0
Giampaolo Rodolàf96482e2010-08-04 10:36:18 +0000197 self.dtp.push(RETR_DATA[offset:])
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000198 self.dtp.close_when_done()
Antoine Pitrou648bcd72009-11-27 13:23:26 +0000199 self.rest = None
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000200
201 def cmd_list(self, arg):
202 self.push('125 list ok')
203 self.dtp.push(LIST_DATA)
204 self.dtp.close_when_done()
205
206 def cmd_nlst(self, arg):
207 self.push('125 nlst ok')
208 self.dtp.push(NLST_DATA)
209 self.dtp.close_when_done()
210
211
212class DummyFTPServer(asyncore.dispatcher, threading.Thread):
213
214 handler = DummyFTPHandler
215
216 def __init__(self, address, af=socket.AF_INET):
217 threading.Thread.__init__(self)
218 asyncore.dispatcher.__init__(self)
219 self.create_socket(af, socket.SOCK_STREAM)
220 self.bind(address)
221 self.listen(5)
222 self.active = False
223 self.active_lock = threading.Lock()
224 self.host, self.port = self.socket.getsockname()[:2]
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000225 self.handler_instance = None
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000226
227 def start(self):
228 assert not self.active
229 self.__flag = threading.Event()
230 threading.Thread.start(self)
231 self.__flag.wait()
232
233 def run(self):
234 self.active = True
235 self.__flag.set()
236 while self.active and asyncore.socket_map:
237 self.active_lock.acquire()
238 asyncore.loop(timeout=0.1, count=1)
239 self.active_lock.release()
240 asyncore.close_all(ignore_all=True)
241
242 def stop(self):
243 assert self.active
244 self.active = False
245 self.join()
246
247 def handle_accept(self):
248 conn, addr = self.accept()
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000249 self.handler_instance = self.handler(conn)
Benjamin Petersond06e3b02008-09-28 21:00:42 +0000250
251 def handle_connect(self):
252 self.close()
253 handle_read = handle_connect
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000254
255 def writable(self):
256 return 0
257
258 def handle_error(self):
259 raise
260
261
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000262if ssl is not None:
263
264 CERTFILE = os.path.join(os.path.dirname(__file__), "keycert.pem")
265
266 class SSLConnection(asyncore.dispatcher):
267 """An asyncore.dispatcher subclass supporting TLS/SSL."""
268
269 _ssl_accepting = False
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +0000270 _ssl_closing = False
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000271
272 def secure_connection(self):
273 self.del_channel()
274 socket = ssl.wrap_socket(self.socket, suppress_ragged_eofs=False,
275 certfile=CERTFILE, server_side=True,
276 do_handshake_on_connect=False,
277 ssl_version=ssl.PROTOCOL_SSLv23)
278 self.set_socket(socket)
279 self._ssl_accepting = True
280
281 def _do_ssl_handshake(self):
282 try:
283 self.socket.do_handshake()
284 except ssl.SSLError as err:
285 if err.args[0] in (ssl.SSL_ERROR_WANT_READ,
286 ssl.SSL_ERROR_WANT_WRITE):
287 return
288 elif err.args[0] == ssl.SSL_ERROR_EOF:
289 return self.handle_close()
290 raise
291 except socket.error as err:
292 if err.args[0] == errno.ECONNABORTED:
293 return self.handle_close()
294 else:
295 self._ssl_accepting = False
296
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +0000297 def _do_ssl_shutdown(self):
298 self._ssl_closing = True
299 try:
300 self.socket = self.socket.unwrap()
301 except ssl.SSLError as err:
302 if err.args[0] in (ssl.SSL_ERROR_WANT_READ,
303 ssl.SSL_ERROR_WANT_WRITE):
304 return
305 except socket.error as err:
306 # Any "socket error" corresponds to a SSL_ERROR_SYSCALL return
307 # from OpenSSL's SSL_shutdown(), corresponding to a
308 # closed socket condition. See also:
309 # http://www.mail-archive.com/openssl-users@openssl.org/msg60710.html
310 pass
311 self._ssl_closing = False
312 super(SSLConnection, self).close()
313
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000314 def handle_read_event(self):
315 if self._ssl_accepting:
316 self._do_ssl_handshake()
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +0000317 elif self._ssl_closing:
318 self._do_ssl_shutdown()
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000319 else:
320 super(SSLConnection, self).handle_read_event()
321
322 def handle_write_event(self):
323 if self._ssl_accepting:
324 self._do_ssl_handshake()
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +0000325 elif self._ssl_closing:
326 self._do_ssl_shutdown()
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000327 else:
328 super(SSLConnection, self).handle_write_event()
329
330 def send(self, data):
331 try:
332 return super(SSLConnection, self).send(data)
333 except ssl.SSLError as err:
Antoine Pitrou5733c082010-03-22 14:49:10 +0000334 if err.args[0] in (ssl.SSL_ERROR_EOF, ssl.SSL_ERROR_ZERO_RETURN,
335 ssl.SSL_ERROR_WANT_READ,
336 ssl.SSL_ERROR_WANT_WRITE):
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000337 return 0
338 raise
339
340 def recv(self, buffer_size):
341 try:
342 return super(SSLConnection, self).recv(buffer_size)
343 except ssl.SSLError as err:
Antoine Pitrou5733c082010-03-22 14:49:10 +0000344 if err.args[0] in (ssl.SSL_ERROR_WANT_READ,
345 ssl.SSL_ERROR_WANT_WRITE):
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +0000346 return b''
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000347 if err.args[0] in (ssl.SSL_ERROR_EOF, ssl.SSL_ERROR_ZERO_RETURN):
348 self.handle_close()
349 return b''
350 raise
351
352 def handle_error(self):
353 raise
354
355 def close(self):
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +0000356 if (isinstance(self.socket, ssl.SSLSocket) and
357 self.socket._sslobj is not None):
358 self._do_ssl_shutdown()
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000359
360
361 class DummyTLS_DTPHandler(SSLConnection, DummyDTPHandler):
362 """A DummyDTPHandler subclass supporting TLS/SSL."""
363
364 def __init__(self, conn, baseclass):
365 DummyDTPHandler.__init__(self, conn, baseclass)
366 if self.baseclass.secure_data_channel:
367 self.secure_connection()
368
369
370 class DummyTLS_FTPHandler(SSLConnection, DummyFTPHandler):
371 """A DummyFTPHandler subclass supporting TLS/SSL."""
372
373 dtp_handler = DummyTLS_DTPHandler
374
375 def __init__(self, conn):
376 DummyFTPHandler.__init__(self, conn)
377 self.secure_data_channel = False
378
379 def cmd_auth(self, line):
380 """Set up secure control channel."""
381 self.push('234 AUTH TLS successful')
382 self.secure_connection()
383
384 def cmd_pbsz(self, line):
385 """Negotiate size of buffer for secure data transfer.
386 For TLS/SSL the only valid value for the parameter is '0'.
387 Any other value is accepted but ignored.
388 """
389 self.push('200 PBSZ=0 successful.')
390
391 def cmd_prot(self, line):
392 """Setup un/secure data channel."""
393 arg = line.upper()
394 if arg == 'C':
395 self.push('200 Protection set to Clear')
396 self.secure_data_channel = False
397 elif arg == 'P':
398 self.push('200 Protection set to Private')
399 self.secure_data_channel = True
400 else:
401 self.push("502 Unrecognized PROT type (use C or P).")
402
403
404 class DummyTLS_FTPServer(DummyFTPServer):
405 handler = DummyTLS_FTPHandler
406
407
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000408class TestFTPClass(TestCase):
409
410 def setUp(self):
411 self.server = DummyFTPServer((HOST, 0))
412 self.server.start()
413 self.client = ftplib.FTP(timeout=2)
414 self.client.connect(self.server.host, self.server.port)
415
416 def tearDown(self):
417 self.client.close()
418 self.server.stop()
419
420 def test_getwelcome(self):
421 self.assertEqual(self.client.getwelcome(), '220 welcome')
422
423 def test_sanitize(self):
424 self.assertEqual(self.client.sanitize('foo'), repr('foo'))
425 self.assertEqual(self.client.sanitize('pass 12345'), repr('pass *****'))
426 self.assertEqual(self.client.sanitize('PASS 12345'), repr('PASS *****'))
427
428 def test_exceptions(self):
429 self.assertRaises(ftplib.error_temp, self.client.sendcmd, 'echo 400')
430 self.assertRaises(ftplib.error_temp, self.client.sendcmd, 'echo 499')
431 self.assertRaises(ftplib.error_perm, self.client.sendcmd, 'echo 500')
432 self.assertRaises(ftplib.error_perm, self.client.sendcmd, 'echo 599')
433 self.assertRaises(ftplib.error_proto, self.client.sendcmd, 'echo 999')
434
435 def test_all_errors(self):
436 exceptions = (ftplib.error_reply, ftplib.error_temp, ftplib.error_perm,
437 ftplib.error_proto, ftplib.Error, IOError, EOFError)
438 for x in exceptions:
439 try:
440 raise x('exception not included in all_errors set')
441 except ftplib.all_errors:
442 pass
443
444 def test_set_pasv(self):
445 # passive mode is supposed to be enabled by default
446 self.assertTrue(self.client.passiveserver)
447 self.client.set_pasv(True)
448 self.assertTrue(self.client.passiveserver)
449 self.client.set_pasv(False)
450 self.assertFalse(self.client.passiveserver)
451
452 def test_voidcmd(self):
453 self.client.voidcmd('echo 200')
454 self.client.voidcmd('echo 299')
455 self.assertRaises(ftplib.error_reply, self.client.voidcmd, 'echo 199')
456 self.assertRaises(ftplib.error_reply, self.client.voidcmd, 'echo 300')
457
458 def test_login(self):
459 self.client.login()
460
461 def test_acct(self):
462 self.client.acct('passwd')
463
464 def test_rename(self):
465 self.client.rename('a', 'b')
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000466 self.server.handler_instance.next_response = '200'
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000467 self.assertRaises(ftplib.error_reply, self.client.rename, 'a', 'b')
468
469 def test_delete(self):
470 self.client.delete('foo')
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000471 self.server.handler_instance.next_response = '199'
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000472 self.assertRaises(ftplib.error_reply, self.client.delete, 'foo')
473
474 def test_size(self):
475 self.client.size('foo')
476
477 def test_mkd(self):
478 dir = self.client.mkd('/foo')
479 self.assertEqual(dir, '/foo')
480
481 def test_rmd(self):
482 self.client.rmd('foo')
483
484 def test_pwd(self):
485 dir = self.client.pwd()
486 self.assertEqual(dir, 'pwd ok')
487
488 def test_quit(self):
489 self.assertEqual(self.client.quit(), '221 quit ok')
490 # Ensure the connection gets closed; sock attribute should be None
491 self.assertEqual(self.client.sock, None)
492
493 def test_retrbinary(self):
494 def callback(data):
495 received.append(data.decode('ascii'))
496 received = []
497 self.client.retrbinary('retr', callback)
498 self.assertEqual(''.join(received), RETR_DATA)
499
Antoine Pitrou648bcd72009-11-27 13:23:26 +0000500 def test_retrbinary_rest(self):
501 def callback(data):
502 received.append(data.decode('ascii'))
503 for rest in (0, 10, 20):
504 received = []
505 self.client.retrbinary('retr', callback, rest=rest)
506 self.assertEqual(''.join(received), RETR_DATA[rest:],
507 msg='rest test case %d %d %d' % (rest,
508 len(''.join(received)),
509 len(RETR_DATA[rest:])))
510
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000511 def test_retrlines(self):
512 received = []
513 self.client.retrlines('retr', received.append)
Giampaolo Rodolàf96482e2010-08-04 10:36:18 +0000514 self.assertEqual(''.join(received), RETR_DATA.replace('\r\n', ''))
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000515
516 def test_storbinary(self):
517 f = io.BytesIO(RETR_DATA.encode('ascii'))
518 self.client.storbinary('stor', f)
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000519 self.assertEqual(self.server.handler_instance.last_received_data, RETR_DATA)
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000520 # test new callback arg
521 flag = []
522 f.seek(0)
523 self.client.storbinary('stor', f, callback=lambda x: flag.append(None))
524 self.assertTrue(flag)
525
Antoine Pitrou648bcd72009-11-27 13:23:26 +0000526 def test_storbinary_rest(self):
527 f = io.BytesIO(RETR_DATA.replace('\r\n', '\n').encode('ascii'))
528 for r in (30, '30'):
529 f.seek(0)
530 self.client.storbinary('stor', f, rest=r)
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000531 self.assertEqual(self.server.handler_instance.rest, str(r))
Antoine Pitrou648bcd72009-11-27 13:23:26 +0000532
Giampaolo Rodolàf96482e2010-08-04 10:36:18 +0000533 def test_storlines(self):
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000534 f = io.BytesIO(RETR_DATA.replace('\r\n', '\n').encode('ascii'))
535 self.client.storlines('stor', f)
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000536 self.assertEqual(self.server.handler_instance.last_received_data, RETR_DATA)
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000537 # test new callback arg
538 flag = []
539 f.seek(0)
540 self.client.storlines('stor foo', f, callback=lambda x: flag.append(None))
541 self.assertTrue(flag)
542
543 def test_nlst(self):
544 self.client.nlst()
545 self.assertEqual(self.client.nlst(), NLST_DATA.split('\r\n')[:-1])
546
547 def test_dir(self):
548 l = []
549 self.client.dir(lambda x: l.append(x))
550 self.assertEqual(''.join(l), LIST_DATA.replace('\r\n', ''))
551
Benjamin Peterson3a53fbb2008-09-27 22:04:16 +0000552 def test_makeport(self):
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000553 self.client.makeport()
554 # IPv4 is in use, just make sure send_eprt has not been used
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000555 self.assertEqual(self.server.handler_instance.last_received_cmd, 'port')
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000556
557 def test_makepasv(self):
558 host, port = self.client.makepasv()
559 conn = socket.create_connection((host, port), 2)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000560 conn.close()
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000561 # IPv4 is in use, just make sure send_epsv has not been used
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000562 self.assertEqual(self.server.handler_instance.last_received_cmd, 'pasv')
563
564 def test_with_statement(self):
565 self.client.quit()
566
567 def is_client_connected():
568 if self.client.sock is None:
569 return False
570 try:
571 self.client.sendcmd('noop')
572 except (socket.error, EOFError):
573 return False
574 return True
575
576 # base test
577 with ftplib.FTP(timeout=2) as self.client:
578 self.client.connect(self.server.host, self.server.port)
579 self.client.sendcmd('noop')
580 self.assertTrue(is_client_connected())
581 self.assertEqual(self.server.handler_instance.last_received_cmd, 'quit')
582 self.assertFalse(is_client_connected())
583
584 # QUIT sent inside the with block
585 with ftplib.FTP(timeout=2) as self.client:
586 self.client.connect(self.server.host, self.server.port)
587 self.client.sendcmd('noop')
588 self.client.quit()
589 self.assertEqual(self.server.handler_instance.last_received_cmd, 'quit')
590 self.assertFalse(is_client_connected())
591
592 # force a wrong response code to be sent on QUIT: error_perm
593 # is expected and the connection is supposed to be closed
594 try:
595 with ftplib.FTP(timeout=2) as self.client:
596 self.client.connect(self.server.host, self.server.port)
597 self.client.sendcmd('noop')
598 self.server.handler_instance.next_response = '550 error on quit'
599 except ftplib.error_perm as err:
600 self.assertEqual(str(err), '550 error on quit')
601 else:
602 self.fail('Exception not raised')
603 # needed to give the threaded server some time to set the attribute
604 # which otherwise would still be == 'noop'
605 time.sleep(0.1)
606 self.assertEqual(self.server.handler_instance.last_received_cmd, 'quit')
607 self.assertFalse(is_client_connected())
Guido van Rossumd8faa362007-04-27 19:54:29 +0000608
Giampaolo Rodolàbbc47822010-08-23 22:10:32 +0000609 def test_parse257(self):
610 self.assertEqual(ftplib.parse257('257 "/foo/bar"'), '/foo/bar')
611 self.assertEqual(ftplib.parse257('257 "/foo/bar" created'), '/foo/bar')
612 self.assertEqual(ftplib.parse257('257 ""'), '')
613 self.assertEqual(ftplib.parse257('257 "" created'), '')
614 self.assertRaises(ftplib.error_reply, ftplib.parse257, '250 "/foo/bar"')
615 # The 257 response is supposed to include the directory
616 # name and in case it contains embedded double-quotes
617 # they must be doubled (see RFC-959, chapter 7, appendix 2).
618 self.assertEqual(ftplib.parse257('257 "/foo/b""ar"'), '/foo/b"ar')
619 self.assertEqual(ftplib.parse257('257 "/foo/b""ar" created'), '/foo/b"ar')
620
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000621
622class TestIPv6Environment(TestCase):
623
624 def setUp(self):
625 self.server = DummyFTPServer((HOST, 0), af=socket.AF_INET6)
626 self.server.start()
627 self.client = ftplib.FTP()
628 self.client.connect(self.server.host, self.server.port)
629
630 def tearDown(self):
631 self.client.close()
632 self.server.stop()
633
634 def test_af(self):
635 self.assertEqual(self.client.af, socket.AF_INET6)
636
637 def test_makeport(self):
638 self.client.makeport()
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000639 self.assertEqual(self.server.handler_instance.last_received_cmd, 'eprt')
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000640
641 def test_makepasv(self):
642 host, port = self.client.makepasv()
643 conn = socket.create_connection((host, port), 2)
644 conn.close()
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000645 self.assertEqual(self.server.handler_instance.last_received_cmd, 'epsv')
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000646
647 def test_transfer(self):
648 def retr():
649 def callback(data):
650 received.append(data.decode('ascii'))
651 received = []
652 self.client.retrbinary('retr', callback)
653 self.assertEqual(''.join(received), RETR_DATA)
654 self.client.set_pasv(True)
655 retr()
656 self.client.set_pasv(False)
657 retr()
658
659
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000660class TestTLS_FTPClassMixin(TestFTPClass):
661 """Repeat TestFTPClass tests starting the TLS layer for both control
662 and data connections first.
663 """
664
665 def setUp(self):
666 self.server = DummyTLS_FTPServer((HOST, 0))
667 self.server.start()
668 self.client = ftplib.FTP_TLS(timeout=2)
669 self.client.connect(self.server.host, self.server.port)
670 # enable TLS
671 self.client.auth()
672 self.client.prot_p()
673
674
675class TestTLS_FTPClass(TestCase):
676 """Specific TLS_FTP class tests."""
677
678 def setUp(self):
679 self.server = DummyTLS_FTPServer((HOST, 0))
680 self.server.start()
681 self.client = ftplib.FTP_TLS(timeout=2)
682 self.client.connect(self.server.host, self.server.port)
683
684 def tearDown(self):
685 self.client.close()
686 self.server.stop()
687
688 def test_control_connection(self):
Ezio Melottie9615932010-01-24 19:26:24 +0000689 self.assertNotIsInstance(self.client.sock, ssl.SSLSocket)
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000690 self.client.auth()
Ezio Melottie9615932010-01-24 19:26:24 +0000691 self.assertIsInstance(self.client.sock, ssl.SSLSocket)
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000692
693 def test_data_connection(self):
694 # clear text
695 sock = self.client.transfercmd('list')
Ezio Melottie9615932010-01-24 19:26:24 +0000696 self.assertNotIsInstance(sock, ssl.SSLSocket)
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000697 sock.close()
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +0000698 self.assertEqual(self.client.voidresp(), "226 transfer complete")
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000699
700 # secured, after PROT P
701 self.client.prot_p()
702 sock = self.client.transfercmd('list')
Ezio Melottie9615932010-01-24 19:26:24 +0000703 self.assertIsInstance(sock, ssl.SSLSocket)
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000704 sock.close()
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +0000705 self.assertEqual(self.client.voidresp(), "226 transfer complete")
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000706
707 # PROT C is issued, the connection must be in cleartext again
708 self.client.prot_c()
709 sock = self.client.transfercmd('list')
Ezio Melottie9615932010-01-24 19:26:24 +0000710 self.assertNotIsInstance(sock, ssl.SSLSocket)
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000711 sock.close()
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +0000712 self.assertEqual(self.client.voidresp(), "226 transfer complete")
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000713
714 def test_login(self):
715 # login() is supposed to implicitly secure the control connection
Ezio Melottie9615932010-01-24 19:26:24 +0000716 self.assertNotIsInstance(self.client.sock, ssl.SSLSocket)
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000717 self.client.login()
Ezio Melottie9615932010-01-24 19:26:24 +0000718 self.assertIsInstance(self.client.sock, ssl.SSLSocket)
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000719 # make sure that AUTH TLS doesn't get issued again
720 self.client.login()
721
722 def test_auth_issued_twice(self):
723 self.client.auth()
724 self.assertRaises(ValueError, self.client.auth)
725
726 def test_auth_ssl(self):
727 try:
728 self.client.ssl_version = ssl.PROTOCOL_SSLv3
729 self.client.auth()
730 self.assertRaises(ValueError, self.client.auth)
731 finally:
732 self.client.ssl_version = ssl.PROTOCOL_TLSv1
733
Giampaolo Rodolàa67299e2010-05-26 18:06:04 +0000734 def test_context(self):
735 self.client.quit()
736 ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
737 self.assertRaises(ValueError, ftplib.FTP_TLS, keyfile=CERTFILE,
738 context=ctx)
739 self.assertRaises(ValueError, ftplib.FTP_TLS, certfile=CERTFILE,
740 context=ctx)
741 self.assertRaises(ValueError, ftplib.FTP_TLS, certfile=CERTFILE,
742 keyfile=CERTFILE, context=ctx)
743
744 self.client = ftplib.FTP_TLS(context=ctx, timeout=2)
745 self.client.connect(self.server.host, self.server.port)
746 self.assertNotIsInstance(self.client.sock, ssl.SSLSocket)
747 self.client.auth()
748 self.assertIs(self.client.sock.context, ctx)
749 self.assertIsInstance(self.client.sock, ssl.SSLSocket)
750
751 self.client.prot_p()
752 sock = self.client.transfercmd('list')
Giampaolo Rodolà6da11e52010-05-26 18:21:26 +0000753 self.assertIs(sock.context, ctx)
Giampaolo Rodolàa67299e2010-05-26 18:06:04 +0000754 self.assertIsInstance(sock, ssl.SSLSocket)
755 sock.close()
756
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000757
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000758class TestTimeouts(TestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000759
760 def setUp(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000761 self.evt = threading.Event()
Christian Heimes5e696852008-04-09 08:37:03 +0000762 self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
763 self.sock.settimeout(3)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000764 self.port = support.bind_port(self.sock)
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000765 threading.Thread(target=self.server, args=(self.evt,self.sock)).start()
Christian Heimes836baa52008-02-26 08:18:30 +0000766 # Wait for the server to be ready.
767 self.evt.wait()
768 self.evt.clear()
Christian Heimes5e696852008-04-09 08:37:03 +0000769 ftplib.FTP.port = self.port
Guido van Rossumd8faa362007-04-27 19:54:29 +0000770
771 def tearDown(self):
772 self.evt.wait()
773
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000774 def server(self, evt, serv):
775 # This method sets the evt 3 times:
776 # 1) when the connection is ready to be accepted.
777 # 2) when it is safe for the caller to close the connection
778 # 3) when we have closed the socket
779 serv.listen(5)
780 # (1) Signal the caller that we are ready to accept the connection.
781 evt.set()
782 try:
783 conn, addr = serv.accept()
784 except socket.timeout:
785 pass
786 else:
787 conn.send(b"1 Hola mundo\n")
788 # (2) Signal the caller that it is safe to close the socket.
789 evt.set()
790 conn.close()
791 finally:
792 serv.close()
793 # (3) Signal the caller that we are done.
794 evt.set()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000795
796 def testTimeoutDefault(self):
Georg Brandlf78e02b2008-06-10 17:40:04 +0000797 # default -- use global socket timeout
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000798 self.assertTrue(socket.getdefaulttimeout() is None)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000799 socket.setdefaulttimeout(30)
800 try:
801 ftp = ftplib.FTP("localhost")
802 finally:
803 socket.setdefaulttimeout(None)
804 self.assertEqual(ftp.sock.gettimeout(), 30)
805 self.evt.wait()
806 ftp.close()
807
808 def testTimeoutNone(self):
809 # no timeout -- do not use global socket timeout
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000810 self.assertTrue(socket.getdefaulttimeout() is None)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000811 socket.setdefaulttimeout(30)
812 try:
813 ftp = ftplib.FTP("localhost", timeout=None)
814 finally:
815 socket.setdefaulttimeout(None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000816 self.assertTrue(ftp.sock.gettimeout() is None)
Christian Heimes836baa52008-02-26 08:18:30 +0000817 self.evt.wait()
Georg Brandlf78e02b2008-06-10 17:40:04 +0000818 ftp.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000819
820 def testTimeoutValue(self):
821 # a value
Christian Heimes5e696852008-04-09 08:37:03 +0000822 ftp = ftplib.FTP(HOST, timeout=30)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000823 self.assertEqual(ftp.sock.gettimeout(), 30)
Christian Heimes836baa52008-02-26 08:18:30 +0000824 self.evt.wait()
Georg Brandlf78e02b2008-06-10 17:40:04 +0000825 ftp.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000826
827 def testTimeoutConnect(self):
828 ftp = ftplib.FTP()
Christian Heimes5e696852008-04-09 08:37:03 +0000829 ftp.connect(HOST, timeout=30)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000830 self.assertEqual(ftp.sock.gettimeout(), 30)
Christian Heimes836baa52008-02-26 08:18:30 +0000831 self.evt.wait()
Georg Brandlf78e02b2008-06-10 17:40:04 +0000832 ftp.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000833
834 def testTimeoutDifferentOrder(self):
835 ftp = ftplib.FTP(timeout=30)
Christian Heimes5e696852008-04-09 08:37:03 +0000836 ftp.connect(HOST)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000837 self.assertEqual(ftp.sock.gettimeout(), 30)
Christian Heimes836baa52008-02-26 08:18:30 +0000838 self.evt.wait()
Georg Brandlf78e02b2008-06-10 17:40:04 +0000839 ftp.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000840
841 def testTimeoutDirectAccess(self):
842 ftp = ftplib.FTP()
843 ftp.timeout = 30
Christian Heimes5e696852008-04-09 08:37:03 +0000844 ftp.connect(HOST)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000845 self.assertEqual(ftp.sock.gettimeout(), 30)
Christian Heimes836baa52008-02-26 08:18:30 +0000846 self.evt.wait()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000847 ftp.close()
848
849
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000850def test_main():
851 tests = [TestFTPClass, TestTimeouts]
852 if socket.has_ipv6:
853 try:
854 DummyFTPServer((HOST, 0), af=socket.AF_INET6)
855 except socket.error:
856 pass
857 else:
858 tests.append(TestIPv6Environment)
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000859
860 if ssl is not None:
861 tests.extend([TestTLS_FTPClassMixin, TestTLS_FTPClass])
862
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000863 thread_info = support.threading_setup()
864 try:
865 support.run_unittest(*tests)
866 finally:
867 support.threading_cleanup(*thread_info)
868
Guido van Rossumd8faa362007-04-27 19:54:29 +0000869
870if __name__ == '__main__':
871 test_main()