blob: 2424911c7ac5e9fa9a25eb3be33eba0c66da249f [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
Antoine Pitroua6a4dc82017-09-07 18:56:24 +020013import threading
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +000014import time
Antoine Pitrouf988cd02009-11-17 20:21:14 +000015try:
16 import ssl
17except ImportError:
18 ssl = None
Guido van Rossumd8faa362007-04-27 19:54:29 +000019
Serhiy Storchaka43767632013-11-03 21:31:38 +020020from unittest import TestCase, skipUnless
Benjamin Petersonee8712c2008-05-20 21:35:26 +000021from test import support
Hai Shie80697d2020-05-28 06:10:27 +080022from test.support import threading_helper
Serhiy Storchaka16994912020-04-25 10:06:29 +030023from test.support import socket_helper
Hai Shi46605972020-08-04 00:49:18 +080024from test.support import warnings_helper
Serhiy Storchaka16994912020-04-25 10:06:29 +030025from test.support.socket_helper import HOST, HOSTv6
Guido van Rossumd8faa362007-04-27 19:54:29 +000026
Victor Stinner07871b22019-12-10 20:32:59 +010027TIMEOUT = support.LOOPBACK_TIMEOUT
Sebastian Pedersena1a0eb42020-04-14 01:07:56 +020028DEFAULT_ENCODING = 'utf-8'
Benjamin Petersonbe17a112008-09-27 21:49:47 +000029# the dummy data returned by server over the data channel when
Giampaolo Rodola'd78def92011-05-06 19:49:08 +020030# RETR, LIST, NLST, MLSD commands are issued
Sebastian Pedersena1a0eb42020-04-14 01:07:56 +020031RETR_DATA = 'abcde12345\r\n' * 1000 + 'non-ascii char \xAE\r\n'
32LIST_DATA = 'foo\r\nbar\r\n non-ascii char \xAE\r\n'
33NLST_DATA = 'foo\r\nbar\r\n non-ascii char \xAE\r\n'
Giampaolo Rodola'd78def92011-05-06 19:49:08 +020034MLSD_DATA = ("type=cdir;perm=el;unique==keVO1+ZF4; test\r\n"
35 "type=pdir;perm=e;unique==keVO1+d?3; ..\r\n"
36 "type=OS.unix=slink:/foobar;perm=;unique==keVO1+4G4; foobar\r\n"
37 "type=OS.unix=chr-13/29;perm=;unique==keVO1+5G4; device\r\n"
38 "type=OS.unix=blk-11/108;perm=;unique==keVO1+6G4; block\r\n"
39 "type=file;perm=awr;unique==keVO1+8G4; writable\r\n"
40 "type=dir;perm=cpmel;unique==keVO1+7G4; promiscuous\r\n"
41 "type=dir;perm=;unique==keVO1+1t2; no-exec\r\n"
42 "type=file;perm=r;unique==keVO1+EG4; two words\r\n"
43 "type=file;perm=r;unique==keVO1+IH4; leading space\r\n"
44 "type=file;perm=r;unique==keVO1+1G4; file1\r\n"
45 "type=dir;perm=cpmel;unique==keVO1+7G4; incoming\r\n"
46 "type=file;perm=r;unique==keVO1+1G4; file2\r\n"
47 "type=file;perm=r;unique==keVO1+1G4; file3\r\n"
Sebastian Pedersena1a0eb42020-04-14 01:07:56 +020048 "type=file;perm=r;unique==keVO1+1G4; file4\r\n"
49 "type=dir;perm=cpmel;unique==SGP1; dir \xAE non-ascii char\r\n"
50 "type=file;perm=r;unique==SGP2; file \xAE non-ascii char\r\n")
Christian Heimes836baa52008-02-26 08:18:30 +000051
Christian Heimes836baa52008-02-26 08:18:30 +000052
Benjamin Petersonbe17a112008-09-27 21:49:47 +000053class DummyDTPHandler(asynchat.async_chat):
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +000054 dtp_conn_closed = False
Benjamin Petersonbe17a112008-09-27 21:49:47 +000055
56 def __init__(self, conn, baseclass):
57 asynchat.async_chat.__init__(self, conn)
58 self.baseclass = baseclass
59 self.baseclass.last_received_data = ''
Sebastian Pedersena1a0eb42020-04-14 01:07:56 +020060 self.encoding = baseclass.encoding
Benjamin Petersonbe17a112008-09-27 21:49:47 +000061
62 def handle_read(self):
Sebastian Pedersena1a0eb42020-04-14 01:07:56 +020063 new_data = self.recv(1024).decode(self.encoding, 'replace')
64 self.baseclass.last_received_data += new_data
Benjamin Petersonbe17a112008-09-27 21:49:47 +000065
66 def handle_close(self):
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +000067 # XXX: this method can be called many times in a row for a single
68 # connection, including in clear-text (non-TLS) mode.
69 # (behaviour witnessed with test_data_connection)
70 if not self.dtp_conn_closed:
71 self.baseclass.push('226 transfer complete')
72 self.close()
73 self.dtp_conn_closed = True
Benjamin Petersonbe17a112008-09-27 21:49:47 +000074
75 def push(self, what):
Giampaolo Rodola'd78def92011-05-06 19:49:08 +020076 if self.baseclass.next_data is not None:
77 what = self.baseclass.next_data
78 self.baseclass.next_data = None
79 if not what:
80 return self.close_when_done()
Sebastian Pedersena1a0eb42020-04-14 01:07:56 +020081 super(DummyDTPHandler, self).push(what.encode(self.encoding))
Benjamin Petersonbe17a112008-09-27 21:49:47 +000082
Giampaolo Rodolàd930b632010-05-06 20:21:57 +000083 def handle_error(self):
Berker Peksag8f791d32014-11-01 10:45:57 +020084 raise Exception
Giampaolo Rodolàd930b632010-05-06 20:21:57 +000085
Benjamin Petersonbe17a112008-09-27 21:49:47 +000086
87class DummyFTPHandler(asynchat.async_chat):
88
Antoine Pitrouf988cd02009-11-17 20:21:14 +000089 dtp_handler = DummyDTPHandler
90
Sebastian Pedersena1a0eb42020-04-14 01:07:56 +020091 def __init__(self, conn, encoding=DEFAULT_ENCODING):
Benjamin Petersonbe17a112008-09-27 21:49:47 +000092 asynchat.async_chat.__init__(self, conn)
Giampaolo Rodola'0b5c21f2011-05-07 19:03:47 +020093 # tells the socket to handle urgent data inline (ABOR command)
94 self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_OOBINLINE, 1)
Benjamin Petersonbe17a112008-09-27 21:49:47 +000095 self.set_terminator(b"\r\n")
96 self.in_buffer = []
97 self.dtp = None
98 self.last_received_cmd = None
99 self.last_received_data = ''
100 self.next_response = ''
Giampaolo Rodola'd78def92011-05-06 19:49:08 +0200101 self.next_data = None
Antoine Pitrou648bcd72009-11-27 13:23:26 +0000102 self.rest = None
Serhiy Storchakac30b1782013-10-20 16:58:27 +0300103 self.next_retr_data = RETR_DATA
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000104 self.push('220 welcome')
Sebastian Pedersena1a0eb42020-04-14 01:07:56 +0200105 self.encoding = encoding
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000106
107 def collect_incoming_data(self, data):
108 self.in_buffer.append(data)
109
110 def found_terminator(self):
Sebastian Pedersena1a0eb42020-04-14 01:07:56 +0200111 line = b''.join(self.in_buffer).decode(self.encoding)
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000112 self.in_buffer = []
113 if self.next_response:
114 self.push(self.next_response)
115 self.next_response = ''
116 cmd = line.split(' ')[0].lower()
117 self.last_received_cmd = cmd
118 space = line.find(' ')
119 if space != -1:
120 arg = line[space + 1:]
121 else:
122 arg = ""
123 if hasattr(self, 'cmd_' + cmd):
124 method = getattr(self, 'cmd_' + cmd)
125 method(arg)
126 else:
127 self.push('550 command "%s" not understood.' %cmd)
128
129 def handle_error(self):
Berker Peksag8f791d32014-11-01 10:45:57 +0200130 raise Exception
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000131
132 def push(self, data):
Sebastian Pedersena1a0eb42020-04-14 01:07:56 +0200133 asynchat.async_chat.push(self, data.encode(self.encoding) + b'\r\n')
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000134
135 def cmd_port(self, arg):
136 addr = list(map(int, arg.split(',')))
137 ip = '%d.%d.%d.%d' %tuple(addr[:4])
138 port = (addr[4] * 256) + addr[5]
Giampaolo Rodola'0d4f08c2013-05-16 15:12:01 +0200139 s = socket.create_connection((ip, port), timeout=TIMEOUT)
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000140 self.dtp = self.dtp_handler(s, baseclass=self)
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000141 self.push('200 active data connection established')
142
143 def cmd_pasv(self, arg):
Giampaolo Rodolaeb7e29f2019-04-09 00:34:02 +0200144 with socket.create_server((self.socket.getsockname()[0], 0)) as sock:
Giampaolo Rodola'0d4f08c2013-05-16 15:12:01 +0200145 sock.settimeout(TIMEOUT)
Brett Cannon918e2d42010-10-29 23:26:25 +0000146 ip, port = sock.getsockname()[:2]
147 ip = ip.replace('.', ','); p1 = port / 256; p2 = port % 256
148 self.push('227 entering passive mode (%s,%d,%d)' %(ip, p1, p2))
149 conn, addr = sock.accept()
150 self.dtp = self.dtp_handler(conn, baseclass=self)
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000151
152 def cmd_eprt(self, arg):
153 af, ip, port = arg.split(arg[0])[1:-1]
154 port = int(port)
Giampaolo Rodola'0d4f08c2013-05-16 15:12:01 +0200155 s = socket.create_connection((ip, port), timeout=TIMEOUT)
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000156 self.dtp = self.dtp_handler(s, baseclass=self)
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000157 self.push('200 active data connection established')
158
159 def cmd_epsv(self, arg):
Giampaolo Rodolaeb7e29f2019-04-09 00:34:02 +0200160 with socket.create_server((self.socket.getsockname()[0], 0),
161 family=socket.AF_INET6) as sock:
Giampaolo Rodola'0d4f08c2013-05-16 15:12:01 +0200162 sock.settimeout(TIMEOUT)
Brett Cannon918e2d42010-10-29 23:26:25 +0000163 port = sock.getsockname()[1]
164 self.push('229 entering extended passive mode (|||%d|)' %port)
165 conn, addr = sock.accept()
166 self.dtp = self.dtp_handler(conn, baseclass=self)
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000167
168 def cmd_echo(self, arg):
169 # sends back the received string (used by the test suite)
170 self.push(arg)
171
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000172 def cmd_noop(self, arg):
173 self.push('200 noop ok')
174
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000175 def cmd_user(self, arg):
176 self.push('331 username ok')
177
178 def cmd_pass(self, arg):
179 self.push('230 password ok')
180
181 def cmd_acct(self, arg):
182 self.push('230 acct ok')
183
184 def cmd_rnfr(self, arg):
185 self.push('350 rnfr ok')
186
187 def cmd_rnto(self, arg):
188 self.push('250 rnto ok')
189
190 def cmd_dele(self, arg):
191 self.push('250 dele ok')
192
193 def cmd_cwd(self, arg):
194 self.push('250 cwd ok')
195
196 def cmd_size(self, arg):
197 self.push('250 1000')
198
199 def cmd_mkd(self, arg):
200 self.push('257 "%s"' %arg)
201
202 def cmd_rmd(self, arg):
203 self.push('250 rmd ok')
204
205 def cmd_pwd(self, arg):
206 self.push('257 "pwd ok"')
207
208 def cmd_type(self, arg):
Giampaolo Rodolàf96482e2010-08-04 10:36:18 +0000209 self.push('200 type ok')
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000210
211 def cmd_quit(self, arg):
212 self.push('221 quit ok')
213 self.close()
214
Giampaolo Rodola'0b5c21f2011-05-07 19:03:47 +0200215 def cmd_abor(self, arg):
216 self.push('226 abor ok')
217
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000218 def cmd_stor(self, arg):
219 self.push('125 stor ok')
220
Antoine Pitrou648bcd72009-11-27 13:23:26 +0000221 def cmd_rest(self, arg):
222 self.rest = arg
223 self.push('350 rest ok')
224
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000225 def cmd_retr(self, arg):
226 self.push('125 retr ok')
Antoine Pitrou648bcd72009-11-27 13:23:26 +0000227 if self.rest is not None:
228 offset = int(self.rest)
229 else:
230 offset = 0
Serhiy Storchakac30b1782013-10-20 16:58:27 +0300231 self.dtp.push(self.next_retr_data[offset:])
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000232 self.dtp.close_when_done()
Antoine Pitrou648bcd72009-11-27 13:23:26 +0000233 self.rest = None
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000234
235 def cmd_list(self, arg):
236 self.push('125 list ok')
237 self.dtp.push(LIST_DATA)
238 self.dtp.close_when_done()
239
240 def cmd_nlst(self, arg):
241 self.push('125 nlst ok')
242 self.dtp.push(NLST_DATA)
243 self.dtp.close_when_done()
244
Giampaolo Rodola'd78def92011-05-06 19:49:08 +0200245 def cmd_opts(self, arg):
246 self.push('200 opts ok')
247
248 def cmd_mlsd(self, arg):
249 self.push('125 mlsd ok')
250 self.dtp.push(MLSD_DATA)
251 self.dtp.close_when_done()
252
Serhiy Storchakac30b1782013-10-20 16:58:27 +0300253 def cmd_setlongretr(self, arg):
254 # For testing. Next RETR will return long line.
255 self.next_retr_data = 'x' * int(arg)
256 self.push('125 setlongretr ok')
257
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000258
259class DummyFTPServer(asyncore.dispatcher, threading.Thread):
260
261 handler = DummyFTPHandler
262
Sebastian Pedersena1a0eb42020-04-14 01:07:56 +0200263 def __init__(self, address, af=socket.AF_INET, encoding=DEFAULT_ENCODING):
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000264 threading.Thread.__init__(self)
265 asyncore.dispatcher.__init__(self)
Christian Heimes529525f2018-05-23 22:24:45 +0200266 self.daemon = True
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000267 self.create_socket(af, socket.SOCK_STREAM)
268 self.bind(address)
269 self.listen(5)
270 self.active = False
271 self.active_lock = threading.Lock()
272 self.host, self.port = self.socket.getsockname()[:2]
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000273 self.handler_instance = None
Sebastian Pedersena1a0eb42020-04-14 01:07:56 +0200274 self.encoding = encoding
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000275
276 def start(self):
277 assert not self.active
278 self.__flag = threading.Event()
279 threading.Thread.start(self)
280 self.__flag.wait()
281
282 def run(self):
283 self.active = True
284 self.__flag.set()
285 while self.active and asyncore.socket_map:
286 self.active_lock.acquire()
287 asyncore.loop(timeout=0.1, count=1)
288 self.active_lock.release()
289 asyncore.close_all(ignore_all=True)
290
291 def stop(self):
292 assert self.active
293 self.active = False
294 self.join()
295
Giampaolo Rodolà977c7072010-10-04 21:08:36 +0000296 def handle_accepted(self, conn, addr):
Sebastian Pedersena1a0eb42020-04-14 01:07:56 +0200297 self.handler_instance = self.handler(conn, encoding=self.encoding)
Benjamin Petersond06e3b02008-09-28 21:00:42 +0000298
299 def handle_connect(self):
300 self.close()
301 handle_read = handle_connect
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000302
303 def writable(self):
304 return 0
305
306 def handle_error(self):
Berker Peksag8f791d32014-11-01 10:45:57 +0200307 raise Exception
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000308
309
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000310if ssl is not None:
311
Christian Heimese5b5edf2013-12-02 02:56:02 +0100312 CERTFILE = os.path.join(os.path.dirname(__file__), "keycert3.pem")
313 CAFILE = os.path.join(os.path.dirname(__file__), "pycacert.pem")
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000314
315 class SSLConnection(asyncore.dispatcher):
316 """An asyncore.dispatcher subclass supporting TLS/SSL."""
317
318 _ssl_accepting = False
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +0000319 _ssl_closing = False
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000320
321 def secure_connection(self):
Christian Heimesd0486372016-09-10 23:23:33 +0200322 context = ssl.SSLContext()
323 context.load_cert_chain(CERTFILE)
324 socket = context.wrap_socket(self.socket,
325 suppress_ragged_eofs=False,
326 server_side=True,
327 do_handshake_on_connect=False)
Giampaolo Rodola'096dcb12011-06-27 11:17:51 +0200328 self.del_channel()
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000329 self.set_socket(socket)
330 self._ssl_accepting = True
331
332 def _do_ssl_handshake(self):
333 try:
334 self.socket.do_handshake()
335 except ssl.SSLError as err:
336 if err.args[0] in (ssl.SSL_ERROR_WANT_READ,
337 ssl.SSL_ERROR_WANT_WRITE):
338 return
339 elif err.args[0] == ssl.SSL_ERROR_EOF:
340 return self.handle_close()
Christian Heimes61d478c2018-01-27 15:51:38 +0100341 # TODO: SSLError does not expose alert information
342 elif "SSLV3_ALERT_BAD_CERTIFICATE" in err.args[1]:
343 return self.handle_close()
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000344 raise
Andrew Svetlov0832af62012-12-18 23:10:48 +0200345 except OSError as err:
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000346 if err.args[0] == errno.ECONNABORTED:
347 return self.handle_close()
348 else:
349 self._ssl_accepting = False
350
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +0000351 def _do_ssl_shutdown(self):
352 self._ssl_closing = True
353 try:
354 self.socket = self.socket.unwrap()
355 except ssl.SSLError as err:
356 if err.args[0] in (ssl.SSL_ERROR_WANT_READ,
357 ssl.SSL_ERROR_WANT_WRITE):
358 return
Pablo Galindo293dd232019-11-19 21:34:03 +0000359 except OSError:
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +0000360 # Any "socket error" corresponds to a SSL_ERROR_SYSCALL return
361 # from OpenSSL's SSL_shutdown(), corresponding to a
362 # closed socket condition. See also:
363 # http://www.mail-archive.com/openssl-users@openssl.org/msg60710.html
364 pass
365 self._ssl_closing = False
Benjamin Petersonb29614e2012-10-09 11:16:03 -0400366 if getattr(self, '_ccc', False) is False:
Giampaolo Rodola'096dcb12011-06-27 11:17:51 +0200367 super(SSLConnection, self).close()
368 else:
369 pass
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +0000370
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000371 def handle_read_event(self):
372 if self._ssl_accepting:
373 self._do_ssl_handshake()
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +0000374 elif self._ssl_closing:
375 self._do_ssl_shutdown()
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000376 else:
377 super(SSLConnection, self).handle_read_event()
378
379 def handle_write_event(self):
380 if self._ssl_accepting:
381 self._do_ssl_handshake()
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +0000382 elif self._ssl_closing:
383 self._do_ssl_shutdown()
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000384 else:
385 super(SSLConnection, self).handle_write_event()
386
387 def send(self, data):
388 try:
389 return super(SSLConnection, self).send(data)
390 except ssl.SSLError as err:
Antoine Pitrou5733c082010-03-22 14:49:10 +0000391 if err.args[0] in (ssl.SSL_ERROR_EOF, ssl.SSL_ERROR_ZERO_RETURN,
392 ssl.SSL_ERROR_WANT_READ,
393 ssl.SSL_ERROR_WANT_WRITE):
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000394 return 0
395 raise
396
397 def recv(self, buffer_size):
398 try:
399 return super(SSLConnection, self).recv(buffer_size)
400 except ssl.SSLError as err:
Antoine Pitrou5733c082010-03-22 14:49:10 +0000401 if err.args[0] in (ssl.SSL_ERROR_WANT_READ,
402 ssl.SSL_ERROR_WANT_WRITE):
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +0000403 return b''
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000404 if err.args[0] in (ssl.SSL_ERROR_EOF, ssl.SSL_ERROR_ZERO_RETURN):
405 self.handle_close()
406 return b''
407 raise
408
409 def handle_error(self):
Berker Peksag8f791d32014-11-01 10:45:57 +0200410 raise Exception
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000411
412 def close(self):
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +0000413 if (isinstance(self.socket, ssl.SSLSocket) and
Christian Heimes529525f2018-05-23 22:24:45 +0200414 self.socket._sslobj is not None):
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +0000415 self._do_ssl_shutdown()
Benjamin Peterson1bd93a72010-10-31 19:58:07 +0000416 else:
417 super(SSLConnection, self).close()
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000418
419
420 class DummyTLS_DTPHandler(SSLConnection, DummyDTPHandler):
421 """A DummyDTPHandler subclass supporting TLS/SSL."""
422
423 def __init__(self, conn, baseclass):
424 DummyDTPHandler.__init__(self, conn, baseclass)
425 if self.baseclass.secure_data_channel:
426 self.secure_connection()
427
428
429 class DummyTLS_FTPHandler(SSLConnection, DummyFTPHandler):
430 """A DummyFTPHandler subclass supporting TLS/SSL."""
431
432 dtp_handler = DummyTLS_DTPHandler
433
Sebastian Pedersena1a0eb42020-04-14 01:07:56 +0200434 def __init__(self, conn, encoding=DEFAULT_ENCODING):
435 DummyFTPHandler.__init__(self, conn, encoding=encoding)
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000436 self.secure_data_channel = False
Giampaolo Rodola'096dcb12011-06-27 11:17:51 +0200437 self._ccc = False
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000438
439 def cmd_auth(self, line):
440 """Set up secure control channel."""
441 self.push('234 AUTH TLS successful')
442 self.secure_connection()
443
Giampaolo Rodola'096dcb12011-06-27 11:17:51 +0200444 def cmd_ccc(self, line):
445 self.push('220 Reverting back to clear-text')
446 self._ccc = True
447 self._do_ssl_shutdown()
448
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000449 def cmd_pbsz(self, line):
450 """Negotiate size of buffer for secure data transfer.
451 For TLS/SSL the only valid value for the parameter is '0'.
452 Any other value is accepted but ignored.
453 """
454 self.push('200 PBSZ=0 successful.')
455
456 def cmd_prot(self, line):
457 """Setup un/secure data channel."""
458 arg = line.upper()
459 if arg == 'C':
460 self.push('200 Protection set to Clear')
461 self.secure_data_channel = False
462 elif arg == 'P':
463 self.push('200 Protection set to Private')
464 self.secure_data_channel = True
465 else:
466 self.push("502 Unrecognized PROT type (use C or P).")
467
468
469 class DummyTLS_FTPServer(DummyFTPServer):
470 handler = DummyTLS_FTPHandler
471
472
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000473class TestFTPClass(TestCase):
474
Sebastian Pedersena1a0eb42020-04-14 01:07:56 +0200475 def setUp(self, encoding=DEFAULT_ENCODING):
476 self.server = DummyFTPServer((HOST, 0), encoding=encoding)
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000477 self.server.start()
Sebastian Pedersena1a0eb42020-04-14 01:07:56 +0200478 self.client = ftplib.FTP(timeout=TIMEOUT, encoding=encoding)
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000479 self.client.connect(self.server.host, self.server.port)
480
481 def tearDown(self):
482 self.client.close()
483 self.server.stop()
Victor Stinnerd403a292017-09-13 03:58:25 -0700484 # Explicitly clear the attribute to prevent dangling thread
485 self.server = None
Victor Stinner73528642017-06-30 17:36:57 +0200486 asyncore.close_all(ignore_all=True)
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000487
Giampaolo Rodola'8bc85852012-01-09 17:10:10 +0100488 def check_data(self, received, expected):
489 self.assertEqual(len(received), len(expected))
490 self.assertEqual(received, expected)
491
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000492 def test_getwelcome(self):
493 self.assertEqual(self.client.getwelcome(), '220 welcome')
494
495 def test_sanitize(self):
496 self.assertEqual(self.client.sanitize('foo'), repr('foo'))
497 self.assertEqual(self.client.sanitize('pass 12345'), repr('pass *****'))
498 self.assertEqual(self.client.sanitize('PASS 12345'), repr('PASS *****'))
499
500 def test_exceptions(self):
Dong-hee Na2b1e6e92017-07-23 02:20:22 +0900501 self.assertRaises(ValueError, self.client.sendcmd, 'echo 40\r\n0')
502 self.assertRaises(ValueError, self.client.sendcmd, 'echo 40\n0')
503 self.assertRaises(ValueError, self.client.sendcmd, 'echo 40\r0')
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000504 self.assertRaises(ftplib.error_temp, self.client.sendcmd, 'echo 400')
505 self.assertRaises(ftplib.error_temp, self.client.sendcmd, 'echo 499')
506 self.assertRaises(ftplib.error_perm, self.client.sendcmd, 'echo 500')
507 self.assertRaises(ftplib.error_perm, self.client.sendcmd, 'echo 599')
508 self.assertRaises(ftplib.error_proto, self.client.sendcmd, 'echo 999')
509
510 def test_all_errors(self):
511 exceptions = (ftplib.error_reply, ftplib.error_temp, ftplib.error_perm,
Dong-hee Na2b1e6e92017-07-23 02:20:22 +0900512 ftplib.error_proto, ftplib.Error, OSError,
513 EOFError)
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000514 for x in exceptions:
515 try:
516 raise x('exception not included in all_errors set')
517 except ftplib.all_errors:
518 pass
519
520 def test_set_pasv(self):
521 # passive mode is supposed to be enabled by default
522 self.assertTrue(self.client.passiveserver)
523 self.client.set_pasv(True)
524 self.assertTrue(self.client.passiveserver)
525 self.client.set_pasv(False)
526 self.assertFalse(self.client.passiveserver)
527
528 def test_voidcmd(self):
529 self.client.voidcmd('echo 200')
530 self.client.voidcmd('echo 299')
531 self.assertRaises(ftplib.error_reply, self.client.voidcmd, 'echo 199')
532 self.assertRaises(ftplib.error_reply, self.client.voidcmd, 'echo 300')
533
534 def test_login(self):
535 self.client.login()
536
537 def test_acct(self):
538 self.client.acct('passwd')
539
540 def test_rename(self):
541 self.client.rename('a', 'b')
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000542 self.server.handler_instance.next_response = '200'
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000543 self.assertRaises(ftplib.error_reply, self.client.rename, 'a', 'b')
544
545 def test_delete(self):
546 self.client.delete('foo')
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000547 self.server.handler_instance.next_response = '199'
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000548 self.assertRaises(ftplib.error_reply, self.client.delete, 'foo')
549
550 def test_size(self):
551 self.client.size('foo')
552
553 def test_mkd(self):
554 dir = self.client.mkd('/foo')
555 self.assertEqual(dir, '/foo')
556
557 def test_rmd(self):
558 self.client.rmd('foo')
559
Senthil Kumaran0d538602013-08-12 22:25:27 -0700560 def test_cwd(self):
561 dir = self.client.cwd('/foo')
562 self.assertEqual(dir, '250 cwd ok')
563
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000564 def test_pwd(self):
565 dir = self.client.pwd()
566 self.assertEqual(dir, 'pwd ok')
567
568 def test_quit(self):
569 self.assertEqual(self.client.quit(), '221 quit ok')
570 # Ensure the connection gets closed; sock attribute should be None
571 self.assertEqual(self.client.sock, None)
572
Giampaolo Rodola'0b5c21f2011-05-07 19:03:47 +0200573 def test_abort(self):
574 self.client.abort()
575
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000576 def test_retrbinary(self):
577 def callback(data):
Sebastian Pedersena1a0eb42020-04-14 01:07:56 +0200578 received.append(data.decode(self.client.encoding))
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000579 received = []
580 self.client.retrbinary('retr', callback)
Giampaolo Rodola'8bc85852012-01-09 17:10:10 +0100581 self.check_data(''.join(received), RETR_DATA)
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000582
Antoine Pitrou648bcd72009-11-27 13:23:26 +0000583 def test_retrbinary_rest(self):
584 def callback(data):
Sebastian Pedersena1a0eb42020-04-14 01:07:56 +0200585 received.append(data.decode(self.client.encoding))
Antoine Pitrou648bcd72009-11-27 13:23:26 +0000586 for rest in (0, 10, 20):
587 received = []
588 self.client.retrbinary('retr', callback, rest=rest)
Giampaolo Rodola'8bc85852012-01-09 17:10:10 +0100589 self.check_data(''.join(received), RETR_DATA[rest:])
Antoine Pitrou648bcd72009-11-27 13:23:26 +0000590
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000591 def test_retrlines(self):
592 received = []
593 self.client.retrlines('retr', received.append)
Giampaolo Rodola'8bc85852012-01-09 17:10:10 +0100594 self.check_data(''.join(received), RETR_DATA.replace('\r\n', ''))
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000595
596 def test_storbinary(self):
Sebastian Pedersena1a0eb42020-04-14 01:07:56 +0200597 f = io.BytesIO(RETR_DATA.encode(self.client.encoding))
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000598 self.client.storbinary('stor', f)
Giampaolo Rodola'8bc85852012-01-09 17:10:10 +0100599 self.check_data(self.server.handler_instance.last_received_data, RETR_DATA)
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000600 # test new callback arg
601 flag = []
602 f.seek(0)
603 self.client.storbinary('stor', f, callback=lambda x: flag.append(None))
604 self.assertTrue(flag)
605
Antoine Pitrou648bcd72009-11-27 13:23:26 +0000606 def test_storbinary_rest(self):
Sebastian Pedersena1a0eb42020-04-14 01:07:56 +0200607 data = RETR_DATA.replace('\r\n', '\n').encode(self.client.encoding)
608 f = io.BytesIO(data)
Antoine Pitrou648bcd72009-11-27 13:23:26 +0000609 for r in (30, '30'):
610 f.seek(0)
611 self.client.storbinary('stor', f, rest=r)
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000612 self.assertEqual(self.server.handler_instance.rest, str(r))
Antoine Pitrou648bcd72009-11-27 13:23:26 +0000613
Giampaolo Rodolàf96482e2010-08-04 10:36:18 +0000614 def test_storlines(self):
Sebastian Pedersena1a0eb42020-04-14 01:07:56 +0200615 data = RETR_DATA.replace('\r\n', '\n').encode(self.client.encoding)
616 f = io.BytesIO(data)
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000617 self.client.storlines('stor', f)
Giampaolo Rodola'8bc85852012-01-09 17:10:10 +0100618 self.check_data(self.server.handler_instance.last_received_data, RETR_DATA)
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000619 # test new callback arg
620 flag = []
621 f.seek(0)
622 self.client.storlines('stor foo', f, callback=lambda x: flag.append(None))
623 self.assertTrue(flag)
624
Victor Stinnered3a3032013-04-02 22:13:27 +0200625 f = io.StringIO(RETR_DATA.replace('\r\n', '\n'))
626 # storlines() expects a binary file, not a text file
Hai Shi46605972020-08-04 00:49:18 +0800627 with warnings_helper.check_warnings(('', BytesWarning), quiet=True):
Florent Xicluna5f3fef32013-07-06 15:08:21 +0200628 self.assertRaises(TypeError, self.client.storlines, 'stor foo', f)
Victor Stinnered3a3032013-04-02 22:13:27 +0200629
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000630 def test_nlst(self):
631 self.client.nlst()
632 self.assertEqual(self.client.nlst(), NLST_DATA.split('\r\n')[:-1])
633
634 def test_dir(self):
635 l = []
636 self.client.dir(lambda x: l.append(x))
637 self.assertEqual(''.join(l), LIST_DATA.replace('\r\n', ''))
638
Giampaolo Rodola'd78def92011-05-06 19:49:08 +0200639 def test_mlsd(self):
640 list(self.client.mlsd())
641 list(self.client.mlsd(path='/'))
642 list(self.client.mlsd(path='/', facts=['size', 'type']))
643
644 ls = list(self.client.mlsd())
645 for name, facts in ls:
Giampaolo Rodola'a55efb32011-05-07 16:06:59 +0200646 self.assertIsInstance(name, str)
647 self.assertIsInstance(facts, dict)
Giampaolo Rodola'd78def92011-05-06 19:49:08 +0200648 self.assertTrue(name)
Giampaolo Rodola'a55efb32011-05-07 16:06:59 +0200649 self.assertIn('type', facts)
650 self.assertIn('perm', facts)
651 self.assertIn('unique', facts)
Giampaolo Rodola'd78def92011-05-06 19:49:08 +0200652
653 def set_data(data):
654 self.server.handler_instance.next_data = data
655
656 def test_entry(line, type=None, perm=None, unique=None, name=None):
657 type = 'type' if type is None else type
658 perm = 'perm' if perm is None else perm
659 unique = 'unique' if unique is None else unique
660 name = 'name' if name is None else name
661 set_data(line)
662 _name, facts = next(self.client.mlsd())
663 self.assertEqual(_name, name)
664 self.assertEqual(facts['type'], type)
665 self.assertEqual(facts['perm'], perm)
666 self.assertEqual(facts['unique'], unique)
667
668 # plain
669 test_entry('type=type;perm=perm;unique=unique; name\r\n')
670 # "=" in fact value
671 test_entry('type=ty=pe;perm=perm;unique=unique; name\r\n', type="ty=pe")
672 test_entry('type==type;perm=perm;unique=unique; name\r\n', type="=type")
673 test_entry('type=t=y=pe;perm=perm;unique=unique; name\r\n', type="t=y=pe")
674 test_entry('type=====;perm=perm;unique=unique; name\r\n', type="====")
675 # spaces in name
676 test_entry('type=type;perm=perm;unique=unique; na me\r\n', name="na me")
677 test_entry('type=type;perm=perm;unique=unique; name \r\n', name="name ")
678 test_entry('type=type;perm=perm;unique=unique; name\r\n', name=" name")
679 test_entry('type=type;perm=perm;unique=unique; n am e\r\n', name="n am e")
680 # ";" in name
681 test_entry('type=type;perm=perm;unique=unique; na;me\r\n', name="na;me")
682 test_entry('type=type;perm=perm;unique=unique; ;name\r\n', name=";name")
683 test_entry('type=type;perm=perm;unique=unique; ;name;\r\n', name=";name;")
684 test_entry('type=type;perm=perm;unique=unique; ;;;;\r\n', name=";;;;")
685 # case sensitiveness
686 set_data('Type=type;TyPe=perm;UNIQUE=unique; name\r\n')
687 _name, facts = next(self.client.mlsd())
Giampaolo Rodola'a55efb32011-05-07 16:06:59 +0200688 for x in facts:
689 self.assertTrue(x.islower())
Giampaolo Rodola'd78def92011-05-06 19:49:08 +0200690 # no data (directory empty)
691 set_data('')
692 self.assertRaises(StopIteration, next, self.client.mlsd())
693 set_data('')
694 for x in self.client.mlsd():
Berker Peksag8f791d32014-11-01 10:45:57 +0200695 self.fail("unexpected data %s" % x)
Giampaolo Rodola'd78def92011-05-06 19:49:08 +0200696
Benjamin Peterson3a53fbb2008-09-27 22:04:16 +0000697 def test_makeport(self):
Brett Cannon918e2d42010-10-29 23:26:25 +0000698 with self.client.makeport():
699 # IPv4 is in use, just make sure send_eprt has not been used
700 self.assertEqual(self.server.handler_instance.last_received_cmd,
701 'port')
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000702
703 def test_makepasv(self):
704 host, port = self.client.makepasv()
Giampaolo Rodola'0d4f08c2013-05-16 15:12:01 +0200705 conn = socket.create_connection((host, port), timeout=TIMEOUT)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000706 conn.close()
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000707 # IPv4 is in use, just make sure send_epsv has not been used
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000708 self.assertEqual(self.server.handler_instance.last_received_cmd, 'pasv')
709
710 def test_with_statement(self):
711 self.client.quit()
712
713 def is_client_connected():
714 if self.client.sock is None:
715 return False
716 try:
717 self.client.sendcmd('noop')
Andrew Svetlov0832af62012-12-18 23:10:48 +0200718 except (OSError, EOFError):
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000719 return False
720 return True
721
722 # base test
Giampaolo Rodola'0d4f08c2013-05-16 15:12:01 +0200723 with ftplib.FTP(timeout=TIMEOUT) as self.client:
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000724 self.client.connect(self.server.host, self.server.port)
725 self.client.sendcmd('noop')
726 self.assertTrue(is_client_connected())
727 self.assertEqual(self.server.handler_instance.last_received_cmd, 'quit')
728 self.assertFalse(is_client_connected())
729
730 # QUIT sent inside the with block
Giampaolo Rodola'0d4f08c2013-05-16 15:12:01 +0200731 with ftplib.FTP(timeout=TIMEOUT) as self.client:
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000732 self.client.connect(self.server.host, self.server.port)
733 self.client.sendcmd('noop')
734 self.client.quit()
735 self.assertEqual(self.server.handler_instance.last_received_cmd, 'quit')
736 self.assertFalse(is_client_connected())
737
738 # force a wrong response code to be sent on QUIT: error_perm
739 # is expected and the connection is supposed to be closed
740 try:
Giampaolo Rodola'0d4f08c2013-05-16 15:12:01 +0200741 with ftplib.FTP(timeout=TIMEOUT) as self.client:
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000742 self.client.connect(self.server.host, self.server.port)
743 self.client.sendcmd('noop')
744 self.server.handler_instance.next_response = '550 error on quit'
745 except ftplib.error_perm as err:
746 self.assertEqual(str(err), '550 error on quit')
747 else:
748 self.fail('Exception not raised')
749 # needed to give the threaded server some time to set the attribute
750 # which otherwise would still be == 'noop'
751 time.sleep(0.1)
752 self.assertEqual(self.server.handler_instance.last_received_cmd, 'quit')
753 self.assertFalse(is_client_connected())
Guido van Rossumd8faa362007-04-27 19:54:29 +0000754
Giampaolo Rodolà396ff062011-02-28 19:19:51 +0000755 def test_source_address(self):
756 self.client.quit()
Serhiy Storchaka16994912020-04-25 10:06:29 +0300757 port = socket_helper.find_unused_port()
Antoine Pitrou6dca5272011-04-03 18:29:45 +0200758 try:
759 self.client.connect(self.server.host, self.server.port,
760 source_address=(HOST, port))
761 self.assertEqual(self.client.sock.getsockname()[1], port)
762 self.client.quit()
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200763 except OSError as e:
Antoine Pitrou6dca5272011-04-03 18:29:45 +0200764 if e.errno == errno.EADDRINUSE:
765 self.skipTest("couldn't bind to port %d" % port)
766 raise
Giampaolo Rodolà396ff062011-02-28 19:19:51 +0000767
768 def test_source_address_passive_connection(self):
Serhiy Storchaka16994912020-04-25 10:06:29 +0300769 port = socket_helper.find_unused_port()
Giampaolo Rodolà396ff062011-02-28 19:19:51 +0000770 self.client.source_address = (HOST, port)
Antoine Pitrou6dca5272011-04-03 18:29:45 +0200771 try:
772 with self.client.transfercmd('list') as sock:
773 self.assertEqual(sock.getsockname()[1], port)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200774 except OSError as e:
Antoine Pitrou6dca5272011-04-03 18:29:45 +0200775 if e.errno == errno.EADDRINUSE:
776 self.skipTest("couldn't bind to port %d" % port)
777 raise
Giampaolo Rodolà396ff062011-02-28 19:19:51 +0000778
Giampaolo Rodolàbbc47822010-08-23 22:10:32 +0000779 def test_parse257(self):
780 self.assertEqual(ftplib.parse257('257 "/foo/bar"'), '/foo/bar')
781 self.assertEqual(ftplib.parse257('257 "/foo/bar" created'), '/foo/bar')
782 self.assertEqual(ftplib.parse257('257 ""'), '')
783 self.assertEqual(ftplib.parse257('257 "" created'), '')
784 self.assertRaises(ftplib.error_reply, ftplib.parse257, '250 "/foo/bar"')
785 # The 257 response is supposed to include the directory
786 # name and in case it contains embedded double-quotes
787 # they must be doubled (see RFC-959, chapter 7, appendix 2).
788 self.assertEqual(ftplib.parse257('257 "/foo/b""ar"'), '/foo/b"ar')
789 self.assertEqual(ftplib.parse257('257 "/foo/b""ar" created'), '/foo/b"ar')
790
Serhiy Storchakac30b1782013-10-20 16:58:27 +0300791 def test_line_too_long(self):
792 self.assertRaises(ftplib.Error, self.client.sendcmd,
793 'x' * self.client.maxline * 2)
794
795 def test_retrlines_too_long(self):
796 self.client.sendcmd('SETLONGRETR %d' % (self.client.maxline * 2))
797 received = []
798 self.assertRaises(ftplib.Error,
799 self.client.retrlines, 'retr', received.append)
800
801 def test_storlines_too_long(self):
802 f = io.BytesIO(b'x' * self.client.maxline * 2)
803 self.assertRaises(ftplib.Error, self.client.storlines, 'stor', f)
804
Sebastian Pedersena1a0eb42020-04-14 01:07:56 +0200805 def test_encoding_param(self):
806 encodings = ['latin-1', 'utf-8']
807 for encoding in encodings:
808 with self.subTest(encoding=encoding):
809 self.tearDown()
810 self.setUp(encoding=encoding)
811 self.assertEqual(encoding, self.client.encoding)
812 self.test_retrbinary()
813 self.test_storbinary()
814 self.test_retrlines()
815 new_dir = self.client.mkd('/non-ascii dir \xAE')
816 self.check_data(new_dir, '/non-ascii dir \xAE')
817 # Check default encoding
818 client = ftplib.FTP(timeout=TIMEOUT)
819 self.assertEqual(DEFAULT_ENCODING, client.encoding)
820
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000821
Serhiy Storchaka16994912020-04-25 10:06:29 +0300822@skipUnless(socket_helper.IPV6_ENABLED, "IPv6 not enabled")
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000823class TestIPv6Environment(TestCase):
824
825 def setUp(self):
Sebastian Pedersena1a0eb42020-04-14 01:07:56 +0200826 self.server = DummyFTPServer((HOSTv6, 0),
827 af=socket.AF_INET6,
828 encoding=DEFAULT_ENCODING)
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000829 self.server.start()
Sebastian Pedersena1a0eb42020-04-14 01:07:56 +0200830 self.client = ftplib.FTP(timeout=TIMEOUT, encoding=DEFAULT_ENCODING)
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000831 self.client.connect(self.server.host, self.server.port)
832
833 def tearDown(self):
834 self.client.close()
835 self.server.stop()
Victor Stinnerd403a292017-09-13 03:58:25 -0700836 # Explicitly clear the attribute to prevent dangling thread
837 self.server = None
Victor Stinner73528642017-06-30 17:36:57 +0200838 asyncore.close_all(ignore_all=True)
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000839
840 def test_af(self):
841 self.assertEqual(self.client.af, socket.AF_INET6)
842
843 def test_makeport(self):
Brett Cannon918e2d42010-10-29 23:26:25 +0000844 with self.client.makeport():
845 self.assertEqual(self.server.handler_instance.last_received_cmd,
846 'eprt')
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000847
848 def test_makepasv(self):
849 host, port = self.client.makepasv()
Giampaolo Rodola'0d4f08c2013-05-16 15:12:01 +0200850 conn = socket.create_connection((host, port), timeout=TIMEOUT)
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000851 conn.close()
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000852 self.assertEqual(self.server.handler_instance.last_received_cmd, 'epsv')
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000853
854 def test_transfer(self):
855 def retr():
856 def callback(data):
Sebastian Pedersena1a0eb42020-04-14 01:07:56 +0200857 received.append(data.decode(self.client.encoding))
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000858 received = []
859 self.client.retrbinary('retr', callback)
Giampaolo Rodola'8bc85852012-01-09 17:10:10 +0100860 self.assertEqual(len(''.join(received)), len(RETR_DATA))
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000861 self.assertEqual(''.join(received), RETR_DATA)
862 self.client.set_pasv(True)
863 retr()
864 self.client.set_pasv(False)
865 retr()
866
867
Serhiy Storchaka43767632013-11-03 21:31:38 +0200868@skipUnless(ssl, "SSL not available")
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000869class TestTLS_FTPClassMixin(TestFTPClass):
870 """Repeat TestFTPClass tests starting the TLS layer for both control
871 and data connections first.
872 """
873
Sebastian Pedersena1a0eb42020-04-14 01:07:56 +0200874 def setUp(self, encoding=DEFAULT_ENCODING):
875 self.server = DummyTLS_FTPServer((HOST, 0), encoding=encoding)
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000876 self.server.start()
Sebastian Pedersena1a0eb42020-04-14 01:07:56 +0200877 self.client = ftplib.FTP_TLS(timeout=TIMEOUT, encoding=encoding)
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000878 self.client.connect(self.server.host, self.server.port)
879 # enable TLS
880 self.client.auth()
881 self.client.prot_p()
882
883
Serhiy Storchaka43767632013-11-03 21:31:38 +0200884@skipUnless(ssl, "SSL not available")
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000885class TestTLS_FTPClass(TestCase):
886 """Specific TLS_FTP class tests."""
887
Sebastian Pedersena1a0eb42020-04-14 01:07:56 +0200888 def setUp(self, encoding=DEFAULT_ENCODING):
889 self.server = DummyTLS_FTPServer((HOST, 0), encoding=encoding)
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000890 self.server.start()
Giampaolo Rodola'0d4f08c2013-05-16 15:12:01 +0200891 self.client = ftplib.FTP_TLS(timeout=TIMEOUT)
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000892 self.client.connect(self.server.host, self.server.port)
893
894 def tearDown(self):
895 self.client.close()
896 self.server.stop()
Victor Stinnerd403a292017-09-13 03:58:25 -0700897 # Explicitly clear the attribute to prevent dangling thread
898 self.server = None
Victor Stinner73528642017-06-30 17:36:57 +0200899 asyncore.close_all(ignore_all=True)
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000900
901 def test_control_connection(self):
Ezio Melottie9615932010-01-24 19:26:24 +0000902 self.assertNotIsInstance(self.client.sock, ssl.SSLSocket)
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000903 self.client.auth()
Ezio Melottie9615932010-01-24 19:26:24 +0000904 self.assertIsInstance(self.client.sock, ssl.SSLSocket)
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000905
906 def test_data_connection(self):
907 # clear text
Brett Cannon918e2d42010-10-29 23:26:25 +0000908 with self.client.transfercmd('list') as sock:
909 self.assertNotIsInstance(sock, ssl.SSLSocket)
Sebastian Pedersena1a0eb42020-04-14 01:07:56 +0200910 self.assertEqual(sock.recv(1024),
911 LIST_DATA.encode(self.client.encoding))
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +0000912 self.assertEqual(self.client.voidresp(), "226 transfer complete")
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000913
914 # secured, after PROT P
915 self.client.prot_p()
Brett Cannon918e2d42010-10-29 23:26:25 +0000916 with self.client.transfercmd('list') as sock:
917 self.assertIsInstance(sock, ssl.SSLSocket)
Christian Heimes1590c392018-08-16 19:43:44 +0200918 # consume from SSL socket to finalize handshake and avoid
919 # "SSLError [SSL] shutdown while in init"
Sebastian Pedersena1a0eb42020-04-14 01:07:56 +0200920 self.assertEqual(sock.recv(1024),
921 LIST_DATA.encode(self.client.encoding))
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +0000922 self.assertEqual(self.client.voidresp(), "226 transfer complete")
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000923
924 # PROT C is issued, the connection must be in cleartext again
925 self.client.prot_c()
Brett Cannon918e2d42010-10-29 23:26:25 +0000926 with self.client.transfercmd('list') as sock:
927 self.assertNotIsInstance(sock, ssl.SSLSocket)
Sebastian Pedersena1a0eb42020-04-14 01:07:56 +0200928 self.assertEqual(sock.recv(1024),
929 LIST_DATA.encode(self.client.encoding))
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +0000930 self.assertEqual(self.client.voidresp(), "226 transfer complete")
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000931
932 def test_login(self):
933 # login() is supposed to implicitly secure the control connection
Ezio Melottie9615932010-01-24 19:26:24 +0000934 self.assertNotIsInstance(self.client.sock, ssl.SSLSocket)
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000935 self.client.login()
Ezio Melottie9615932010-01-24 19:26:24 +0000936 self.assertIsInstance(self.client.sock, ssl.SSLSocket)
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000937 # make sure that AUTH TLS doesn't get issued again
938 self.client.login()
939
940 def test_auth_issued_twice(self):
941 self.client.auth()
942 self.assertRaises(ValueError, self.client.auth)
943
Giampaolo Rodolàa67299e2010-05-26 18:06:04 +0000944 def test_context(self):
945 self.client.quit()
Christian Heimesa170fa12017-09-15 20:27:30 +0200946 ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
947 ctx.check_hostname = False
948 ctx.verify_mode = ssl.CERT_NONE
Giampaolo Rodolàa67299e2010-05-26 18:06:04 +0000949 self.assertRaises(ValueError, ftplib.FTP_TLS, keyfile=CERTFILE,
950 context=ctx)
951 self.assertRaises(ValueError, ftplib.FTP_TLS, certfile=CERTFILE,
952 context=ctx)
953 self.assertRaises(ValueError, ftplib.FTP_TLS, certfile=CERTFILE,
954 keyfile=CERTFILE, context=ctx)
955
Giampaolo Rodola'0d4f08c2013-05-16 15:12:01 +0200956 self.client = ftplib.FTP_TLS(context=ctx, timeout=TIMEOUT)
Giampaolo Rodolàa67299e2010-05-26 18:06:04 +0000957 self.client.connect(self.server.host, self.server.port)
958 self.assertNotIsInstance(self.client.sock, ssl.SSLSocket)
959 self.client.auth()
960 self.assertIs(self.client.sock.context, ctx)
961 self.assertIsInstance(self.client.sock, ssl.SSLSocket)
962
963 self.client.prot_p()
Brett Cannon918e2d42010-10-29 23:26:25 +0000964 with self.client.transfercmd('list') as sock:
965 self.assertIs(sock.context, ctx)
966 self.assertIsInstance(sock, ssl.SSLSocket)
Giampaolo Rodolàa67299e2010-05-26 18:06:04 +0000967
Giampaolo Rodola'096dcb12011-06-27 11:17:51 +0200968 def test_ccc(self):
969 self.assertRaises(ValueError, self.client.ccc)
970 self.client.login(secure=True)
971 self.assertIsInstance(self.client.sock, ssl.SSLSocket)
972 self.client.ccc()
973 self.assertRaises(ValueError, self.client.sock.unwrap)
Giampaolo Rodola'096dcb12011-06-27 11:17:51 +0200974
Victor Stinner51500f32018-01-29 13:21:34 +0100975 @skipUnless(False, "FIXME: bpo-32706")
Christian Heimese5b5edf2013-12-02 02:56:02 +0100976 def test_check_hostname(self):
977 self.client.quit()
Christian Heimesa170fa12017-09-15 20:27:30 +0200978 ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
979 self.assertEqual(ctx.verify_mode, ssl.CERT_REQUIRED)
980 self.assertEqual(ctx.check_hostname, True)
Christian Heimese5b5edf2013-12-02 02:56:02 +0100981 ctx.load_verify_locations(CAFILE)
982 self.client = ftplib.FTP_TLS(context=ctx, timeout=TIMEOUT)
983
984 # 127.0.0.1 doesn't match SAN
985 self.client.connect(self.server.host, self.server.port)
986 with self.assertRaises(ssl.CertificateError):
987 self.client.auth()
988 # exception quits connection
989
990 self.client.connect(self.server.host, self.server.port)
991 self.client.prot_p()
992 with self.assertRaises(ssl.CertificateError):
993 with self.client.transfercmd("list") as sock:
994 pass
995 self.client.quit()
996
997 self.client.connect("localhost", self.server.port)
998 self.client.auth()
999 self.client.quit()
1000
1001 self.client.connect("localhost", self.server.port)
1002 self.client.prot_p()
1003 with self.client.transfercmd("list") as sock:
1004 pass
1005
Antoine Pitrouf988cd02009-11-17 20:21:14 +00001006
Benjamin Petersonbe17a112008-09-27 21:49:47 +00001007class TestTimeouts(TestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001008
1009 def setUp(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001010 self.evt = threading.Event()
Christian Heimes5e696852008-04-09 08:37:03 +00001011 self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Antoine Pitrou08d02722012-12-19 20:44:02 +01001012 self.sock.settimeout(20)
Serhiy Storchaka16994912020-04-25 10:06:29 +03001013 self.port = socket_helper.bind_port(self.sock)
Antoine Pitrou08d02722012-12-19 20:44:02 +01001014 self.server_thread = threading.Thread(target=self.server)
Christian Heimes529525f2018-05-23 22:24:45 +02001015 self.server_thread.daemon = True
Antoine Pitrou08d02722012-12-19 20:44:02 +01001016 self.server_thread.start()
Christian Heimes836baa52008-02-26 08:18:30 +00001017 # Wait for the server to be ready.
1018 self.evt.wait()
1019 self.evt.clear()
Antoine Pitrou08d02722012-12-19 20:44:02 +01001020 self.old_port = ftplib.FTP.port
Christian Heimes5e696852008-04-09 08:37:03 +00001021 ftplib.FTP.port = self.port
Guido van Rossumd8faa362007-04-27 19:54:29 +00001022
1023 def tearDown(self):
Antoine Pitrou08d02722012-12-19 20:44:02 +01001024 ftplib.FTP.port = self.old_port
1025 self.server_thread.join()
Victor Stinnerb157ce12017-09-13 06:43:58 -07001026 # Explicitly clear the attribute to prevent dangling thread
1027 self.server_thread = None
Guido van Rossumd8faa362007-04-27 19:54:29 +00001028
Antoine Pitrou08d02722012-12-19 20:44:02 +01001029 def server(self):
Benjamin Petersonbe17a112008-09-27 21:49:47 +00001030 # This method sets the evt 3 times:
1031 # 1) when the connection is ready to be accepted.
1032 # 2) when it is safe for the caller to close the connection
1033 # 3) when we have closed the socket
Charles-François Natali6e204602014-07-23 19:28:13 +01001034 self.sock.listen()
Benjamin Petersonbe17a112008-09-27 21:49:47 +00001035 # (1) Signal the caller that we are ready to accept the connection.
Antoine Pitrou08d02722012-12-19 20:44:02 +01001036 self.evt.set()
Benjamin Petersonbe17a112008-09-27 21:49:47 +00001037 try:
Antoine Pitrou08d02722012-12-19 20:44:02 +01001038 conn, addr = self.sock.accept()
Christian Heimes03c8ddd2020-11-20 09:26:07 +01001039 except TimeoutError:
Benjamin Petersonbe17a112008-09-27 21:49:47 +00001040 pass
1041 else:
Antoine Pitrou08d02722012-12-19 20:44:02 +01001042 conn.sendall(b"1 Hola mundo\n")
1043 conn.shutdown(socket.SHUT_WR)
Benjamin Petersonbe17a112008-09-27 21:49:47 +00001044 # (2) Signal the caller that it is safe to close the socket.
Antoine Pitrou08d02722012-12-19 20:44:02 +01001045 self.evt.set()
Benjamin Petersonbe17a112008-09-27 21:49:47 +00001046 conn.close()
1047 finally:
Antoine Pitrou08d02722012-12-19 20:44:02 +01001048 self.sock.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001049
1050 def testTimeoutDefault(self):
Georg Brandlf78e02b2008-06-10 17:40:04 +00001051 # default -- use global socket timeout
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +02001052 self.assertIsNone(socket.getdefaulttimeout())
Georg Brandlf78e02b2008-06-10 17:40:04 +00001053 socket.setdefaulttimeout(30)
1054 try:
Antoine Pitrouf6fbf562013-08-22 00:39:46 +02001055 ftp = ftplib.FTP(HOST)
Georg Brandlf78e02b2008-06-10 17:40:04 +00001056 finally:
1057 socket.setdefaulttimeout(None)
1058 self.assertEqual(ftp.sock.gettimeout(), 30)
1059 self.evt.wait()
1060 ftp.close()
1061
1062 def testTimeoutNone(self):
1063 # no timeout -- do not use global socket timeout
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +02001064 self.assertIsNone(socket.getdefaulttimeout())
Georg Brandlf78e02b2008-06-10 17:40:04 +00001065 socket.setdefaulttimeout(30)
1066 try:
Antoine Pitrouf6fbf562013-08-22 00:39:46 +02001067 ftp = ftplib.FTP(HOST, timeout=None)
Georg Brandlf78e02b2008-06-10 17:40:04 +00001068 finally:
1069 socket.setdefaulttimeout(None)
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +02001070 self.assertIsNone(ftp.sock.gettimeout())
Christian Heimes836baa52008-02-26 08:18:30 +00001071 self.evt.wait()
Georg Brandlf78e02b2008-06-10 17:40:04 +00001072 ftp.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001073
1074 def testTimeoutValue(self):
1075 # a value
Christian Heimes5e696852008-04-09 08:37:03 +00001076 ftp = ftplib.FTP(HOST, timeout=30)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001077 self.assertEqual(ftp.sock.gettimeout(), 30)
Christian Heimes836baa52008-02-26 08:18:30 +00001078 self.evt.wait()
Georg Brandlf78e02b2008-06-10 17:40:04 +00001079 ftp.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001080
Dong-hee Naa190e2a2020-01-14 04:34:34 +09001081 # bpo-39259
1082 with self.assertRaises(ValueError):
1083 ftplib.FTP(HOST, timeout=0)
1084
Guido van Rossumd8faa362007-04-27 19:54:29 +00001085 def testTimeoutConnect(self):
1086 ftp = ftplib.FTP()
Christian Heimes5e696852008-04-09 08:37:03 +00001087 ftp.connect(HOST, timeout=30)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001088 self.assertEqual(ftp.sock.gettimeout(), 30)
Christian Heimes836baa52008-02-26 08:18:30 +00001089 self.evt.wait()
Georg Brandlf78e02b2008-06-10 17:40:04 +00001090 ftp.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001091
1092 def testTimeoutDifferentOrder(self):
1093 ftp = ftplib.FTP(timeout=30)
Christian Heimes5e696852008-04-09 08:37:03 +00001094 ftp.connect(HOST)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001095 self.assertEqual(ftp.sock.gettimeout(), 30)
Christian Heimes836baa52008-02-26 08:18:30 +00001096 self.evt.wait()
Georg Brandlf78e02b2008-06-10 17:40:04 +00001097 ftp.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001098
1099 def testTimeoutDirectAccess(self):
1100 ftp = ftplib.FTP()
1101 ftp.timeout = 30
Christian Heimes5e696852008-04-09 08:37:03 +00001102 ftp.connect(HOST)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001103 self.assertEqual(ftp.sock.gettimeout(), 30)
Christian Heimes836baa52008-02-26 08:18:30 +00001104 self.evt.wait()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001105 ftp.close()
1106
1107
Martin Panter19e69c52015-11-14 12:46:42 +00001108class MiscTestCase(TestCase):
1109 def test__all__(self):
Victor Stinnerfbf43f02020-08-17 07:20:40 +02001110 not_exported = {
1111 'MSG_OOB', 'FTP_PORT', 'MAXLINE', 'CRLF', 'B_CRLF', 'Error',
1112 'parse150', 'parse227', 'parse229', 'parse257', 'print_line',
1113 'ftpcp', 'test'}
1114 support.check__all__(self, ftplib, not_exported=not_exported)
Martin Panter19e69c52015-11-14 12:46:42 +00001115
1116
Benjamin Petersonbe17a112008-09-27 21:49:47 +00001117def test_main():
Berker Peksag8f791d32014-11-01 10:45:57 +02001118 tests = [TestFTPClass, TestTimeouts,
Serhiy Storchaka43767632013-11-03 21:31:38 +02001119 TestIPv6Environment,
Martin Panter19e69c52015-11-14 12:46:42 +00001120 TestTLS_FTPClassMixin, TestTLS_FTPClass,
1121 MiscTestCase]
Antoine Pitrouf988cd02009-11-17 20:21:14 +00001122
Hai Shie80697d2020-05-28 06:10:27 +08001123 thread_info = threading_helper.threading_setup()
Benjamin Petersonbe17a112008-09-27 21:49:47 +00001124 try:
1125 support.run_unittest(*tests)
1126 finally:
Hai Shie80697d2020-05-28 06:10:27 +08001127 threading_helper.threading_cleanup(*thread_info)
Benjamin Petersonbe17a112008-09-27 21:49:47 +00001128
Guido van Rossumd8faa362007-04-27 19:54:29 +00001129
1130if __name__ == '__main__':
1131 test_main()