blob: 1a8e2f91d386dfb013b0d38c30291cff2bf5b7c1 [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
Antoine Pitrouf6fbf562013-08-22 00:39:46 +020022from test.support import HOST, HOSTv6
Guido van Rossumd8faa362007-04-27 19:54:29 +000023
Giampaolo Rodola'0d4f08c2013-05-16 15:12:01 +020024TIMEOUT = 3
Benjamin Petersonbe17a112008-09-27 21:49:47 +000025# the dummy data returned by server over the data channel when
Giampaolo Rodola'd78def92011-05-06 19:49:08 +020026# RETR, LIST, NLST, MLSD commands are issued
Benjamin Petersonbe17a112008-09-27 21:49:47 +000027RETR_DATA = 'abcde12345\r\n' * 1000
28LIST_DATA = 'foo\r\nbar\r\n'
29NLST_DATA = 'foo\r\nbar\r\n'
Giampaolo Rodola'd78def92011-05-06 19:49:08 +020030MLSD_DATA = ("type=cdir;perm=el;unique==keVO1+ZF4; test\r\n"
31 "type=pdir;perm=e;unique==keVO1+d?3; ..\r\n"
32 "type=OS.unix=slink:/foobar;perm=;unique==keVO1+4G4; foobar\r\n"
33 "type=OS.unix=chr-13/29;perm=;unique==keVO1+5G4; device\r\n"
34 "type=OS.unix=blk-11/108;perm=;unique==keVO1+6G4; block\r\n"
35 "type=file;perm=awr;unique==keVO1+8G4; writable\r\n"
36 "type=dir;perm=cpmel;unique==keVO1+7G4; promiscuous\r\n"
37 "type=dir;perm=;unique==keVO1+1t2; no-exec\r\n"
38 "type=file;perm=r;unique==keVO1+EG4; two words\r\n"
39 "type=file;perm=r;unique==keVO1+IH4; leading space\r\n"
40 "type=file;perm=r;unique==keVO1+1G4; file1\r\n"
41 "type=dir;perm=cpmel;unique==keVO1+7G4; incoming\r\n"
42 "type=file;perm=r;unique==keVO1+1G4; file2\r\n"
43 "type=file;perm=r;unique==keVO1+1G4; file3\r\n"
44 "type=file;perm=r;unique==keVO1+1G4; file4\r\n")
Christian Heimes836baa52008-02-26 08:18:30 +000045
Christian Heimes836baa52008-02-26 08:18:30 +000046
Benjamin Petersonbe17a112008-09-27 21:49:47 +000047class DummyDTPHandler(asynchat.async_chat):
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +000048 dtp_conn_closed = False
Benjamin Petersonbe17a112008-09-27 21:49:47 +000049
50 def __init__(self, conn, baseclass):
51 asynchat.async_chat.__init__(self, conn)
52 self.baseclass = baseclass
53 self.baseclass.last_received_data = ''
54
55 def handle_read(self):
Giampaolo Rodolàf96482e2010-08-04 10:36:18 +000056 self.baseclass.last_received_data += self.recv(1024).decode('ascii')
Benjamin Petersonbe17a112008-09-27 21:49:47 +000057
58 def handle_close(self):
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +000059 # XXX: this method can be called many times in a row for a single
60 # connection, including in clear-text (non-TLS) mode.
61 # (behaviour witnessed with test_data_connection)
62 if not self.dtp_conn_closed:
63 self.baseclass.push('226 transfer complete')
64 self.close()
65 self.dtp_conn_closed = True
Benjamin Petersonbe17a112008-09-27 21:49:47 +000066
67 def push(self, what):
Giampaolo Rodola'd78def92011-05-06 19:49:08 +020068 if self.baseclass.next_data is not None:
69 what = self.baseclass.next_data
70 self.baseclass.next_data = None
71 if not what:
72 return self.close_when_done()
Giampaolo Rodolàf96482e2010-08-04 10:36:18 +000073 super(DummyDTPHandler, self).push(what.encode('ascii'))
Benjamin Petersonbe17a112008-09-27 21:49:47 +000074
Giampaolo Rodolàd930b632010-05-06 20:21:57 +000075 def handle_error(self):
Berker Peksag8f791d32014-11-01 10:45:57 +020076 raise Exception
Giampaolo Rodolàd930b632010-05-06 20:21:57 +000077
Benjamin Petersonbe17a112008-09-27 21:49:47 +000078
79class DummyFTPHandler(asynchat.async_chat):
80
Antoine Pitrouf988cd02009-11-17 20:21:14 +000081 dtp_handler = DummyDTPHandler
82
Benjamin Petersonbe17a112008-09-27 21:49:47 +000083 def __init__(self, conn):
84 asynchat.async_chat.__init__(self, conn)
Giampaolo Rodola'0b5c21f2011-05-07 19:03:47 +020085 # tells the socket to handle urgent data inline (ABOR command)
86 self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_OOBINLINE, 1)
Benjamin Petersonbe17a112008-09-27 21:49:47 +000087 self.set_terminator(b"\r\n")
88 self.in_buffer = []
89 self.dtp = None
90 self.last_received_cmd = None
91 self.last_received_data = ''
92 self.next_response = ''
Giampaolo Rodola'd78def92011-05-06 19:49:08 +020093 self.next_data = None
Antoine Pitrou648bcd72009-11-27 13:23:26 +000094 self.rest = None
Serhiy Storchakac30b1782013-10-20 16:58:27 +030095 self.next_retr_data = RETR_DATA
Benjamin Petersonbe17a112008-09-27 21:49:47 +000096 self.push('220 welcome')
97
98 def collect_incoming_data(self, data):
99 self.in_buffer.append(data)
100
101 def found_terminator(self):
102 line = b''.join(self.in_buffer).decode('ascii')
103 self.in_buffer = []
104 if self.next_response:
105 self.push(self.next_response)
106 self.next_response = ''
107 cmd = line.split(' ')[0].lower()
108 self.last_received_cmd = cmd
109 space = line.find(' ')
110 if space != -1:
111 arg = line[space + 1:]
112 else:
113 arg = ""
114 if hasattr(self, 'cmd_' + cmd):
115 method = getattr(self, 'cmd_' + cmd)
116 method(arg)
117 else:
118 self.push('550 command "%s" not understood.' %cmd)
119
120 def handle_error(self):
Berker Peksag8f791d32014-11-01 10:45:57 +0200121 raise Exception
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000122
123 def push(self, data):
124 asynchat.async_chat.push(self, data.encode('ascii') + b'\r\n')
125
126 def cmd_port(self, arg):
127 addr = list(map(int, arg.split(',')))
128 ip = '%d.%d.%d.%d' %tuple(addr[:4])
129 port = (addr[4] * 256) + addr[5]
Giampaolo Rodola'0d4f08c2013-05-16 15:12:01 +0200130 s = socket.create_connection((ip, port), timeout=TIMEOUT)
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000131 self.dtp = self.dtp_handler(s, baseclass=self)
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000132 self.push('200 active data connection established')
133
134 def cmd_pasv(self, arg):
Brett Cannon918e2d42010-10-29 23:26:25 +0000135 with socket.socket() as sock:
136 sock.bind((self.socket.getsockname()[0], 0))
Charles-François Natali6e204602014-07-23 19:28:13 +0100137 sock.listen()
Giampaolo Rodola'0d4f08c2013-05-16 15:12:01 +0200138 sock.settimeout(TIMEOUT)
Brett Cannon918e2d42010-10-29 23:26:25 +0000139 ip, port = sock.getsockname()[:2]
140 ip = ip.replace('.', ','); p1 = port / 256; p2 = port % 256
141 self.push('227 entering passive mode (%s,%d,%d)' %(ip, p1, p2))
142 conn, addr = sock.accept()
143 self.dtp = self.dtp_handler(conn, baseclass=self)
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000144
145 def cmd_eprt(self, arg):
146 af, ip, port = arg.split(arg[0])[1:-1]
147 port = int(port)
Giampaolo Rodola'0d4f08c2013-05-16 15:12:01 +0200148 s = socket.create_connection((ip, port), timeout=TIMEOUT)
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000149 self.dtp = self.dtp_handler(s, baseclass=self)
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000150 self.push('200 active data connection established')
151
152 def cmd_epsv(self, arg):
Brett Cannon918e2d42010-10-29 23:26:25 +0000153 with socket.socket(socket.AF_INET6) as sock:
154 sock.bind((self.socket.getsockname()[0], 0))
Charles-François Natali6e204602014-07-23 19:28:13 +0100155 sock.listen()
Giampaolo Rodola'0d4f08c2013-05-16 15:12:01 +0200156 sock.settimeout(TIMEOUT)
Brett Cannon918e2d42010-10-29 23:26:25 +0000157 port = sock.getsockname()[1]
158 self.push('229 entering extended passive mode (|||%d|)' %port)
159 conn, addr = sock.accept()
160 self.dtp = self.dtp_handler(conn, baseclass=self)
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000161
162 def cmd_echo(self, arg):
163 # sends back the received string (used by the test suite)
164 self.push(arg)
165
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000166 def cmd_noop(self, arg):
167 self.push('200 noop ok')
168
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000169 def cmd_user(self, arg):
170 self.push('331 username ok')
171
172 def cmd_pass(self, arg):
173 self.push('230 password ok')
174
175 def cmd_acct(self, arg):
176 self.push('230 acct ok')
177
178 def cmd_rnfr(self, arg):
179 self.push('350 rnfr ok')
180
181 def cmd_rnto(self, arg):
182 self.push('250 rnto ok')
183
184 def cmd_dele(self, arg):
185 self.push('250 dele ok')
186
187 def cmd_cwd(self, arg):
188 self.push('250 cwd ok')
189
190 def cmd_size(self, arg):
191 self.push('250 1000')
192
193 def cmd_mkd(self, arg):
194 self.push('257 "%s"' %arg)
195
196 def cmd_rmd(self, arg):
197 self.push('250 rmd ok')
198
199 def cmd_pwd(self, arg):
200 self.push('257 "pwd ok"')
201
202 def cmd_type(self, arg):
Giampaolo Rodolàf96482e2010-08-04 10:36:18 +0000203 self.push('200 type ok')
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000204
205 def cmd_quit(self, arg):
206 self.push('221 quit ok')
207 self.close()
208
Giampaolo Rodola'0b5c21f2011-05-07 19:03:47 +0200209 def cmd_abor(self, arg):
210 self.push('226 abor ok')
211
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000212 def cmd_stor(self, arg):
213 self.push('125 stor ok')
214
Antoine Pitrou648bcd72009-11-27 13:23:26 +0000215 def cmd_rest(self, arg):
216 self.rest = arg
217 self.push('350 rest ok')
218
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000219 def cmd_retr(self, arg):
220 self.push('125 retr ok')
Antoine Pitrou648bcd72009-11-27 13:23:26 +0000221 if self.rest is not None:
222 offset = int(self.rest)
223 else:
224 offset = 0
Serhiy Storchakac30b1782013-10-20 16:58:27 +0300225 self.dtp.push(self.next_retr_data[offset:])
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000226 self.dtp.close_when_done()
Antoine Pitrou648bcd72009-11-27 13:23:26 +0000227 self.rest = None
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000228
229 def cmd_list(self, arg):
230 self.push('125 list ok')
231 self.dtp.push(LIST_DATA)
232 self.dtp.close_when_done()
233
234 def cmd_nlst(self, arg):
235 self.push('125 nlst ok')
236 self.dtp.push(NLST_DATA)
237 self.dtp.close_when_done()
238
Giampaolo Rodola'd78def92011-05-06 19:49:08 +0200239 def cmd_opts(self, arg):
240 self.push('200 opts ok')
241
242 def cmd_mlsd(self, arg):
243 self.push('125 mlsd ok')
244 self.dtp.push(MLSD_DATA)
245 self.dtp.close_when_done()
246
Serhiy Storchakac30b1782013-10-20 16:58:27 +0300247 def cmd_setlongretr(self, arg):
248 # For testing. Next RETR will return long line.
249 self.next_retr_data = 'x' * int(arg)
250 self.push('125 setlongretr ok')
251
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000252
253class DummyFTPServer(asyncore.dispatcher, threading.Thread):
254
255 handler = DummyFTPHandler
256
257 def __init__(self, address, af=socket.AF_INET):
258 threading.Thread.__init__(self)
259 asyncore.dispatcher.__init__(self)
260 self.create_socket(af, socket.SOCK_STREAM)
261 self.bind(address)
262 self.listen(5)
263 self.active = False
264 self.active_lock = threading.Lock()
265 self.host, self.port = self.socket.getsockname()[:2]
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000266 self.handler_instance = None
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000267
268 def start(self):
269 assert not self.active
270 self.__flag = threading.Event()
271 threading.Thread.start(self)
272 self.__flag.wait()
273
274 def run(self):
275 self.active = True
276 self.__flag.set()
277 while self.active and asyncore.socket_map:
278 self.active_lock.acquire()
279 asyncore.loop(timeout=0.1, count=1)
280 self.active_lock.release()
281 asyncore.close_all(ignore_all=True)
282
283 def stop(self):
284 assert self.active
285 self.active = False
286 self.join()
287
Giampaolo Rodolà977c7072010-10-04 21:08:36 +0000288 def handle_accepted(self, conn, addr):
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000289 self.handler_instance = self.handler(conn)
Benjamin Petersond06e3b02008-09-28 21:00:42 +0000290
291 def handle_connect(self):
292 self.close()
293 handle_read = handle_connect
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000294
295 def writable(self):
296 return 0
297
298 def handle_error(self):
Berker Peksag8f791d32014-11-01 10:45:57 +0200299 raise Exception
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000300
301
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000302if ssl is not None:
303
Christian Heimese5b5edf2013-12-02 02:56:02 +0100304 CERTFILE = os.path.join(os.path.dirname(__file__), "keycert3.pem")
305 CAFILE = os.path.join(os.path.dirname(__file__), "pycacert.pem")
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000306
307 class SSLConnection(asyncore.dispatcher):
308 """An asyncore.dispatcher subclass supporting TLS/SSL."""
309
310 _ssl_accepting = False
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +0000311 _ssl_closing = False
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000312
313 def secure_connection(self):
Christian Heimesd0486372016-09-10 23:23:33 +0200314 context = ssl.SSLContext()
Miss Islington (bot)2614ed42018-02-27 00:17:49 -0800315 # TODO: fix TLSv1.3 support
316 context.options |= ssl.OP_NO_TLSv1_3
Christian Heimesd0486372016-09-10 23:23:33 +0200317 context.load_cert_chain(CERTFILE)
318 socket = context.wrap_socket(self.socket,
319 suppress_ragged_eofs=False,
320 server_side=True,
321 do_handshake_on_connect=False)
Giampaolo Rodola'096dcb12011-06-27 11:17:51 +0200322 self.del_channel()
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000323 self.set_socket(socket)
324 self._ssl_accepting = True
325
326 def _do_ssl_handshake(self):
327 try:
328 self.socket.do_handshake()
329 except ssl.SSLError as err:
330 if err.args[0] in (ssl.SSL_ERROR_WANT_READ,
331 ssl.SSL_ERROR_WANT_WRITE):
332 return
333 elif err.args[0] == ssl.SSL_ERROR_EOF:
334 return self.handle_close()
Christian Heimes61d478c2018-01-27 15:51:38 +0100335 # TODO: SSLError does not expose alert information
336 elif "SSLV3_ALERT_BAD_CERTIFICATE" in err.args[1]:
337 return self.handle_close()
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000338 raise
Andrew Svetlov0832af62012-12-18 23:10:48 +0200339 except OSError as err:
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000340 if err.args[0] == errno.ECONNABORTED:
341 return self.handle_close()
342 else:
343 self._ssl_accepting = False
344
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +0000345 def _do_ssl_shutdown(self):
346 self._ssl_closing = True
347 try:
348 self.socket = self.socket.unwrap()
349 except ssl.SSLError as err:
350 if err.args[0] in (ssl.SSL_ERROR_WANT_READ,
351 ssl.SSL_ERROR_WANT_WRITE):
352 return
Andrew Svetlov0832af62012-12-18 23:10:48 +0200353 except OSError as err:
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +0000354 # Any "socket error" corresponds to a SSL_ERROR_SYSCALL return
355 # from OpenSSL's SSL_shutdown(), corresponding to a
356 # closed socket condition. See also:
357 # http://www.mail-archive.com/openssl-users@openssl.org/msg60710.html
358 pass
359 self._ssl_closing = False
Benjamin Petersonb29614e2012-10-09 11:16:03 -0400360 if getattr(self, '_ccc', False) is False:
Giampaolo Rodola'096dcb12011-06-27 11:17:51 +0200361 super(SSLConnection, self).close()
362 else:
363 pass
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +0000364
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000365 def handle_read_event(self):
366 if self._ssl_accepting:
367 self._do_ssl_handshake()
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +0000368 elif self._ssl_closing:
369 self._do_ssl_shutdown()
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000370 else:
371 super(SSLConnection, self).handle_read_event()
372
373 def handle_write_event(self):
374 if self._ssl_accepting:
375 self._do_ssl_handshake()
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +0000376 elif self._ssl_closing:
377 self._do_ssl_shutdown()
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000378 else:
379 super(SSLConnection, self).handle_write_event()
380
381 def send(self, data):
382 try:
383 return super(SSLConnection, self).send(data)
384 except ssl.SSLError as err:
Antoine Pitrou5733c082010-03-22 14:49:10 +0000385 if err.args[0] in (ssl.SSL_ERROR_EOF, ssl.SSL_ERROR_ZERO_RETURN,
386 ssl.SSL_ERROR_WANT_READ,
387 ssl.SSL_ERROR_WANT_WRITE):
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000388 return 0
389 raise
390
391 def recv(self, buffer_size):
392 try:
393 return super(SSLConnection, self).recv(buffer_size)
394 except ssl.SSLError as err:
Antoine Pitrou5733c082010-03-22 14:49:10 +0000395 if err.args[0] in (ssl.SSL_ERROR_WANT_READ,
396 ssl.SSL_ERROR_WANT_WRITE):
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +0000397 return b''
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000398 if err.args[0] in (ssl.SSL_ERROR_EOF, ssl.SSL_ERROR_ZERO_RETURN):
399 self.handle_close()
400 return b''
401 raise
402
403 def handle_error(self):
Berker Peksag8f791d32014-11-01 10:45:57 +0200404 raise Exception
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000405
406 def close(self):
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +0000407 if (isinstance(self.socket, ssl.SSLSocket) and
408 self.socket._sslobj is not None):
409 self._do_ssl_shutdown()
Benjamin Peterson1bd93a72010-10-31 19:58:07 +0000410 else:
411 super(SSLConnection, self).close()
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000412
413
414 class DummyTLS_DTPHandler(SSLConnection, DummyDTPHandler):
415 """A DummyDTPHandler subclass supporting TLS/SSL."""
416
417 def __init__(self, conn, baseclass):
418 DummyDTPHandler.__init__(self, conn, baseclass)
419 if self.baseclass.secure_data_channel:
420 self.secure_connection()
421
422
423 class DummyTLS_FTPHandler(SSLConnection, DummyFTPHandler):
424 """A DummyFTPHandler subclass supporting TLS/SSL."""
425
426 dtp_handler = DummyTLS_DTPHandler
427
428 def __init__(self, conn):
429 DummyFTPHandler.__init__(self, conn)
430 self.secure_data_channel = False
Giampaolo Rodola'096dcb12011-06-27 11:17:51 +0200431 self._ccc = False
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000432
433 def cmd_auth(self, line):
434 """Set up secure control channel."""
435 self.push('234 AUTH TLS successful')
436 self.secure_connection()
437
Giampaolo Rodola'096dcb12011-06-27 11:17:51 +0200438 def cmd_ccc(self, line):
439 self.push('220 Reverting back to clear-text')
440 self._ccc = True
441 self._do_ssl_shutdown()
442
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000443 def cmd_pbsz(self, line):
444 """Negotiate size of buffer for secure data transfer.
445 For TLS/SSL the only valid value for the parameter is '0'.
446 Any other value is accepted but ignored.
447 """
448 self.push('200 PBSZ=0 successful.')
449
450 def cmd_prot(self, line):
451 """Setup un/secure data channel."""
452 arg = line.upper()
453 if arg == 'C':
454 self.push('200 Protection set to Clear')
455 self.secure_data_channel = False
456 elif arg == 'P':
457 self.push('200 Protection set to Private')
458 self.secure_data_channel = True
459 else:
460 self.push("502 Unrecognized PROT type (use C or P).")
461
462
463 class DummyTLS_FTPServer(DummyFTPServer):
464 handler = DummyTLS_FTPHandler
465
466
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000467class TestFTPClass(TestCase):
468
469 def setUp(self):
470 self.server = DummyFTPServer((HOST, 0))
471 self.server.start()
Giampaolo Rodola'0d4f08c2013-05-16 15:12:01 +0200472 self.client = ftplib.FTP(timeout=TIMEOUT)
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000473 self.client.connect(self.server.host, self.server.port)
474
475 def tearDown(self):
476 self.client.close()
477 self.server.stop()
Victor Stinnerd403a292017-09-13 03:58:25 -0700478 # Explicitly clear the attribute to prevent dangling thread
479 self.server = None
Victor Stinner73528642017-06-30 17:36:57 +0200480 asyncore.close_all(ignore_all=True)
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000481
Giampaolo Rodola'8bc85852012-01-09 17:10:10 +0100482 def check_data(self, received, expected):
483 self.assertEqual(len(received), len(expected))
484 self.assertEqual(received, expected)
485
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000486 def test_getwelcome(self):
487 self.assertEqual(self.client.getwelcome(), '220 welcome')
488
489 def test_sanitize(self):
490 self.assertEqual(self.client.sanitize('foo'), repr('foo'))
491 self.assertEqual(self.client.sanitize('pass 12345'), repr('pass *****'))
492 self.assertEqual(self.client.sanitize('PASS 12345'), repr('PASS *****'))
493
494 def test_exceptions(self):
Dong-hee Na2b1e6e92017-07-23 02:20:22 +0900495 self.assertRaises(ValueError, self.client.sendcmd, 'echo 40\r\n0')
496 self.assertRaises(ValueError, self.client.sendcmd, 'echo 40\n0')
497 self.assertRaises(ValueError, self.client.sendcmd, 'echo 40\r0')
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000498 self.assertRaises(ftplib.error_temp, self.client.sendcmd, 'echo 400')
499 self.assertRaises(ftplib.error_temp, self.client.sendcmd, 'echo 499')
500 self.assertRaises(ftplib.error_perm, self.client.sendcmd, 'echo 500')
501 self.assertRaises(ftplib.error_perm, self.client.sendcmd, 'echo 599')
502 self.assertRaises(ftplib.error_proto, self.client.sendcmd, 'echo 999')
503
504 def test_all_errors(self):
505 exceptions = (ftplib.error_reply, ftplib.error_temp, ftplib.error_perm,
Dong-hee Na2b1e6e92017-07-23 02:20:22 +0900506 ftplib.error_proto, ftplib.Error, OSError,
507 EOFError)
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000508 for x in exceptions:
509 try:
510 raise x('exception not included in all_errors set')
511 except ftplib.all_errors:
512 pass
513
514 def test_set_pasv(self):
515 # passive mode is supposed to be enabled by default
516 self.assertTrue(self.client.passiveserver)
517 self.client.set_pasv(True)
518 self.assertTrue(self.client.passiveserver)
519 self.client.set_pasv(False)
520 self.assertFalse(self.client.passiveserver)
521
522 def test_voidcmd(self):
523 self.client.voidcmd('echo 200')
524 self.client.voidcmd('echo 299')
525 self.assertRaises(ftplib.error_reply, self.client.voidcmd, 'echo 199')
526 self.assertRaises(ftplib.error_reply, self.client.voidcmd, 'echo 300')
527
528 def test_login(self):
529 self.client.login()
530
531 def test_acct(self):
532 self.client.acct('passwd')
533
534 def test_rename(self):
535 self.client.rename('a', 'b')
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000536 self.server.handler_instance.next_response = '200'
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000537 self.assertRaises(ftplib.error_reply, self.client.rename, 'a', 'b')
538
539 def test_delete(self):
540 self.client.delete('foo')
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000541 self.server.handler_instance.next_response = '199'
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000542 self.assertRaises(ftplib.error_reply, self.client.delete, 'foo')
543
544 def test_size(self):
545 self.client.size('foo')
546
547 def test_mkd(self):
548 dir = self.client.mkd('/foo')
549 self.assertEqual(dir, '/foo')
550
551 def test_rmd(self):
552 self.client.rmd('foo')
553
Senthil Kumaran0d538602013-08-12 22:25:27 -0700554 def test_cwd(self):
555 dir = self.client.cwd('/foo')
556 self.assertEqual(dir, '250 cwd ok')
557
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000558 def test_pwd(self):
559 dir = self.client.pwd()
560 self.assertEqual(dir, 'pwd ok')
561
562 def test_quit(self):
563 self.assertEqual(self.client.quit(), '221 quit ok')
564 # Ensure the connection gets closed; sock attribute should be None
565 self.assertEqual(self.client.sock, None)
566
Giampaolo Rodola'0b5c21f2011-05-07 19:03:47 +0200567 def test_abort(self):
568 self.client.abort()
569
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000570 def test_retrbinary(self):
571 def callback(data):
572 received.append(data.decode('ascii'))
573 received = []
574 self.client.retrbinary('retr', callback)
Giampaolo Rodola'8bc85852012-01-09 17:10:10 +0100575 self.check_data(''.join(received), RETR_DATA)
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000576
Antoine Pitrou648bcd72009-11-27 13:23:26 +0000577 def test_retrbinary_rest(self):
578 def callback(data):
579 received.append(data.decode('ascii'))
580 for rest in (0, 10, 20):
581 received = []
582 self.client.retrbinary('retr', callback, rest=rest)
Giampaolo Rodola'8bc85852012-01-09 17:10:10 +0100583 self.check_data(''.join(received), RETR_DATA[rest:])
Antoine Pitrou648bcd72009-11-27 13:23:26 +0000584
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000585 def test_retrlines(self):
586 received = []
587 self.client.retrlines('retr', received.append)
Giampaolo Rodola'8bc85852012-01-09 17:10:10 +0100588 self.check_data(''.join(received), RETR_DATA.replace('\r\n', ''))
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000589
590 def test_storbinary(self):
591 f = io.BytesIO(RETR_DATA.encode('ascii'))
592 self.client.storbinary('stor', f)
Giampaolo Rodola'8bc85852012-01-09 17:10:10 +0100593 self.check_data(self.server.handler_instance.last_received_data, RETR_DATA)
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000594 # test new callback arg
595 flag = []
596 f.seek(0)
597 self.client.storbinary('stor', f, callback=lambda x: flag.append(None))
598 self.assertTrue(flag)
599
Antoine Pitrou648bcd72009-11-27 13:23:26 +0000600 def test_storbinary_rest(self):
601 f = io.BytesIO(RETR_DATA.replace('\r\n', '\n').encode('ascii'))
602 for r in (30, '30'):
603 f.seek(0)
604 self.client.storbinary('stor', f, rest=r)
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000605 self.assertEqual(self.server.handler_instance.rest, str(r))
Antoine Pitrou648bcd72009-11-27 13:23:26 +0000606
Giampaolo Rodolàf96482e2010-08-04 10:36:18 +0000607 def test_storlines(self):
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000608 f = io.BytesIO(RETR_DATA.replace('\r\n', '\n').encode('ascii'))
609 self.client.storlines('stor', f)
Giampaolo Rodola'8bc85852012-01-09 17:10:10 +0100610 self.check_data(self.server.handler_instance.last_received_data, RETR_DATA)
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000611 # test new callback arg
612 flag = []
613 f.seek(0)
614 self.client.storlines('stor foo', f, callback=lambda x: flag.append(None))
615 self.assertTrue(flag)
616
Victor Stinnered3a3032013-04-02 22:13:27 +0200617 f = io.StringIO(RETR_DATA.replace('\r\n', '\n'))
618 # storlines() expects a binary file, not a text file
Florent Xicluna5f3fef32013-07-06 15:08:21 +0200619 with support.check_warnings(('', BytesWarning), quiet=True):
620 self.assertRaises(TypeError, self.client.storlines, 'stor foo', f)
Victor Stinnered3a3032013-04-02 22:13:27 +0200621
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000622 def test_nlst(self):
623 self.client.nlst()
624 self.assertEqual(self.client.nlst(), NLST_DATA.split('\r\n')[:-1])
625
626 def test_dir(self):
627 l = []
628 self.client.dir(lambda x: l.append(x))
629 self.assertEqual(''.join(l), LIST_DATA.replace('\r\n', ''))
630
Giampaolo Rodola'd78def92011-05-06 19:49:08 +0200631 def test_mlsd(self):
632 list(self.client.mlsd())
633 list(self.client.mlsd(path='/'))
634 list(self.client.mlsd(path='/', facts=['size', 'type']))
635
636 ls = list(self.client.mlsd())
637 for name, facts in ls:
Giampaolo Rodola'a55efb32011-05-07 16:06:59 +0200638 self.assertIsInstance(name, str)
639 self.assertIsInstance(facts, dict)
Giampaolo Rodola'd78def92011-05-06 19:49:08 +0200640 self.assertTrue(name)
Giampaolo Rodola'a55efb32011-05-07 16:06:59 +0200641 self.assertIn('type', facts)
642 self.assertIn('perm', facts)
643 self.assertIn('unique', facts)
Giampaolo Rodola'd78def92011-05-06 19:49:08 +0200644
645 def set_data(data):
646 self.server.handler_instance.next_data = data
647
648 def test_entry(line, type=None, perm=None, unique=None, name=None):
649 type = 'type' if type is None else type
650 perm = 'perm' if perm is None else perm
651 unique = 'unique' if unique is None else unique
652 name = 'name' if name is None else name
653 set_data(line)
654 _name, facts = next(self.client.mlsd())
655 self.assertEqual(_name, name)
656 self.assertEqual(facts['type'], type)
657 self.assertEqual(facts['perm'], perm)
658 self.assertEqual(facts['unique'], unique)
659
660 # plain
661 test_entry('type=type;perm=perm;unique=unique; name\r\n')
662 # "=" in fact value
663 test_entry('type=ty=pe;perm=perm;unique=unique; name\r\n', type="ty=pe")
664 test_entry('type==type;perm=perm;unique=unique; name\r\n', type="=type")
665 test_entry('type=t=y=pe;perm=perm;unique=unique; name\r\n', type="t=y=pe")
666 test_entry('type=====;perm=perm;unique=unique; name\r\n', type="====")
667 # spaces in name
668 test_entry('type=type;perm=perm;unique=unique; na me\r\n', name="na me")
669 test_entry('type=type;perm=perm;unique=unique; name \r\n', name="name ")
670 test_entry('type=type;perm=perm;unique=unique; name\r\n', name=" name")
671 test_entry('type=type;perm=perm;unique=unique; n am e\r\n', name="n am e")
672 # ";" in name
673 test_entry('type=type;perm=perm;unique=unique; na;me\r\n', name="na;me")
674 test_entry('type=type;perm=perm;unique=unique; ;name\r\n', name=";name")
675 test_entry('type=type;perm=perm;unique=unique; ;name;\r\n', name=";name;")
676 test_entry('type=type;perm=perm;unique=unique; ;;;;\r\n', name=";;;;")
677 # case sensitiveness
678 set_data('Type=type;TyPe=perm;UNIQUE=unique; name\r\n')
679 _name, facts = next(self.client.mlsd())
Giampaolo Rodola'a55efb32011-05-07 16:06:59 +0200680 for x in facts:
681 self.assertTrue(x.islower())
Giampaolo Rodola'd78def92011-05-06 19:49:08 +0200682 # no data (directory empty)
683 set_data('')
684 self.assertRaises(StopIteration, next, self.client.mlsd())
685 set_data('')
686 for x in self.client.mlsd():
Berker Peksag8f791d32014-11-01 10:45:57 +0200687 self.fail("unexpected data %s" % x)
Giampaolo Rodola'd78def92011-05-06 19:49:08 +0200688
Benjamin Peterson3a53fbb2008-09-27 22:04:16 +0000689 def test_makeport(self):
Brett Cannon918e2d42010-10-29 23:26:25 +0000690 with self.client.makeport():
691 # IPv4 is in use, just make sure send_eprt has not been used
692 self.assertEqual(self.server.handler_instance.last_received_cmd,
693 'port')
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000694
695 def test_makepasv(self):
696 host, port = self.client.makepasv()
Giampaolo Rodola'0d4f08c2013-05-16 15:12:01 +0200697 conn = socket.create_connection((host, port), timeout=TIMEOUT)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000698 conn.close()
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000699 # IPv4 is in use, just make sure send_epsv has not been used
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000700 self.assertEqual(self.server.handler_instance.last_received_cmd, 'pasv')
701
702 def test_with_statement(self):
703 self.client.quit()
704
705 def is_client_connected():
706 if self.client.sock is None:
707 return False
708 try:
709 self.client.sendcmd('noop')
Andrew Svetlov0832af62012-12-18 23:10:48 +0200710 except (OSError, EOFError):
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000711 return False
712 return True
713
714 # base test
Giampaolo Rodola'0d4f08c2013-05-16 15:12:01 +0200715 with ftplib.FTP(timeout=TIMEOUT) as self.client:
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000716 self.client.connect(self.server.host, self.server.port)
717 self.client.sendcmd('noop')
718 self.assertTrue(is_client_connected())
719 self.assertEqual(self.server.handler_instance.last_received_cmd, 'quit')
720 self.assertFalse(is_client_connected())
721
722 # QUIT sent inside the with block
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.client.quit()
727 self.assertEqual(self.server.handler_instance.last_received_cmd, 'quit')
728 self.assertFalse(is_client_connected())
729
730 # force a wrong response code to be sent on QUIT: error_perm
731 # is expected and the connection is supposed to be closed
732 try:
Giampaolo Rodola'0d4f08c2013-05-16 15:12:01 +0200733 with ftplib.FTP(timeout=TIMEOUT) as self.client:
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000734 self.client.connect(self.server.host, self.server.port)
735 self.client.sendcmd('noop')
736 self.server.handler_instance.next_response = '550 error on quit'
737 except ftplib.error_perm as err:
738 self.assertEqual(str(err), '550 error on quit')
739 else:
740 self.fail('Exception not raised')
741 # needed to give the threaded server some time to set the attribute
742 # which otherwise would still be == 'noop'
743 time.sleep(0.1)
744 self.assertEqual(self.server.handler_instance.last_received_cmd, 'quit')
745 self.assertFalse(is_client_connected())
Guido van Rossumd8faa362007-04-27 19:54:29 +0000746
Giampaolo Rodolà396ff062011-02-28 19:19:51 +0000747 def test_source_address(self):
748 self.client.quit()
749 port = support.find_unused_port()
Antoine Pitrou6dca5272011-04-03 18:29:45 +0200750 try:
751 self.client.connect(self.server.host, self.server.port,
752 source_address=(HOST, port))
753 self.assertEqual(self.client.sock.getsockname()[1], port)
754 self.client.quit()
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200755 except OSError as e:
Antoine Pitrou6dca5272011-04-03 18:29:45 +0200756 if e.errno == errno.EADDRINUSE:
757 self.skipTest("couldn't bind to port %d" % port)
758 raise
Giampaolo Rodolà396ff062011-02-28 19:19:51 +0000759
760 def test_source_address_passive_connection(self):
761 port = support.find_unused_port()
762 self.client.source_address = (HOST, port)
Antoine Pitrou6dca5272011-04-03 18:29:45 +0200763 try:
764 with self.client.transfercmd('list') as sock:
765 self.assertEqual(sock.getsockname()[1], port)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200766 except OSError as e:
Antoine Pitrou6dca5272011-04-03 18:29:45 +0200767 if e.errno == errno.EADDRINUSE:
768 self.skipTest("couldn't bind to port %d" % port)
769 raise
Giampaolo Rodolà396ff062011-02-28 19:19:51 +0000770
Giampaolo Rodolàbbc47822010-08-23 22:10:32 +0000771 def test_parse257(self):
772 self.assertEqual(ftplib.parse257('257 "/foo/bar"'), '/foo/bar')
773 self.assertEqual(ftplib.parse257('257 "/foo/bar" created'), '/foo/bar')
774 self.assertEqual(ftplib.parse257('257 ""'), '')
775 self.assertEqual(ftplib.parse257('257 "" created'), '')
776 self.assertRaises(ftplib.error_reply, ftplib.parse257, '250 "/foo/bar"')
777 # The 257 response is supposed to include the directory
778 # name and in case it contains embedded double-quotes
779 # they must be doubled (see RFC-959, chapter 7, appendix 2).
780 self.assertEqual(ftplib.parse257('257 "/foo/b""ar"'), '/foo/b"ar')
781 self.assertEqual(ftplib.parse257('257 "/foo/b""ar" created'), '/foo/b"ar')
782
Serhiy Storchakac30b1782013-10-20 16:58:27 +0300783 def test_line_too_long(self):
784 self.assertRaises(ftplib.Error, self.client.sendcmd,
785 'x' * self.client.maxline * 2)
786
787 def test_retrlines_too_long(self):
788 self.client.sendcmd('SETLONGRETR %d' % (self.client.maxline * 2))
789 received = []
790 self.assertRaises(ftplib.Error,
791 self.client.retrlines, 'retr', received.append)
792
793 def test_storlines_too_long(self):
794 f = io.BytesIO(b'x' * self.client.maxline * 2)
795 self.assertRaises(ftplib.Error, self.client.storlines, 'stor', f)
796
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000797
Serhiy Storchaka43767632013-11-03 21:31:38 +0200798@skipUnless(support.IPV6_ENABLED, "IPv6 not enabled")
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000799class TestIPv6Environment(TestCase):
800
801 def setUp(self):
Antoine Pitrouf6fbf562013-08-22 00:39:46 +0200802 self.server = DummyFTPServer((HOSTv6, 0), af=socket.AF_INET6)
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000803 self.server.start()
Giampaolo Rodola'0d4f08c2013-05-16 15:12:01 +0200804 self.client = ftplib.FTP(timeout=TIMEOUT)
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000805 self.client.connect(self.server.host, self.server.port)
806
807 def tearDown(self):
808 self.client.close()
809 self.server.stop()
Victor Stinnerd403a292017-09-13 03:58:25 -0700810 # Explicitly clear the attribute to prevent dangling thread
811 self.server = None
Victor Stinner73528642017-06-30 17:36:57 +0200812 asyncore.close_all(ignore_all=True)
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000813
814 def test_af(self):
815 self.assertEqual(self.client.af, socket.AF_INET6)
816
817 def test_makeport(self):
Brett Cannon918e2d42010-10-29 23:26:25 +0000818 with self.client.makeport():
819 self.assertEqual(self.server.handler_instance.last_received_cmd,
820 'eprt')
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000821
822 def test_makepasv(self):
823 host, port = self.client.makepasv()
Giampaolo Rodola'0d4f08c2013-05-16 15:12:01 +0200824 conn = socket.create_connection((host, port), timeout=TIMEOUT)
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000825 conn.close()
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000826 self.assertEqual(self.server.handler_instance.last_received_cmd, 'epsv')
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000827
828 def test_transfer(self):
829 def retr():
830 def callback(data):
831 received.append(data.decode('ascii'))
832 received = []
833 self.client.retrbinary('retr', callback)
Giampaolo Rodola'8bc85852012-01-09 17:10:10 +0100834 self.assertEqual(len(''.join(received)), len(RETR_DATA))
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000835 self.assertEqual(''.join(received), RETR_DATA)
836 self.client.set_pasv(True)
837 retr()
838 self.client.set_pasv(False)
839 retr()
840
841
Serhiy Storchaka43767632013-11-03 21:31:38 +0200842@skipUnless(ssl, "SSL not available")
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000843class TestTLS_FTPClassMixin(TestFTPClass):
844 """Repeat TestFTPClass tests starting the TLS layer for both control
845 and data connections first.
846 """
847
848 def setUp(self):
849 self.server = DummyTLS_FTPServer((HOST, 0))
850 self.server.start()
Giampaolo Rodola'0d4f08c2013-05-16 15:12:01 +0200851 self.client = ftplib.FTP_TLS(timeout=TIMEOUT)
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000852 self.client.connect(self.server.host, self.server.port)
853 # enable TLS
854 self.client.auth()
855 self.client.prot_p()
856
857
Serhiy Storchaka43767632013-11-03 21:31:38 +0200858@skipUnless(ssl, "SSL not available")
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000859class TestTLS_FTPClass(TestCase):
860 """Specific TLS_FTP class tests."""
861
862 def setUp(self):
863 self.server = DummyTLS_FTPServer((HOST, 0))
864 self.server.start()
Giampaolo Rodola'0d4f08c2013-05-16 15:12:01 +0200865 self.client = ftplib.FTP_TLS(timeout=TIMEOUT)
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000866 self.client.connect(self.server.host, self.server.port)
867
868 def tearDown(self):
869 self.client.close()
870 self.server.stop()
Victor Stinnerd403a292017-09-13 03:58:25 -0700871 # Explicitly clear the attribute to prevent dangling thread
872 self.server = None
Victor Stinner73528642017-06-30 17:36:57 +0200873 asyncore.close_all(ignore_all=True)
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000874
875 def test_control_connection(self):
Ezio Melottie9615932010-01-24 19:26:24 +0000876 self.assertNotIsInstance(self.client.sock, ssl.SSLSocket)
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000877 self.client.auth()
Ezio Melottie9615932010-01-24 19:26:24 +0000878 self.assertIsInstance(self.client.sock, ssl.SSLSocket)
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000879
880 def test_data_connection(self):
881 # clear text
Brett Cannon918e2d42010-10-29 23:26:25 +0000882 with self.client.transfercmd('list') as sock:
883 self.assertNotIsInstance(sock, ssl.SSLSocket)
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +0000884 self.assertEqual(self.client.voidresp(), "226 transfer complete")
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000885
886 # secured, after PROT P
887 self.client.prot_p()
Brett Cannon918e2d42010-10-29 23:26:25 +0000888 with self.client.transfercmd('list') as sock:
889 self.assertIsInstance(sock, ssl.SSLSocket)
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +0000890 self.assertEqual(self.client.voidresp(), "226 transfer complete")
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000891
892 # PROT C is issued, the connection must be in cleartext again
893 self.client.prot_c()
Brett Cannon918e2d42010-10-29 23:26:25 +0000894 with self.client.transfercmd('list') as sock:
895 self.assertNotIsInstance(sock, ssl.SSLSocket)
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +0000896 self.assertEqual(self.client.voidresp(), "226 transfer complete")
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000897
898 def test_login(self):
899 # login() is supposed to implicitly secure the control connection
Ezio Melottie9615932010-01-24 19:26:24 +0000900 self.assertNotIsInstance(self.client.sock, ssl.SSLSocket)
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000901 self.client.login()
Ezio Melottie9615932010-01-24 19:26:24 +0000902 self.assertIsInstance(self.client.sock, ssl.SSLSocket)
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000903 # make sure that AUTH TLS doesn't get issued again
904 self.client.login()
905
906 def test_auth_issued_twice(self):
907 self.client.auth()
908 self.assertRaises(ValueError, self.client.auth)
909
Giampaolo Rodolàa67299e2010-05-26 18:06:04 +0000910 def test_context(self):
911 self.client.quit()
Christian Heimesa170fa12017-09-15 20:27:30 +0200912 ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
Miss Islington (bot)2614ed42018-02-27 00:17:49 -0800913 # TODO: fix TLSv1.3 support
914 ctx.options |= ssl.OP_NO_TLSv1_3
Christian Heimesa170fa12017-09-15 20:27:30 +0200915 ctx.check_hostname = False
916 ctx.verify_mode = ssl.CERT_NONE
Giampaolo Rodolàa67299e2010-05-26 18:06:04 +0000917 self.assertRaises(ValueError, ftplib.FTP_TLS, keyfile=CERTFILE,
918 context=ctx)
919 self.assertRaises(ValueError, ftplib.FTP_TLS, certfile=CERTFILE,
920 context=ctx)
921 self.assertRaises(ValueError, ftplib.FTP_TLS, certfile=CERTFILE,
922 keyfile=CERTFILE, context=ctx)
923
Giampaolo Rodola'0d4f08c2013-05-16 15:12:01 +0200924 self.client = ftplib.FTP_TLS(context=ctx, timeout=TIMEOUT)
Giampaolo Rodolàa67299e2010-05-26 18:06:04 +0000925 self.client.connect(self.server.host, self.server.port)
926 self.assertNotIsInstance(self.client.sock, ssl.SSLSocket)
927 self.client.auth()
928 self.assertIs(self.client.sock.context, ctx)
929 self.assertIsInstance(self.client.sock, ssl.SSLSocket)
930
931 self.client.prot_p()
Brett Cannon918e2d42010-10-29 23:26:25 +0000932 with self.client.transfercmd('list') as sock:
933 self.assertIs(sock.context, ctx)
934 self.assertIsInstance(sock, ssl.SSLSocket)
Giampaolo Rodolàa67299e2010-05-26 18:06:04 +0000935
Giampaolo Rodola'096dcb12011-06-27 11:17:51 +0200936 def test_ccc(self):
937 self.assertRaises(ValueError, self.client.ccc)
938 self.client.login(secure=True)
939 self.assertIsInstance(self.client.sock, ssl.SSLSocket)
940 self.client.ccc()
941 self.assertRaises(ValueError, self.client.sock.unwrap)
Giampaolo Rodola'096dcb12011-06-27 11:17:51 +0200942
Victor Stinner51500f32018-01-29 13:21:34 +0100943 @skipUnless(False, "FIXME: bpo-32706")
Christian Heimese5b5edf2013-12-02 02:56:02 +0100944 def test_check_hostname(self):
945 self.client.quit()
Christian Heimesa170fa12017-09-15 20:27:30 +0200946 ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
Miss Islington (bot)2614ed42018-02-27 00:17:49 -0800947 # TODO: fix TLSv1.3 support
948 ctx.options |= ssl.OP_NO_TLSv1_3
Christian Heimesa170fa12017-09-15 20:27:30 +0200949 self.assertEqual(ctx.verify_mode, ssl.CERT_REQUIRED)
950 self.assertEqual(ctx.check_hostname, True)
Christian Heimese5b5edf2013-12-02 02:56:02 +0100951 ctx.load_verify_locations(CAFILE)
952 self.client = ftplib.FTP_TLS(context=ctx, timeout=TIMEOUT)
953
954 # 127.0.0.1 doesn't match SAN
955 self.client.connect(self.server.host, self.server.port)
956 with self.assertRaises(ssl.CertificateError):
957 self.client.auth()
958 # exception quits connection
959
960 self.client.connect(self.server.host, self.server.port)
961 self.client.prot_p()
962 with self.assertRaises(ssl.CertificateError):
963 with self.client.transfercmd("list") as sock:
964 pass
965 self.client.quit()
966
967 self.client.connect("localhost", self.server.port)
968 self.client.auth()
969 self.client.quit()
970
971 self.client.connect("localhost", self.server.port)
972 self.client.prot_p()
973 with self.client.transfercmd("list") as sock:
974 pass
975
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000976
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000977class TestTimeouts(TestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000978
979 def setUp(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000980 self.evt = threading.Event()
Christian Heimes5e696852008-04-09 08:37:03 +0000981 self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Antoine Pitrou08d02722012-12-19 20:44:02 +0100982 self.sock.settimeout(20)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000983 self.port = support.bind_port(self.sock)
Antoine Pitrou08d02722012-12-19 20:44:02 +0100984 self.server_thread = threading.Thread(target=self.server)
985 self.server_thread.start()
Christian Heimes836baa52008-02-26 08:18:30 +0000986 # Wait for the server to be ready.
987 self.evt.wait()
988 self.evt.clear()
Antoine Pitrou08d02722012-12-19 20:44:02 +0100989 self.old_port = ftplib.FTP.port
Christian Heimes5e696852008-04-09 08:37:03 +0000990 ftplib.FTP.port = self.port
Guido van Rossumd8faa362007-04-27 19:54:29 +0000991
992 def tearDown(self):
Antoine Pitrou08d02722012-12-19 20:44:02 +0100993 ftplib.FTP.port = self.old_port
994 self.server_thread.join()
Victor Stinnerb157ce12017-09-13 06:43:58 -0700995 # Explicitly clear the attribute to prevent dangling thread
996 self.server_thread = None
Guido van Rossumd8faa362007-04-27 19:54:29 +0000997
Antoine Pitrou08d02722012-12-19 20:44:02 +0100998 def server(self):
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000999 # This method sets the evt 3 times:
1000 # 1) when the connection is ready to be accepted.
1001 # 2) when it is safe for the caller to close the connection
1002 # 3) when we have closed the socket
Charles-François Natali6e204602014-07-23 19:28:13 +01001003 self.sock.listen()
Benjamin Petersonbe17a112008-09-27 21:49:47 +00001004 # (1) Signal the caller that we are ready to accept the connection.
Antoine Pitrou08d02722012-12-19 20:44:02 +01001005 self.evt.set()
Benjamin Petersonbe17a112008-09-27 21:49:47 +00001006 try:
Antoine Pitrou08d02722012-12-19 20:44:02 +01001007 conn, addr = self.sock.accept()
Benjamin Petersonbe17a112008-09-27 21:49:47 +00001008 except socket.timeout:
1009 pass
1010 else:
Antoine Pitrou08d02722012-12-19 20:44:02 +01001011 conn.sendall(b"1 Hola mundo\n")
1012 conn.shutdown(socket.SHUT_WR)
Benjamin Petersonbe17a112008-09-27 21:49:47 +00001013 # (2) Signal the caller that it is safe to close the socket.
Antoine Pitrou08d02722012-12-19 20:44:02 +01001014 self.evt.set()
Benjamin Petersonbe17a112008-09-27 21:49:47 +00001015 conn.close()
1016 finally:
Antoine Pitrou08d02722012-12-19 20:44:02 +01001017 self.sock.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001018
1019 def testTimeoutDefault(self):
Georg Brandlf78e02b2008-06-10 17:40:04 +00001020 # default -- use global socket timeout
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +02001021 self.assertIsNone(socket.getdefaulttimeout())
Georg Brandlf78e02b2008-06-10 17:40:04 +00001022 socket.setdefaulttimeout(30)
1023 try:
Antoine Pitrouf6fbf562013-08-22 00:39:46 +02001024 ftp = ftplib.FTP(HOST)
Georg Brandlf78e02b2008-06-10 17:40:04 +00001025 finally:
1026 socket.setdefaulttimeout(None)
1027 self.assertEqual(ftp.sock.gettimeout(), 30)
1028 self.evt.wait()
1029 ftp.close()
1030
1031 def testTimeoutNone(self):
1032 # no timeout -- do not use global socket timeout
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +02001033 self.assertIsNone(socket.getdefaulttimeout())
Georg Brandlf78e02b2008-06-10 17:40:04 +00001034 socket.setdefaulttimeout(30)
1035 try:
Antoine Pitrouf6fbf562013-08-22 00:39:46 +02001036 ftp = ftplib.FTP(HOST, timeout=None)
Georg Brandlf78e02b2008-06-10 17:40:04 +00001037 finally:
1038 socket.setdefaulttimeout(None)
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +02001039 self.assertIsNone(ftp.sock.gettimeout())
Christian Heimes836baa52008-02-26 08:18:30 +00001040 self.evt.wait()
Georg Brandlf78e02b2008-06-10 17:40:04 +00001041 ftp.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001042
1043 def testTimeoutValue(self):
1044 # a value
Christian Heimes5e696852008-04-09 08:37:03 +00001045 ftp = ftplib.FTP(HOST, timeout=30)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001046 self.assertEqual(ftp.sock.gettimeout(), 30)
Christian Heimes836baa52008-02-26 08:18:30 +00001047 self.evt.wait()
Georg Brandlf78e02b2008-06-10 17:40:04 +00001048 ftp.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001049
1050 def testTimeoutConnect(self):
1051 ftp = ftplib.FTP()
Christian Heimes5e696852008-04-09 08:37:03 +00001052 ftp.connect(HOST, timeout=30)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001053 self.assertEqual(ftp.sock.gettimeout(), 30)
Christian Heimes836baa52008-02-26 08:18:30 +00001054 self.evt.wait()
Georg Brandlf78e02b2008-06-10 17:40:04 +00001055 ftp.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001056
1057 def testTimeoutDifferentOrder(self):
1058 ftp = ftplib.FTP(timeout=30)
Christian Heimes5e696852008-04-09 08:37:03 +00001059 ftp.connect(HOST)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001060 self.assertEqual(ftp.sock.gettimeout(), 30)
Christian Heimes836baa52008-02-26 08:18:30 +00001061 self.evt.wait()
Georg Brandlf78e02b2008-06-10 17:40:04 +00001062 ftp.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001063
1064 def testTimeoutDirectAccess(self):
1065 ftp = ftplib.FTP()
1066 ftp.timeout = 30
Christian Heimes5e696852008-04-09 08:37:03 +00001067 ftp.connect(HOST)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001068 self.assertEqual(ftp.sock.gettimeout(), 30)
Christian Heimes836baa52008-02-26 08:18:30 +00001069 self.evt.wait()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001070 ftp.close()
1071
1072
Martin Panter19e69c52015-11-14 12:46:42 +00001073class MiscTestCase(TestCase):
1074 def test__all__(self):
1075 blacklist = {'MSG_OOB', 'FTP_PORT', 'MAXLINE', 'CRLF', 'B_CRLF',
1076 'Error', 'parse150', 'parse227', 'parse229', 'parse257',
1077 'print_line', 'ftpcp', 'test'}
1078 support.check__all__(self, ftplib, blacklist=blacklist)
1079
1080
Benjamin Petersonbe17a112008-09-27 21:49:47 +00001081def test_main():
Berker Peksag8f791d32014-11-01 10:45:57 +02001082 tests = [TestFTPClass, TestTimeouts,
Serhiy Storchaka43767632013-11-03 21:31:38 +02001083 TestIPv6Environment,
Martin Panter19e69c52015-11-14 12:46:42 +00001084 TestTLS_FTPClassMixin, TestTLS_FTPClass,
1085 MiscTestCase]
Antoine Pitrouf988cd02009-11-17 20:21:14 +00001086
Benjamin Petersonbe17a112008-09-27 21:49:47 +00001087 thread_info = support.threading_setup()
1088 try:
1089 support.run_unittest(*tests)
1090 finally:
1091 support.threading_cleanup(*thread_info)
1092
Guido van Rossumd8faa362007-04-27 19:54:29 +00001093
1094if __name__ == '__main__':
1095 test_main()