blob: c9bb06e7c27bcbb657fc3dfc7ba9c48c452b8d65 [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
Giampaolo Rodolà977c7072010-10-04 21:08:36 +0000247 def handle_accepted(self, conn, addr):
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000248 self.handler_instance = self.handler(conn)
Benjamin Petersond06e3b02008-09-28 21:00:42 +0000249
250 def handle_connect(self):
251 self.close()
252 handle_read = handle_connect
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000253
254 def writable(self):
255 return 0
256
257 def handle_error(self):
258 raise
259
260
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000261if ssl is not None:
262
263 CERTFILE = os.path.join(os.path.dirname(__file__), "keycert.pem")
264
265 class SSLConnection(asyncore.dispatcher):
266 """An asyncore.dispatcher subclass supporting TLS/SSL."""
267
268 _ssl_accepting = False
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +0000269 _ssl_closing = False
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000270
271 def secure_connection(self):
272 self.del_channel()
273 socket = ssl.wrap_socket(self.socket, suppress_ragged_eofs=False,
274 certfile=CERTFILE, server_side=True,
275 do_handshake_on_connect=False,
276 ssl_version=ssl.PROTOCOL_SSLv23)
277 self.set_socket(socket)
278 self._ssl_accepting = True
279
280 def _do_ssl_handshake(self):
281 try:
282 self.socket.do_handshake()
283 except ssl.SSLError as err:
284 if err.args[0] in (ssl.SSL_ERROR_WANT_READ,
285 ssl.SSL_ERROR_WANT_WRITE):
286 return
287 elif err.args[0] == ssl.SSL_ERROR_EOF:
288 return self.handle_close()
289 raise
290 except socket.error as err:
291 if err.args[0] == errno.ECONNABORTED:
292 return self.handle_close()
293 else:
294 self._ssl_accepting = False
295
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +0000296 def _do_ssl_shutdown(self):
297 self._ssl_closing = True
298 try:
299 self.socket = self.socket.unwrap()
300 except ssl.SSLError as err:
301 if err.args[0] in (ssl.SSL_ERROR_WANT_READ,
302 ssl.SSL_ERROR_WANT_WRITE):
303 return
304 except socket.error as err:
305 # Any "socket error" corresponds to a SSL_ERROR_SYSCALL return
306 # from OpenSSL's SSL_shutdown(), corresponding to a
307 # closed socket condition. See also:
308 # http://www.mail-archive.com/openssl-users@openssl.org/msg60710.html
309 pass
310 self._ssl_closing = False
311 super(SSLConnection, self).close()
312
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000313 def handle_read_event(self):
314 if self._ssl_accepting:
315 self._do_ssl_handshake()
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +0000316 elif self._ssl_closing:
317 self._do_ssl_shutdown()
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000318 else:
319 super(SSLConnection, self).handle_read_event()
320
321 def handle_write_event(self):
322 if self._ssl_accepting:
323 self._do_ssl_handshake()
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +0000324 elif self._ssl_closing:
325 self._do_ssl_shutdown()
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000326 else:
327 super(SSLConnection, self).handle_write_event()
328
329 def send(self, data):
330 try:
331 return super(SSLConnection, self).send(data)
332 except ssl.SSLError as err:
Antoine Pitrou5733c082010-03-22 14:49:10 +0000333 if err.args[0] in (ssl.SSL_ERROR_EOF, ssl.SSL_ERROR_ZERO_RETURN,
334 ssl.SSL_ERROR_WANT_READ,
335 ssl.SSL_ERROR_WANT_WRITE):
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000336 return 0
337 raise
338
339 def recv(self, buffer_size):
340 try:
341 return super(SSLConnection, self).recv(buffer_size)
342 except ssl.SSLError as err:
Antoine Pitrou5733c082010-03-22 14:49:10 +0000343 if err.args[0] in (ssl.SSL_ERROR_WANT_READ,
344 ssl.SSL_ERROR_WANT_WRITE):
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +0000345 return b''
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000346 if err.args[0] in (ssl.SSL_ERROR_EOF, ssl.SSL_ERROR_ZERO_RETURN):
347 self.handle_close()
348 return b''
349 raise
350
351 def handle_error(self):
352 raise
353
354 def close(self):
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +0000355 if (isinstance(self.socket, ssl.SSLSocket) and
356 self.socket._sslobj is not None):
357 self._do_ssl_shutdown()
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000358
359
360 class DummyTLS_DTPHandler(SSLConnection, DummyDTPHandler):
361 """A DummyDTPHandler subclass supporting TLS/SSL."""
362
363 def __init__(self, conn, baseclass):
364 DummyDTPHandler.__init__(self, conn, baseclass)
365 if self.baseclass.secure_data_channel:
366 self.secure_connection()
367
368
369 class DummyTLS_FTPHandler(SSLConnection, DummyFTPHandler):
370 """A DummyFTPHandler subclass supporting TLS/SSL."""
371
372 dtp_handler = DummyTLS_DTPHandler
373
374 def __init__(self, conn):
375 DummyFTPHandler.__init__(self, conn)
376 self.secure_data_channel = False
377
378 def cmd_auth(self, line):
379 """Set up secure control channel."""
380 self.push('234 AUTH TLS successful')
381 self.secure_connection()
382
383 def cmd_pbsz(self, line):
384 """Negotiate size of buffer for secure data transfer.
385 For TLS/SSL the only valid value for the parameter is '0'.
386 Any other value is accepted but ignored.
387 """
388 self.push('200 PBSZ=0 successful.')
389
390 def cmd_prot(self, line):
391 """Setup un/secure data channel."""
392 arg = line.upper()
393 if arg == 'C':
394 self.push('200 Protection set to Clear')
395 self.secure_data_channel = False
396 elif arg == 'P':
397 self.push('200 Protection set to Private')
398 self.secure_data_channel = True
399 else:
400 self.push("502 Unrecognized PROT type (use C or P).")
401
402
403 class DummyTLS_FTPServer(DummyFTPServer):
404 handler = DummyTLS_FTPHandler
405
406
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000407class TestFTPClass(TestCase):
408
409 def setUp(self):
410 self.server = DummyFTPServer((HOST, 0))
411 self.server.start()
412 self.client = ftplib.FTP(timeout=2)
413 self.client.connect(self.server.host, self.server.port)
414
415 def tearDown(self):
416 self.client.close()
417 self.server.stop()
418
419 def test_getwelcome(self):
420 self.assertEqual(self.client.getwelcome(), '220 welcome')
421
422 def test_sanitize(self):
423 self.assertEqual(self.client.sanitize('foo'), repr('foo'))
424 self.assertEqual(self.client.sanitize('pass 12345'), repr('pass *****'))
425 self.assertEqual(self.client.sanitize('PASS 12345'), repr('PASS *****'))
426
427 def test_exceptions(self):
428 self.assertRaises(ftplib.error_temp, self.client.sendcmd, 'echo 400')
429 self.assertRaises(ftplib.error_temp, self.client.sendcmd, 'echo 499')
430 self.assertRaises(ftplib.error_perm, self.client.sendcmd, 'echo 500')
431 self.assertRaises(ftplib.error_perm, self.client.sendcmd, 'echo 599')
432 self.assertRaises(ftplib.error_proto, self.client.sendcmd, 'echo 999')
433
434 def test_all_errors(self):
435 exceptions = (ftplib.error_reply, ftplib.error_temp, ftplib.error_perm,
436 ftplib.error_proto, ftplib.Error, IOError, EOFError)
437 for x in exceptions:
438 try:
439 raise x('exception not included in all_errors set')
440 except ftplib.all_errors:
441 pass
442
443 def test_set_pasv(self):
444 # passive mode is supposed to be enabled by default
445 self.assertTrue(self.client.passiveserver)
446 self.client.set_pasv(True)
447 self.assertTrue(self.client.passiveserver)
448 self.client.set_pasv(False)
449 self.assertFalse(self.client.passiveserver)
450
451 def test_voidcmd(self):
452 self.client.voidcmd('echo 200')
453 self.client.voidcmd('echo 299')
454 self.assertRaises(ftplib.error_reply, self.client.voidcmd, 'echo 199')
455 self.assertRaises(ftplib.error_reply, self.client.voidcmd, 'echo 300')
456
457 def test_login(self):
458 self.client.login()
459
460 def test_acct(self):
461 self.client.acct('passwd')
462
463 def test_rename(self):
464 self.client.rename('a', 'b')
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000465 self.server.handler_instance.next_response = '200'
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000466 self.assertRaises(ftplib.error_reply, self.client.rename, 'a', 'b')
467
468 def test_delete(self):
469 self.client.delete('foo')
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000470 self.server.handler_instance.next_response = '199'
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000471 self.assertRaises(ftplib.error_reply, self.client.delete, 'foo')
472
473 def test_size(self):
474 self.client.size('foo')
475
476 def test_mkd(self):
477 dir = self.client.mkd('/foo')
478 self.assertEqual(dir, '/foo')
479
480 def test_rmd(self):
481 self.client.rmd('foo')
482
483 def test_pwd(self):
484 dir = self.client.pwd()
485 self.assertEqual(dir, 'pwd ok')
486
487 def test_quit(self):
488 self.assertEqual(self.client.quit(), '221 quit ok')
489 # Ensure the connection gets closed; sock attribute should be None
490 self.assertEqual(self.client.sock, None)
491
492 def test_retrbinary(self):
493 def callback(data):
494 received.append(data.decode('ascii'))
495 received = []
496 self.client.retrbinary('retr', callback)
497 self.assertEqual(''.join(received), RETR_DATA)
498
Antoine Pitrou648bcd72009-11-27 13:23:26 +0000499 def test_retrbinary_rest(self):
500 def callback(data):
501 received.append(data.decode('ascii'))
502 for rest in (0, 10, 20):
503 received = []
504 self.client.retrbinary('retr', callback, rest=rest)
505 self.assertEqual(''.join(received), RETR_DATA[rest:],
506 msg='rest test case %d %d %d' % (rest,
507 len(''.join(received)),
508 len(RETR_DATA[rest:])))
509
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000510 def test_retrlines(self):
511 received = []
512 self.client.retrlines('retr', received.append)
Giampaolo Rodolàf96482e2010-08-04 10:36:18 +0000513 self.assertEqual(''.join(received), RETR_DATA.replace('\r\n', ''))
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000514
515 def test_storbinary(self):
516 f = io.BytesIO(RETR_DATA.encode('ascii'))
517 self.client.storbinary('stor', f)
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000518 self.assertEqual(self.server.handler_instance.last_received_data, RETR_DATA)
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000519 # test new callback arg
520 flag = []
521 f.seek(0)
522 self.client.storbinary('stor', f, callback=lambda x: flag.append(None))
523 self.assertTrue(flag)
524
Antoine Pitrou648bcd72009-11-27 13:23:26 +0000525 def test_storbinary_rest(self):
526 f = io.BytesIO(RETR_DATA.replace('\r\n', '\n').encode('ascii'))
527 for r in (30, '30'):
528 f.seek(0)
529 self.client.storbinary('stor', f, rest=r)
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000530 self.assertEqual(self.server.handler_instance.rest, str(r))
Antoine Pitrou648bcd72009-11-27 13:23:26 +0000531
Giampaolo Rodolàf96482e2010-08-04 10:36:18 +0000532 def test_storlines(self):
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000533 f = io.BytesIO(RETR_DATA.replace('\r\n', '\n').encode('ascii'))
534 self.client.storlines('stor', f)
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000535 self.assertEqual(self.server.handler_instance.last_received_data, RETR_DATA)
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000536 # test new callback arg
537 flag = []
538 f.seek(0)
539 self.client.storlines('stor foo', f, callback=lambda x: flag.append(None))
540 self.assertTrue(flag)
541
542 def test_nlst(self):
543 self.client.nlst()
544 self.assertEqual(self.client.nlst(), NLST_DATA.split('\r\n')[:-1])
545
546 def test_dir(self):
547 l = []
548 self.client.dir(lambda x: l.append(x))
549 self.assertEqual(''.join(l), LIST_DATA.replace('\r\n', ''))
550
Benjamin Peterson3a53fbb2008-09-27 22:04:16 +0000551 def test_makeport(self):
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000552 self.client.makeport()
553 # IPv4 is in use, just make sure send_eprt has not been used
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000554 self.assertEqual(self.server.handler_instance.last_received_cmd, 'port')
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000555
556 def test_makepasv(self):
557 host, port = self.client.makepasv()
558 conn = socket.create_connection((host, port), 2)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000559 conn.close()
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000560 # IPv4 is in use, just make sure send_epsv has not been used
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000561 self.assertEqual(self.server.handler_instance.last_received_cmd, 'pasv')
562
563 def test_with_statement(self):
564 self.client.quit()
565
566 def is_client_connected():
567 if self.client.sock is None:
568 return False
569 try:
570 self.client.sendcmd('noop')
571 except (socket.error, EOFError):
572 return False
573 return True
574
575 # base test
576 with ftplib.FTP(timeout=2) as self.client:
577 self.client.connect(self.server.host, self.server.port)
578 self.client.sendcmd('noop')
579 self.assertTrue(is_client_connected())
580 self.assertEqual(self.server.handler_instance.last_received_cmd, 'quit')
581 self.assertFalse(is_client_connected())
582
583 # QUIT sent inside the with block
584 with ftplib.FTP(timeout=2) as self.client:
585 self.client.connect(self.server.host, self.server.port)
586 self.client.sendcmd('noop')
587 self.client.quit()
588 self.assertEqual(self.server.handler_instance.last_received_cmd, 'quit')
589 self.assertFalse(is_client_connected())
590
591 # force a wrong response code to be sent on QUIT: error_perm
592 # is expected and the connection is supposed to be closed
593 try:
594 with ftplib.FTP(timeout=2) as self.client:
595 self.client.connect(self.server.host, self.server.port)
596 self.client.sendcmd('noop')
597 self.server.handler_instance.next_response = '550 error on quit'
598 except ftplib.error_perm as err:
599 self.assertEqual(str(err), '550 error on quit')
600 else:
601 self.fail('Exception not raised')
602 # needed to give the threaded server some time to set the attribute
603 # which otherwise would still be == 'noop'
604 time.sleep(0.1)
605 self.assertEqual(self.server.handler_instance.last_received_cmd, 'quit')
606 self.assertFalse(is_client_connected())
Guido van Rossumd8faa362007-04-27 19:54:29 +0000607
Giampaolo Rodolàbbc47822010-08-23 22:10:32 +0000608 def test_parse257(self):
609 self.assertEqual(ftplib.parse257('257 "/foo/bar"'), '/foo/bar')
610 self.assertEqual(ftplib.parse257('257 "/foo/bar" created'), '/foo/bar')
611 self.assertEqual(ftplib.parse257('257 ""'), '')
612 self.assertEqual(ftplib.parse257('257 "" created'), '')
613 self.assertRaises(ftplib.error_reply, ftplib.parse257, '250 "/foo/bar"')
614 # The 257 response is supposed to include the directory
615 # name and in case it contains embedded double-quotes
616 # they must be doubled (see RFC-959, chapter 7, appendix 2).
617 self.assertEqual(ftplib.parse257('257 "/foo/b""ar"'), '/foo/b"ar')
618 self.assertEqual(ftplib.parse257('257 "/foo/b""ar" created'), '/foo/b"ar')
619
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000620
621class TestIPv6Environment(TestCase):
622
623 def setUp(self):
624 self.server = DummyFTPServer((HOST, 0), af=socket.AF_INET6)
625 self.server.start()
626 self.client = ftplib.FTP()
627 self.client.connect(self.server.host, self.server.port)
628
629 def tearDown(self):
630 self.client.close()
631 self.server.stop()
632
633 def test_af(self):
634 self.assertEqual(self.client.af, socket.AF_INET6)
635
636 def test_makeport(self):
637 self.client.makeport()
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000638 self.assertEqual(self.server.handler_instance.last_received_cmd, 'eprt')
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000639
640 def test_makepasv(self):
641 host, port = self.client.makepasv()
642 conn = socket.create_connection((host, port), 2)
643 conn.close()
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000644 self.assertEqual(self.server.handler_instance.last_received_cmd, 'epsv')
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000645
646 def test_transfer(self):
647 def retr():
648 def callback(data):
649 received.append(data.decode('ascii'))
650 received = []
651 self.client.retrbinary('retr', callback)
652 self.assertEqual(''.join(received), RETR_DATA)
653 self.client.set_pasv(True)
654 retr()
655 self.client.set_pasv(False)
656 retr()
657
658
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000659class TestTLS_FTPClassMixin(TestFTPClass):
660 """Repeat TestFTPClass tests starting the TLS layer for both control
661 and data connections first.
662 """
663
664 def setUp(self):
665 self.server = DummyTLS_FTPServer((HOST, 0))
666 self.server.start()
667 self.client = ftplib.FTP_TLS(timeout=2)
668 self.client.connect(self.server.host, self.server.port)
669 # enable TLS
670 self.client.auth()
671 self.client.prot_p()
672
673
674class TestTLS_FTPClass(TestCase):
675 """Specific TLS_FTP class tests."""
676
677 def setUp(self):
678 self.server = DummyTLS_FTPServer((HOST, 0))
679 self.server.start()
680 self.client = ftplib.FTP_TLS(timeout=2)
681 self.client.connect(self.server.host, self.server.port)
682
683 def tearDown(self):
684 self.client.close()
685 self.server.stop()
686
687 def test_control_connection(self):
Ezio Melottie9615932010-01-24 19:26:24 +0000688 self.assertNotIsInstance(self.client.sock, ssl.SSLSocket)
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000689 self.client.auth()
Ezio Melottie9615932010-01-24 19:26:24 +0000690 self.assertIsInstance(self.client.sock, ssl.SSLSocket)
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000691
692 def test_data_connection(self):
693 # clear text
694 sock = self.client.transfercmd('list')
Ezio Melottie9615932010-01-24 19:26:24 +0000695 self.assertNotIsInstance(sock, ssl.SSLSocket)
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000696 sock.close()
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +0000697 self.assertEqual(self.client.voidresp(), "226 transfer complete")
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000698
699 # secured, after PROT P
700 self.client.prot_p()
701 sock = self.client.transfercmd('list')
Ezio Melottie9615932010-01-24 19:26:24 +0000702 self.assertIsInstance(sock, ssl.SSLSocket)
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000703 sock.close()
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +0000704 self.assertEqual(self.client.voidresp(), "226 transfer complete")
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000705
706 # PROT C is issued, the connection must be in cleartext again
707 self.client.prot_c()
708 sock = self.client.transfercmd('list')
Ezio Melottie9615932010-01-24 19:26:24 +0000709 self.assertNotIsInstance(sock, ssl.SSLSocket)
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000710 sock.close()
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +0000711 self.assertEqual(self.client.voidresp(), "226 transfer complete")
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000712
713 def test_login(self):
714 # login() is supposed to implicitly secure the control connection
Ezio Melottie9615932010-01-24 19:26:24 +0000715 self.assertNotIsInstance(self.client.sock, ssl.SSLSocket)
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000716 self.client.login()
Ezio Melottie9615932010-01-24 19:26:24 +0000717 self.assertIsInstance(self.client.sock, ssl.SSLSocket)
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000718 # make sure that AUTH TLS doesn't get issued again
719 self.client.login()
720
721 def test_auth_issued_twice(self):
722 self.client.auth()
723 self.assertRaises(ValueError, self.client.auth)
724
725 def test_auth_ssl(self):
726 try:
727 self.client.ssl_version = ssl.PROTOCOL_SSLv3
728 self.client.auth()
729 self.assertRaises(ValueError, self.client.auth)
730 finally:
731 self.client.ssl_version = ssl.PROTOCOL_TLSv1
732
Giampaolo Rodolàa67299e2010-05-26 18:06:04 +0000733 def test_context(self):
734 self.client.quit()
735 ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
736 self.assertRaises(ValueError, ftplib.FTP_TLS, keyfile=CERTFILE,
737 context=ctx)
738 self.assertRaises(ValueError, ftplib.FTP_TLS, certfile=CERTFILE,
739 context=ctx)
740 self.assertRaises(ValueError, ftplib.FTP_TLS, certfile=CERTFILE,
741 keyfile=CERTFILE, context=ctx)
742
743 self.client = ftplib.FTP_TLS(context=ctx, timeout=2)
744 self.client.connect(self.server.host, self.server.port)
745 self.assertNotIsInstance(self.client.sock, ssl.SSLSocket)
746 self.client.auth()
747 self.assertIs(self.client.sock.context, ctx)
748 self.assertIsInstance(self.client.sock, ssl.SSLSocket)
749
750 self.client.prot_p()
751 sock = self.client.transfercmd('list')
Giampaolo Rodolà6da11e52010-05-26 18:21:26 +0000752 self.assertIs(sock.context, ctx)
Giampaolo Rodolàa67299e2010-05-26 18:06:04 +0000753 self.assertIsInstance(sock, ssl.SSLSocket)
754 sock.close()
755
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000756
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000757class TestTimeouts(TestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000758
759 def setUp(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000760 self.evt = threading.Event()
Christian Heimes5e696852008-04-09 08:37:03 +0000761 self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
762 self.sock.settimeout(3)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000763 self.port = support.bind_port(self.sock)
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000764 threading.Thread(target=self.server, args=(self.evt,self.sock)).start()
Christian Heimes836baa52008-02-26 08:18:30 +0000765 # Wait for the server to be ready.
766 self.evt.wait()
767 self.evt.clear()
Christian Heimes5e696852008-04-09 08:37:03 +0000768 ftplib.FTP.port = self.port
Guido van Rossumd8faa362007-04-27 19:54:29 +0000769
770 def tearDown(self):
771 self.evt.wait()
772
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000773 def server(self, evt, serv):
774 # This method sets the evt 3 times:
775 # 1) when the connection is ready to be accepted.
776 # 2) when it is safe for the caller to close the connection
777 # 3) when we have closed the socket
778 serv.listen(5)
779 # (1) Signal the caller that we are ready to accept the connection.
780 evt.set()
781 try:
782 conn, addr = serv.accept()
783 except socket.timeout:
784 pass
785 else:
786 conn.send(b"1 Hola mundo\n")
787 # (2) Signal the caller that it is safe to close the socket.
788 evt.set()
789 conn.close()
790 finally:
791 serv.close()
792 # (3) Signal the caller that we are done.
793 evt.set()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000794
795 def testTimeoutDefault(self):
Georg Brandlf78e02b2008-06-10 17:40:04 +0000796 # default -- use global socket timeout
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000797 self.assertTrue(socket.getdefaulttimeout() is None)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000798 socket.setdefaulttimeout(30)
799 try:
800 ftp = ftplib.FTP("localhost")
801 finally:
802 socket.setdefaulttimeout(None)
803 self.assertEqual(ftp.sock.gettimeout(), 30)
804 self.evt.wait()
805 ftp.close()
806
807 def testTimeoutNone(self):
808 # no timeout -- do not use global socket timeout
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000809 self.assertTrue(socket.getdefaulttimeout() is None)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000810 socket.setdefaulttimeout(30)
811 try:
812 ftp = ftplib.FTP("localhost", timeout=None)
813 finally:
814 socket.setdefaulttimeout(None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000815 self.assertTrue(ftp.sock.gettimeout() is None)
Christian Heimes836baa52008-02-26 08:18:30 +0000816 self.evt.wait()
Georg Brandlf78e02b2008-06-10 17:40:04 +0000817 ftp.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000818
819 def testTimeoutValue(self):
820 # a value
Christian Heimes5e696852008-04-09 08:37:03 +0000821 ftp = ftplib.FTP(HOST, timeout=30)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000822 self.assertEqual(ftp.sock.gettimeout(), 30)
Christian Heimes836baa52008-02-26 08:18:30 +0000823 self.evt.wait()
Georg Brandlf78e02b2008-06-10 17:40:04 +0000824 ftp.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000825
826 def testTimeoutConnect(self):
827 ftp = ftplib.FTP()
Christian Heimes5e696852008-04-09 08:37:03 +0000828 ftp.connect(HOST, timeout=30)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000829 self.assertEqual(ftp.sock.gettimeout(), 30)
Christian Heimes836baa52008-02-26 08:18:30 +0000830 self.evt.wait()
Georg Brandlf78e02b2008-06-10 17:40:04 +0000831 ftp.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000832
833 def testTimeoutDifferentOrder(self):
834 ftp = ftplib.FTP(timeout=30)
Christian Heimes5e696852008-04-09 08:37:03 +0000835 ftp.connect(HOST)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000836 self.assertEqual(ftp.sock.gettimeout(), 30)
Christian Heimes836baa52008-02-26 08:18:30 +0000837 self.evt.wait()
Georg Brandlf78e02b2008-06-10 17:40:04 +0000838 ftp.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000839
840 def testTimeoutDirectAccess(self):
841 ftp = ftplib.FTP()
842 ftp.timeout = 30
Christian Heimes5e696852008-04-09 08:37:03 +0000843 ftp.connect(HOST)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000844 self.assertEqual(ftp.sock.gettimeout(), 30)
Christian Heimes836baa52008-02-26 08:18:30 +0000845 self.evt.wait()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000846 ftp.close()
847
848
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000849def test_main():
850 tests = [TestFTPClass, TestTimeouts]
851 if socket.has_ipv6:
852 try:
853 DummyFTPServer((HOST, 0), af=socket.AF_INET6)
854 except socket.error:
855 pass
856 else:
857 tests.append(TestIPv6Environment)
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000858
859 if ssl is not None:
860 tests.extend([TestTLS_FTPClassMixin, TestTLS_FTPClass])
861
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000862 thread_info = support.threading_setup()
863 try:
864 support.run_unittest(*tests)
865 finally:
866 support.threading_cleanup(*thread_info)
867
Guido van Rossumd8faa362007-04-27 19:54:29 +0000868
869if __name__ == '__main__':
870 test_main()