-
Notifications
You must be signed in to change notification settings - Fork 3
/
ftpserver.py
executable file
·3362 lines (2928 loc) · 128 KB
/
ftpserver.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# $Id: ftpserver.py 629 2009-09-13 20:20:15Z billiejoex $
#
# pyftpdlib is released under the MIT license, reproduced below:
# ======================================================================
# Copyright (C) 2007-2009 Giampaolo Rodola' <[email protected]>
#
# All Rights Reserved
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following
# conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
#
# ======================================================================
"""pyftpdlib: RFC-959 asynchronous FTP server.
pyftpdlib implements a fully functioning asynchronous FTP server as
defined in RFC-959. A hierarchy of classes outlined below implement
the backend functionality for the FTPd:
[FTPServer] - the base class for the backend.
[FTPHandler] - a class representing the server-protocol-interpreter
(server-PI, see RFC-959). Each time a new connection occurs
FTPServer will create a new FTPHandler instance to handle the
current PI session.
[ActiveDTP], [PassiveDTP] - base classes for active/passive-DTP
backends.
[DTPHandler] - this class handles processing of data transfer
operations (server-DTP, see RFC-959).
[ThrottledDTPHandler] - a DTPHandler subclass implementing transfer
rates limits.
[DummyAuthorizer] - an "authorizer" is a class handling FTPd
authentications and permissions. It is used inside FTPHandler class
to verify user passwords, to get user's home directory and to get
permissions when a filesystem read/write occurs. "DummyAuthorizer"
is the base authorizer class providing a platform independent
interface for managing virtual users.
[AbstractedFS] - class used to interact with the file system,
providing a high level, cross-platform interface compatible
with both Windows and UNIX style filesystems.
[CallLater] - calls a function at a later time whithin the polling
loop asynchronously.
[AuthorizerError] - base class for authorizers exceptions.
pyftpdlib also provides 3 different logging streams through 3 functions
which can be overridden to allow for custom logging.
[log] - the main logger that logs the most important messages for
the end user regarding the FTPd.
[logline] - this function is used to log commands and responses
passing through the control FTP channel.
[logerror] - log traceback outputs occurring in case of errors.
Usage example:
>>> from pyftpdlib import ftpserver
>>> authorizer = ftpserver.DummyAuthorizer()
>>> authorizer.add_user('user', 'password', '/home/user', perm='elradfmw')
>>> authorizer.add_anonymous('/home/nobody')
>>> ftp_handler = ftpserver.FTPHandler
>>> ftp_handler.authorizer = authorizer
>>> address = ("127.0.0.1", 21)
>>> ftpd = ftpserver.FTPServer(address, ftp_handler)
>>> ftpd.serve_forever()
Serving FTP on 127.0.0.1:21
[]127.0.0.1:2503 connected.
127.0.0.1:2503 ==> 220 Ready.
127.0.0.1:2503 <== USER anonymous
127.0.0.1:2503 ==> 331 Username ok, send password.
127.0.0.1:2503 <== PASS ******
127.0.0.1:2503 ==> 230 Login successful.
[anonymous]@127.0.0.1:2503 User anonymous logged in.
127.0.0.1:2503 <== TYPE A
127.0.0.1:2503 ==> 200 Type set to: ASCII.
127.0.0.1:2503 <== PASV
127.0.0.1:2503 ==> 227 Entering passive mode (127,0,0,1,9,201).
127.0.0.1:2503 <== LIST
127.0.0.1:2503 ==> 150 File status okay. About to open data connection.
[anonymous]@127.0.0.1:2503 OK LIST "/". Transfer starting.
127.0.0.1:2503 ==> 226 Transfer complete.
[anonymous]@127.0.0.1:2503 Transfer complete. 706 bytes transmitted.
127.0.0.1:2503 <== QUIT
127.0.0.1:2503 ==> 221 Goodbye.
[anonymous]@127.0.0.1:2503 Disconnected.
"""
import asyncore
import asynchat
import socket
import os
import sys
import traceback
import errno
import time
import glob
import tempfile
import warnings
import random
import stat
import heapq
from tarfile import filemode as _filemode
try:
import pwd
import grp
except ImportError:
pwd = grp = None
__all__ = ['proto_cmds', 'Error', 'log', 'logline', 'logerror', 'DummyAuthorizer',
'AuthorizerError', 'FTPHandler', 'FTPServer', 'PassiveDTP',
'ActiveDTP', 'DTPHandler', 'ThrottledDTPHandler', 'FileProducer',
'BufferedIteratorProducer', 'AbstractedFS', 'CallLater']
__pname__ = 'Python FTP server library (pyftpdlib)'
__ver__ = '0.5.2'
__date__ = '2009-09-14'
__author__ = "Giampaolo Rodola' <[email protected]>"
__web__ = 'http://code.google.com/p/pyftpdlib/'
proto_cmds = {
# cmd : (perm, auth, arg, path, help)
'ABOR': (None, True, False, False, 'Syntax: ABOR (abort transfer).'),
'ALLO': (None, True, True, False, 'Syntax: ALLO <SP> bytes (noop; allocate storage).'),
'APPE': ('a', True, True, True, 'Syntax: APPE <SP> file-name (append data to an existent file).'),
'CDUP': ('e', True, False, True, 'Syntax: CDUP (go to parent directory).'),
'CWD' : ('e', True, None, True, 'Syntax: CWD [<SP> dir-name] (change current working directory).'),
'DELE': ('d', True, True, True, 'Syntax: DELE <SP> file-name (delete file).'),
'EPRT': (None, True, True, False, 'Syntax: EPRT <SP> |proto|ip|port| (set server in extended active mode).'),
'EPSV': (None, True, None, False, 'Syntax: EPSV [<SP> proto/"ALL"] (set server in extended passive mode).'),
'FEAT': (None, False, False, False, 'Syntax: FEAT (list all new features supported).'),
'HELP': (None, False, None, False, 'Syntax: HELP [<SP> cmd] (show help).'),
'LIST': ('l', True, None, True, 'Syntax: LIST [<SP> path-name] (list files).'),
'MDTM': (None, True, True, True, 'Syntax: MDTM [<SP> file-name] (get last modification time).'),
'MLSD': ('l', True, None, True, 'Syntax: MLSD [<SP> dir-name] (list files in a machine-processable form)'),
'MLST': ('l', True, None, True, 'Syntax: MLST [<SP> path-name] (show a path in a machine-processable form)'),
'MODE': (None, True, True, False, 'Syntax: MODE <SP> mode (noop; set data transfer mode).'),
'MKD' : ('m', True, True, True, 'Syntax: MDK <SP> dir-name (create directory).'),
'NLST': ('l', True, None, True, 'Syntax: NLST [<SP> path-name] (list files in a compact form).'),
'NOOP': (None, False, False, False, 'Syntax: NOOP (just do nothing).'),
'OPTS': (None, True, True, False, 'Syntax: OPTS <SP> ftp-command [<SP> option] (specify options for FTP commands)'),
'PASS': (None, False, True, False, 'Syntax: PASS <SP> user-name (set user password).'),
'PASV': (None, True, False, False, 'Syntax: PASV (set server in passive mode).'),
'PORT': (None, True, True, False, 'Syntax: PORT <sp> h1,h2,h3,h4,p1,p2 (set server in active mode).'),
'PWD' : (None, True, False, False, 'Syntax: PWD (get current working directory).'),
'QUIT': (None, False, False, False, 'Syntax: QUIT (quit current session).'),
'REIN': (None, True, False, False, 'Syntax: REIN (reinitialize / flush account).'),
'REST': (None, True, True, False, 'Syntax: REST <SP> marker (restart file position).'),
'RETR': ('r', True, True, True, 'Syntax: RETR <SP> file-name (retrieve a file).'),
'RMD' : ('d', True, True, True, 'Syntax: RMD <SP> dir-name (remove directory).'),
'RNFR': ('f', True, True, True, 'Syntax: RNFR <SP> file-name (file renaming (source name)).'),
'RNTO': (None, True, True, True, 'Syntax: RNTO <SP> file-name (file renaming (destination name)).'),
'SITE': (None, False, True, False, 'Syntax: SITE <SP> site-command (execute the specified SITE command).'),
'SITE HELP' : (None, False, None, False, 'Syntax: SITE HELP [<SP> site-command] (show SITE command help).'),
'SIZE': (None, True, True, True, 'Syntax: HELP <SP> file-name (get file size).'),
'STAT': ('l', False, None, True, 'Syntax: STAT [<SP> path name] (status information [list files]).'),
'STOR': ('w', True, True, True, 'Syntax: STOR <SP> file-name (store a file).'),
'STOU': ('w', True, None, True, 'Syntax: STOU [<SP> file-name] (store a file with a unique name).'),
'STRU': (None, True, True, False, 'Syntax: STRU <SP> type (noop; set file structure).'),
'SYST': (None, False, False, False, 'Syntax: SYST (get operating system type).'),
'TYPE': (None, True, True, False, 'Syntax: TYPE <SP> [A | I] (set transfer type).'),
'USER': (None, False, True, False, 'Syntax: USER <SP> user-name (set username).'),
'XCUP': ('e', True, False, True, 'Syntax: XCUP (obsolete; go to parent directory).'),
'XCWD': ('e', True, None, True, 'Syntax: XCWD [<SP> dir-name] (obsolete; change current directory).'),
'XMKD': ('m', True, True, True, 'Syntax: XMDK <SP> dir-name (obsolete; create directory).'),
'XPWD': (None, True, False, False, 'Syntax: XPWD (obsolete; get current dir).'),
'XRMD': ('d', True, True, True, 'Syntax: XRMD <SP> dir-name (obsolete; remove directory).'),
}
class _CommandProperty:
def __init__(self, perm, auth_needed, arg_needed, check_path, help):
self.perm = perm
self.auth_needed = auth_needed
self.arg_needed = arg_needed
self.check_path = check_path
self.help = help
for cmd, properties in proto_cmds.iteritems():
proto_cmds[cmd] = _CommandProperty(*properties)
del cmd, properties
# hack around format_exc function of traceback module to grant
# backward compatibility with python < 2.4
if not hasattr(traceback, 'format_exc'):
try:
import cStringIO as StringIO
except ImportError:
import StringIO
def _format_exc():
f = StringIO.StringIO()
traceback.print_exc(file=f)
data = f.getvalue()
f.close()
return data
traceback.format_exc = _format_exc
def _strerror(err):
"""A wrap around os.strerror() which may be not available on all
platforms (e.g. pythonCE).
- (instance) err: an EnvironmentError or derived class instance.
"""
if hasattr(os, 'strerror'):
return os.strerror(err.errno)
else:
return err.strerror
# the heap used for the scheduled tasks
_tasks = []
def _scheduler():
"""Run the scheduled functions due to expire soonest (if any)."""
now = time.time()
while _tasks and now >= _tasks[0].timeout:
call = heapq.heappop(_tasks)
if call.repush:
heapq.heappush(_tasks, call)
call.repush = False
continue
try:
call.call()
finally:
if not call.cancelled:
call.cancel()
class CallLater:
"""Calls a function at a later time.
It can be used to asynchronously schedule a call within the polling
loop without blocking it. The instance returned is an object that
can be used to cancel or reschedule the call.
"""
def __init__(self, seconds, target, *args, **kwargs):
"""
- (int) seconds: the number of seconds to wait
- (obj) target: the callable object to call later
- args: the arguments to call it with
- kwargs: the keyword arguments to call it with
"""
assert callable(target), "%s is not callable" %target
assert sys.maxint >= seconds >= 0, "%s is not greater than or equal " \
"to 0 seconds" % (seconds)
self.__delay = seconds
self.__target = target
self.__args = args
self.__kwargs = kwargs
# seconds from the epoch at which to call the function
self.timeout = time.time() + self.__delay
self.repush = False
self.cancelled = False
heapq.heappush(_tasks, self)
def __le__(self, other):
return self.timeout <= other.timeout
def call(self):
"""Call this scheduled function."""
assert not self.cancelled, "Already cancelled"
self.__target(*self.__args, **self.__kwargs)
def reset(self):
"""Reschedule this call resetting the current countdown."""
assert not self.cancelled, "Already cancelled"
self.timeout = time.time() + self.__delay
self.repush = True
def delay(self, seconds):
"""Reschedule this call for a later time."""
assert not self.cancelled, "Already cancelled."
assert sys.maxint >= seconds >= 0, "%s is not greater than or equal " \
"to 0 seconds" %(seconds)
self.__delay = seconds
newtime = time.time() + self.__delay
if newtime > self.timeout:
self.timeout = newtime
self.repush = True
else:
# XXX - slow, can be improved
self.timeout = newtime
heapq.heapify(_tasks)
def cancel(self):
"""Unschedule this call."""
assert not self.cancelled, "Already cancelled"
self.cancelled = True
del self.__target, self.__args, self.__kwargs
if self in _tasks:
pos = _tasks.index(self)
if pos == 0:
heapq.heappop(_tasks)
elif pos == len(_tasks) - 1:
_tasks.pop(pos)
else:
_tasks[pos] = _tasks.pop()
heapq._siftup(_tasks, pos)
# --- library defined exceptions
class Error(Exception):
"""Base class for module exceptions."""
class AuthorizerError(Error):
"""Base class for authorizer exceptions."""
# --- loggers
def log(msg):
"""Log messages intended for the end user."""
print msg
def logline(msg):
"""Log commands and responses passing through the command channel."""
print msg
def logerror(msg):
"""Log traceback outputs occurring in case of errors."""
sys.stderr.write(str(msg) + '\n')
sys.stderr.flush()
# --- authorizers
class DummyAuthorizer:
"""Basic "dummy" authorizer class, suitable for subclassing to
create your own custom authorizers.
An "authorizer" is a class handling authentications and permissions
of the FTP server. It is used inside FTPHandler class for verifying
user's password, getting users home directory, checking user
permissions when a file read/write event occurs and changing user
before accessing the filesystem.
DummyAuthorizer is the base authorizer, providing a platform
independent interface for managing "virtual" FTP users. System
dependent authorizers can by written by subclassing this base
class and overriding appropriate methods as necessary.
"""
read_perms = "elr"
write_perms = "adfmw"
def __init__(self):
self.user_table = {}
def add_user(self, username, password, homedir, perm='elr',
msg_login="Login successful.", msg_quit="Goodbye."):
"""Add a user to the virtual users table.
AuthorizerError exceptions raised on error conditions such as
invalid permissions, missing home directory or duplicate usernames.
Optional perm argument is a string referencing the user's
permissions explained below:
Read permissions:
- "e" = change directory (CWD command)
- "l" = list files (LIST, NLST, STAT, MLSD, MLST commands)
- "r" = retrieve file from the server (RETR command)
Write permissions:
- "a" = append data to an existing file (APPE command)
- "d" = delete file or directory (DELE, RMD commands)
- "f" = rename file or directory (RNFR, RNTO commands)
- "m" = create directory (MKD command)
- "w" = store a file to the server (STOR, STOU commands)
Optional msg_login and msg_quit arguments can be specified to
provide customized response strings when user log-in and quit.
"""
if self.has_user(username):
raise AuthorizerError('User "%s" already exists' %username)
if not os.path.isdir(homedir):
raise AuthorizerError('No such directory: "%s"' %homedir)
homedir = os.path.realpath(homedir)
self._check_permissions(username, perm)
dic = {'pwd': str(password),
'home': homedir,
'perm': perm,
'operms': {},
'msg_login': str(msg_login),
'msg_quit': str(msg_quit)
}
self.user_table[username] = dic
def add_anonymous(self, homedir, **kwargs):
"""Add an anonymous user to the virtual users table.
AuthorizerError exception raised on error conditions such as
invalid permissions, missing home directory, or duplicate
anonymous users.
The keyword arguments in kwargs are the same expected by
add_user method: "perm", "msg_login" and "msg_quit".
The optional "perm" keyword argument is a string defaulting to
"elr" referencing "read-only" anonymous user's permissions.
Using write permission values ("adfmw") results in a
RuntimeWarning.
"""
DummyAuthorizer.add_user(self, 'anonymous', '', homedir, **kwargs)
def remove_user(self, username):
"""Remove a user from the virtual users table."""
del self.user_table[username]
def override_perm(self, username, directory, perm, recursive=False):
"""Override permissions for a given directory."""
self._check_permissions(username, perm)
if not os.path.isdir(directory):
raise AuthorizerError('No such directory: "%s"' %directory)
directory = os.path.normcase(os.path.realpath(directory))
home = os.path.normcase(self.get_home_dir(username))
if directory == home:
raise AuthorizerError("Can't override home directory permissions")
if not self._issubpath(directory, home):
raise AuthorizerError("Path escapes user home directory")
self.user_table[username]['operms'][directory] = perm, recursive
def validate_authentication(self, username, password):
"""Return True if the supplied username and password match the
stored credentials."""
if not self.has_user(username):
return False
if username == 'anonymous':
return True
return self.user_table[username]['pwd'] == password
def impersonate_user(self, username, password):
"""Impersonate another user (noop).
It is always called before accessing the filesystem.
By default it does nothing. The subclass overriding this
method is expected to provide a mechanism to change the
current user.
"""
def terminate_impersonation(self):
"""Terminate impersonation (noop).
It is always called after having accessed the filesystem.
By default it does nothing. The subclass overriding this
method is expected to provide a mechanism to switch back
to the original user.
"""
def has_user(self, username):
"""Whether the username exists in the virtual users table."""
return username in self.user_table
def has_perm(self, username, perm, path=None):
"""Whether the user has permission over path (an absolute
pathname of a file or a directory).
Expected perm argument is one of the following letters:
"elradfmw".
"""
if path is None:
return perm in self.user_table[username]['perm']
path = os.path.normcase(path)
for dir in self.user_table[username]['operms'].keys():
operm, recursive = self.user_table[username]['operms'][dir]
if self._issubpath(path, dir):
if recursive:
return perm in operm
if (path == dir) or (os.path.dirname(path) == dir \
and not os.path.isdir(path)):
return perm in operm
return perm in self.user_table[username]['perm']
def get_perms(self, username):
"""Return current user permissions."""
return self.user_table[username]['perm']
def get_home_dir(self, username):
"""Return the user's home directory."""
return self.user_table[username]['home']
def get_msg_login(self, username):
"""Return the user's login message."""
return self.user_table[username]['msg_login']
def get_msg_quit(self, username):
"""Return the user's quitting message."""
return self.user_table[username]['msg_quit']
def _check_permissions(self, username, perm):
warned = 0
for p in perm:
if p not in self.read_perms + self.write_perms:
raise AuthorizerError('No such permission "%s"' %p)
if (username == 'anonymous') and (p in self.write_perms) and not warned:
warnings.warn("Write permissions assigned to anonymous user.",
RuntimeWarning)
warned = 1
def _issubpath(self, a, b):
"""Return True if a is a sub-path of b or if the paths are equal."""
p1 = a.rstrip(os.sep).split(os.sep)
p2 = b.rstrip(os.sep).split(os.sep)
return p1[:len(p2)] == p2
# --- DTP classes
class PassiveDTP(asyncore.dispatcher):
"""This class is an asyncore.dispatcher subclass. It creates a
socket listening on a local port, dispatching the resultant
connection to DTPHandler.
- (int) timeout: the timeout for a remote client to establish
connection with the listening socket. Defaults to 30 seconds.
"""
timeout = 30
def __init__(self, cmd_channel, extmode=False):
"""Initialize the passive data server.
- (instance) cmd_channel: the command channel class instance.
- (bool) extmode: wheter use extended passive mode response type.
"""
asyncore.dispatcher.__init__(self)
self.cmd_channel = cmd_channel
if self.timeout:
self.idler = CallLater(self.timeout, self.handle_timeout)
else:
self.idler = None
ip = self.cmd_channel.getsockname()[0]
self.create_socket(self.cmd_channel.af, socket.SOCK_STREAM)
if self.cmd_channel.passive_ports is None:
# By using 0 as port number value we let kernel choose a
# free unprivileged random port.
self.bind((ip, 0))
else:
ports = list(self.cmd_channel.passive_ports)
while ports:
port = ports.pop(random.randint(0, len(ports) -1))
try:
self.bind((ip, port))
except socket.error, why:
if why[0] == errno.EADDRINUSE: # port already in use
if ports:
continue
# If cannot use one of the ports in the configured
# range we'll use a kernel-assigned port, and log
# a message reporting the issue.
# By using 0 as port number value we let kernel
# choose a free unprivileged random port.
else:
self.bind((ip, 0))
self.cmd_channel.log(
"Can't find a valid passive port in the "
"configured range. A random kernel-assigned "
"port will be used."
)
else:
raise
else:
break
self.listen(5)
port = self.socket.getsockname()[1]
if not extmode:
if self.cmd_channel.masquerade_address:
ip = self.cmd_channel.masquerade_address
# The format of 227 response in not standardized.
# This is the most expected:
self.cmd_channel.respond('227 Entering passive mode (%s,%d,%d).' %(
ip.replace('.', ','), port / 256, port % 256))
else:
self.cmd_channel.respond('229 Entering extended passive mode '
'(|||%d|).' %port)
# --- connection / overridden
def handle_accept(self):
"""Called when remote client initiates a connection."""
try:
sock, addr = self.accept()
except TypeError:
# sometimes accept() might return None (see issue 91)
return
except socket.error, err:
# ECONNABORTED might be thrown on *BSD (see issue 105)
if err[0] != errno.ECONNABORTED:
logerror(traceback.format_exc())
return
else:
# sometimes addr == None instead of (ip, port) (see issue 104)
if addr == None:
return
# Check the origin of data connection. If not expressively
# configured we drop the incoming data connection if remote
# IP address does not match the client's IP address.
if (self.cmd_channel.remote_ip != addr[0]):
if not self.cmd_channel.permit_foreign_addresses:
try:
sock.close()
except socket.error:
pass
msg = 'Rejected data connection from foreign address %s:%s.' \
%(addr[0], addr[1])
self.cmd_channel.respond("425 %s" %msg)
self.cmd_channel.log(msg)
# do not close listening socket: it couldn't be client's blame
return
else:
# site-to-site FTP allowed
msg = 'Established data connection with foreign address %s:%s.'\
%(addr[0], addr[1])
self.cmd_channel.log(msg)
# Immediately close the current channel (we accept only one
# connection at time) and avoid running out of max connections
# limit.
self.close()
# delegate such connection to DTP handler
handler = self.cmd_channel.dtp_handler(sock, self.cmd_channel)
self.cmd_channel.data_channel = handler
self.cmd_channel.on_dtp_connection()
def handle_timeout(self):
self.cmd_channel.respond("421 Passive data channel timed out.")
self.close()
def writable(self):
return 0
def handle_error(self):
"""Called to handle any uncaught exceptions."""
try:
raise
except (KeyboardInterrupt, SystemExit, asyncore.ExitNow):
raise
except:
logerror(traceback.format_exc())
self.close()
def close(self):
asyncore.dispatcher.close(self)
if self.idler is not None and not self.idler.cancelled:
self.idler.cancel()
class ActiveDTP(asyncore.dispatcher):
"""This class is an asyncore.disptacher subclass. It creates a
socket resulting from the connection to a remote user-port,
dispatching it to DTPHandler.
- (int) timeout: the timeout for us to establish connection with
the client's listening data socket.
"""
timeout = 30
def __init__(self, ip, port, cmd_channel):
"""Initialize the active data channel attemping to connect
to remote data socket.
- (str) ip: the remote IP address.
- (int) port: the remote port.
- (instance) cmd_channel: the command channel class instance.
"""
asyncore.dispatcher.__init__(self)
self.cmd_channel = cmd_channel
if self.timeout:
self.idler = CallLater(self.timeout, self.handle_timeout)
else:
self.idler = None
self.create_socket(self.cmd_channel.af, socket.SOCK_STREAM)
try:
self.connect((ip, port))
except socket.gaierror:
self.cmd_channel.respond("425 Can't connect to specified address.")
self.close()
# overridden to prevent unhandled read/write event messages to
# be printed by asyncore on Python < 2.6
def handle_write(self):
pass
def handle_read(self):
pass
def handle_connect(self):
"""Called when connection is established."""
if self.idler is not None and not self.idler.cancelled:
self.idler.cancel()
self.cmd_channel.respond('200 Active data connection established.')
# delegate such connection to DTP handler
handler = self.cmd_channel.dtp_handler(self.socket, self.cmd_channel)
self.cmd_channel.data_channel = handler
self.cmd_channel.on_dtp_connection()
#self.close() # <-- (done automatically)
def handle_timeout(self):
self.cmd_channel.respond("421 Active data channel timed out.")
self.close()
def handle_expt(self):
self.cmd_channel.respond("425 Can't connect to specified address.")
self.close()
def handle_error(self):
"""Called to handle any uncaught exceptions."""
try:
raise
except (KeyboardInterrupt, SystemExit, asyncore.ExitNow):
raise
except:
logerror(traceback.format_exc())
self.cmd_channel.respond("425 Can't connect to specified address.")
self.close()
def close(self):
asyncore.dispatcher.close(self)
if self.idler is not None and not self.idler.cancelled:
self.idler.cancel()
class DTPHandler(asynchat.async_chat):
"""Class handling server-data-transfer-process (server-DTP, see
RFC-959) managing data-transfer operations involving sending
and receiving data.
Class attributes:
- (int) timeout: the timeout which roughly is the maximum time we
permit data transfers to stall for with no progress. If the
timeout triggers, the remote client will be kicked off
(defaults 300).
- (int) ac_in_buffer_size: incoming data buffer size (defaults 65536)
- (int) ac_out_buffer_size: outgoing data buffer size (defaults 65536)
"""
timeout = 300
ac_in_buffer_size = 65536
ac_out_buffer_size = 65536
def __init__(self, sock_obj, cmd_channel):
"""Initialize the command channel.
- (instance) sock_obj: the socket object instance of the newly
established connection.
- (instance) cmd_channel: the command channel class instance.
"""
asynchat.async_chat.__init__(self, sock_obj)
self.cmd_channel = cmd_channel
self.file_obj = None
self.receive = False
self.transfer_finished = False
self.tot_bytes_sent = 0
self.tot_bytes_received = 0
self.data_wrapper = lambda x: x
self._lastdata = 0
self._closed = False
self._had_cr = False
if self.timeout:
self.idler = CallLater(self.timeout, self.handle_timeout)
else:
self.idler = None
# --- utility methods
def _posix_ascii_data_wrapper(self, chunk):
"""The data wrapper used for receiving data in ASCII mode on
systems using a single line terminator, handling those cases
where CRLF ('\r\n') gets delivered in two chunks.
"""
if self._had_cr:
chunk = '\r' + chunk
if chunk.endswith('\r'):
self._had_cr = True
chunk = chunk[:-1]
else:
self._had_cr = False
return chunk.replace('\r\n', os.linesep)
def enable_receiving(self, type):
"""Enable receiving of data over the channel. Depending on the
TYPE currently in use it creates an appropriate wrapper for the
incoming data.
- (str) type: current transfer type, 'a' (ASCII) or 'i' (binary).
"""
if type == 'a':
if os.linesep == '\r\n':
self.data_wrapper = lambda x: x
else:
self.data_wrapper = self._posix_ascii_data_wrapper
elif type == 'i':
self.data_wrapper = lambda x: x
else:
raise TypeError("Unsupported type")
self.receive = True
def get_transmitted_bytes(self):
"Return the number of transmitted bytes."
return self.tot_bytes_sent + self.tot_bytes_received
def transfer_in_progress(self):
"Return True if a transfer is in progress, else False."
return self.get_transmitted_bytes() != 0
# --- connection
def send(self, data):
result = asyncore.dispatcher.send(self, data)
self.tot_bytes_sent += result
return result
def refill_buffer (self):
"""Overridden as a fix around http://bugs.python.org/issue1740572
(when the producer is consumed, close() was called instead of
handle_close()).
"""
while 1:
if len(self.producer_fifo):
p = self.producer_fifo.first()
# a 'None' in the producer fifo is a sentinel,
# telling us to close the channel.
if p is None:
if not self.ac_out_buffer:
self.producer_fifo.pop()
#self.close()
self.handle_close()
return
elif isinstance(p, str):
self.producer_fifo.pop()
self.ac_out_buffer = self.ac_out_buffer + p
return
data = p.more()
if data:
self.ac_out_buffer = self.ac_out_buffer + data
return
else:
self.producer_fifo.pop()
else:
return
def handle_read(self):
"""Called when there is data waiting to be read."""
try:
chunk = self.recv(self.ac_in_buffer_size)
except socket.error:
self.handle_error()
else:
self.tot_bytes_received += len(chunk)
if not chunk:
self.transfer_finished = True
#self.close() # <-- asyncore.recv() already do that...
return
# while we're writing on the file an exception could occur
# in case that filesystem gets full; if this happens we
# let handle_error() method handle this exception, providing
# a detailed error message.
self.file_obj.write(self.data_wrapper(chunk))
def readable(self):
"""Predicate for inclusion in the readable for select()."""
# we don't use asynchat's find terminator feature so we can
# freely avoid to call the original implementation
return self.receive
def writable(self):
"""Predicate for inclusion in the writable for select()."""
return not self.receive and asynchat.async_chat.writable(self)
def handle_timeout(self):
"""Called cyclically to check if data trasfer is stalling with
no progress in which case the client is kicked off.
"""
if self.get_transmitted_bytes() > self._lastdata:
self._lastdata = self.get_transmitted_bytes()
self.idler = CallLater(self.timeout, self.handle_timeout)
else:
msg = "Data connection timed out."
self.cmd_channel.log(msg)
self.cmd_channel.respond("421 " + msg)
self.cmd_channel.close_when_done()
self.close()
def handle_expt(self):
"""Called on "exceptional" data events."""
self.cmd_channel.respond("426 Connection error; transfer aborted.")
self.close()
def handle_error(self):
"""Called when an exception is raised and not otherwise handled."""
try:
raise
except (KeyboardInterrupt, SystemExit, asyncore.ExitNow):
raise
except socket.error, err:
# fixes around various bugs:
# - http://bugs.python.org/issue1736101
# - http://code.google.com/p/pyftpdlib/issues/detail?id=104
# - http://code.google.com/p/pyftpdlib/issues/detail?id=109
if err[0] in (errno.ECONNRESET, errno.ENOTCONN, errno.ESHUTDOWN, \
errno.ECONNABORTED, errno.EPIPE, errno.EBADF):
self.handle_close()
return
else:
logerror(traceback.format_exc())
error = str(err[1])
# an error could occur in case we fail reading / writing
# from / to file (e.g. file system gets full)
except EnvironmentError, err:
error = _strerror(err)
except:
# some other exception occurred; we don't want to provide
# confidential error messages
logerror(traceback.format_exc())
error = "Internal error"
self.cmd_channel.respond("426 %s; transfer aborted." %error)
self.close()
def handle_close(self):
"""Called when the socket is closed."""
# If we used channel for receiving we assume that transfer is
# finished when client closes the connection, if we used channel
# for sending we have to check that all data has been sent
# (responding with 226) or not (responding with 426).
# In both cases handle_close() is automatically called by the
# underlying asynchat module.
if self.receive:
self.transfer_finished = True
action = 'received'
else:
self.transfer_finished = len(self.producer_fifo) == 0
action = 'sent'
if self.transfer_finished:
self.cmd_channel.respond("226 Transfer complete.")
if self.file_obj:
fname = self.cmd_channel.fs.fs2ftp(self.file_obj.name)
self.cmd_channel.log('"%s" %s.' %(fname, action))
else:
tot_bytes = self.get_transmitted_bytes()
msg = "Transfer aborted; %d bytes transmitted." %tot_bytes
self.cmd_channel.respond("426 " + msg)
self.cmd_channel.log(msg)
self.close()
def close(self):
"""Close the data channel, first attempting to close any remaining
file handles."""
if not self._closed:
self._closed = True
asyncore.dispatcher.close(self)
if self.file_obj is not None and not self.file_obj.closed: