forked from akkakks/ipv6-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ftpserver.py
3966 lines (3467 loc) · 151 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 988 2012-01-25 19:11:43Z g.rodola $
# pyftpdlib is released under the MIT license, reproduced below:
# ======================================================================
# Copyright (C) 2007-2012 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
import optparse
from tarfile import filemode as _filemode
try:
import pwd
import grp
except ImportError:
pwd = grp = None
# http://code.google.com/p/pysendfile/
try:
from sendfile import sendfile
except ImportError:
sendfile = None
__all__ = ['proto_cmds', 'Error', 'log', 'logline', 'logerror', 'DummyAuthorizer',
'AuthorizerError', 'FTPHandler', 'FTPServer', 'PassiveDTP',
'ActiveDTP', 'DTPHandler', 'ThrottledDTPHandler', 'FileProducer',
'BufferedIteratorProducer', 'AbstractedFS', 'CallLater', 'CallEvery']
__pname__ = 'Python FTP server library (pyftpdlib)'
__ver__ = '0.7.0'
__date__ = '2012-01-25'
__author__ = "Giampaolo Rodola' <[email protected]>"
__web__ = 'http://code.google.com/p/pyftpdlib/'
_DISCONNECTED = frozenset((errno.ECONNRESET, errno.ENOTCONN, errno.ESHUTDOWN,
errno.ECONNABORTED, errno.EPIPE, errno.EBADF))
proto_cmds = {
'ABOR' : dict(perm=None, auth=True, arg=False,
help='Syntax: ABOR (abort transfer).'),
'ALLO' : dict(perm=None, auth=True, arg=True,
help='Syntax: ALLO <SP> bytes (noop; allocate storage).'),
'APPE' : dict(perm='a', auth=True, arg=True,
help='Syntax: APPE <SP> file-name (append data to file).'),
'CDUP' : dict(perm='e', auth=True, arg=False,
help='Syntax: CDUP (go to parent directory).'),
'CWD' : dict(perm='e', auth=True, arg=None,
help='Syntax: CWD [<SP> dir-name] (change working directory).'),
'DELE' : dict(perm='d', auth=True, arg=True,
help='Syntax: DELE <SP> file-name (delete file).'),
'EPRT' : dict(perm=None, auth=True, arg=True,
help='Syntax: EPRT <SP> |proto|ip|port| (extended active mode).'),
'EPSV' : dict(perm=None, auth=True, arg=None,
help='Syntax: EPSV [<SP> proto/"ALL"] (extended passive mode).'),
'FEAT' : dict(perm=None, auth=False, arg=False,
help='Syntax: FEAT (list all new features supported).'),
'HELP' : dict(perm=None, auth=False, arg=None,
help='Syntax: HELP [<SP> cmd] (show help).'),
'LIST' : dict(perm='l', auth=True, arg=None,
help='Syntax: LIST [<SP> path] (list files).'),
'MDTM' : dict(perm='l', auth=True, arg=True,
help='Syntax: MDTM [<SP> path] (file last modification time).'),
'MLSD' : dict(perm='l', auth=True, arg=None,
help='Syntax: MLSD [<SP> path] (list directory).'),
'MLST' : dict(perm='l', auth=True, arg=None,
help='Syntax: MLST [<SP> path] (show information about path).'),
'MODE' : dict(perm=None, auth=True, arg=True,
help='Syntax: MODE <SP> mode (noop; set data transfer mode).'),
'MKD' : dict(perm='m', auth=True, arg=True,
help='Syntax: MKD <SP> path (create directory).'),
'NLST' : dict(perm='l', auth=True, arg=None,
help='Syntax: NLST [<SP> path] (list path in a compact form).'),
'NOOP' : dict(perm=None, auth=False, arg=False,
help='Syntax: NOOP (just do nothing).'),
'OPTS' : dict(perm=None, auth=True, arg=True,
help='Syntax: OPTS <SP> cmd [<SP> option] (set option for command).'),
'PASS' : dict(perm=None, auth=False, arg=True,
help='Syntax: PASS <SP> password (set user password).'),
'PASV' : dict(perm=None, auth=True, arg=False,
help='Syntax: PASV (open passive data connection).'),
'PORT' : dict(perm=None, auth=True, arg=True,
help='Syntax: PORT <sp> h1,h2,h3,h4,p1,p2 (open active data connection).'),
'PWD' : dict(perm=None, auth=True, arg=False,
help='Syntax: PWD (get current working directory).'),
'QUIT' : dict(perm=None, auth=False, arg=False,
help='Syntax: QUIT (quit current session).'),
'REIN' : dict(perm=None, auth=True, arg=False,
help='Syntax: REIN (flush account).'),
'REST' : dict(perm=None, auth=True, arg=True,
help='Syntax: REST <SP> offset (set file offset).'),
'RETR' : dict(perm='r', auth=True, arg=True,
help='Syntax: RETR <SP> file-name (retrieve a file).'),
'RMD' : dict(perm='d', auth=True, arg=True,
help='Syntax: RMD <SP> dir-name (remove directory).'),
'RNFR' : dict(perm='f', auth=True, arg=True,
help='Syntax: RNFR <SP> file-name (rename (source name)).'),
'RNTO' : dict(perm='f', auth=True, arg=True,
help='Syntax: RNTO <SP> file-name (rename (destination name)).'),
'SITE' : dict(perm=None, auth=False, arg=True,
help='Syntax: SITE <SP> site-command (execute SITE command).'),
'SITE HELP' : dict(perm=None, auth=False, arg=None,
help='Syntax: SITE HELP [<SP> site-command] (show SITE command help).'),
'SITE CHMOD': dict(perm='M', auth=True, arg=True,
help='Syntax: SITE CHMOD <SP> mode path (change file mode).'),
'SIZE' : dict(perm='l', auth=True, arg=True,
help='Syntax: SIZE <SP> file-name (get file size).'),
'STAT' : dict(perm='l', auth=False, arg=None,
help='Syntax: STAT [<SP> path name] (server stats [list files]).'),
'STOR' : dict(perm='w', auth=True, arg=True,
help='Syntax: STOR <SP> file-name (store a file).'),
'STOU' : dict(perm='w', auth=True, arg=None,
help='Syntax: STOU [<SP> file-name] (store a file with a unique name).'),
'STRU' : dict(perm=None, auth=True, arg=True,
help='Syntax: STRU <SP> type (noop; set file structure).'),
'SYST' : dict(perm=None, auth=False, arg=False,
help='Syntax: SYST (get operating system type).'),
'TYPE' : dict(perm=None, auth=True, arg=True,
help='Syntax: TYPE <SP> [A | I] (set transfer type).'),
'USER' : dict(perm=None, auth=False, arg=True,
help='Syntax: USER <SP> user-name (set username).'),
'XCUP' : dict(perm='e', auth=True, arg=False,
help='Syntax: XCUP (obsolete; go to parent directory).'),
'XCWD' : dict(perm='e', auth=True, arg=None,
help='Syntax: XCWD [<SP> dir-name] (obsolete; change directory).'),
'XMKD' : dict(perm='m', auth=True, arg=True,
help='Syntax: XMKD <SP> dir-name (obsolete; create directory).'),
'XPWD' : dict(perm=None, auth=True, arg=False,
help='Syntax: XPWD (obsolete; get current dir).'),
'XRMD' : dict(perm='d', auth=True, arg=True,
help='Syntax: XRMD <SP> dir-name (obsolete; remove directory).'),
}
if not hasattr(os, 'chmod'):
del proto_cmds['SITE CHMOD']
# A wrapper around os.strerror() which may be not available
# on all platforms (e.g. pythonCE). Expected arg is a
# EnvironmentError or derived class instance.
if hasattr(os, 'strerror'):
_strerror = lambda err: os.strerror(err.errno)
else:
_strerror = lambda err: err.strerror
class _Scheduler(object):
"""Run the scheduled functions due to expire soonest (if any)."""
def __init__(self):
# the heap used for the scheduled tasks
self._tasks = []
self._cancellations = 0
def __call__(self):
now = time.time()
calls = []
while self._tasks:
if now < self._tasks[0].timeout:
break
call = heapq.heappop(self._tasks)
if not call.cancelled:
calls.append(call)
else:
self._cancellations -= 1
for call in calls:
if call._repush:
heapq.heappush(self._tasks, call)
call._repush = False
continue
try:
call.call()
except (KeyboardInterrupt, SystemExit, asyncore.ExitNow):
raise
except:
logerror(traceback.format_exc())
# remove cancelled tasks and re-heapify the queue if the
# number of cancelled tasks is more than the half of the
# entire queue
if self._cancellations > 512 \
and self._cancellations > (len(self._tasks) >> 1):
self._cancellations = 0
self._tasks = [x for x in self._tasks if not x.cancelled]
self.reheapify()
def register(self, what):
heapq.heappush(self._tasks, what)
def unregister(self, what):
self._cancellations += 1
def reheapify(self):
heapq.heapify(self._tasks)
_scheduler = _Scheduler()
# dirty hack to support property.setter on python < 2.6
if not hasattr(property, "setter"):
class property(property):
def setter(self, value):
cls_ns = sys._getframe(1).f_locals
for k, v in cls_ns.iteritems():
if v == self:
name = k
break
cls_ns[name] = property(self.fget, value, self.fdel, self.__doc__)
return cls_ns[name]
_months_map = {1:'Jan', 2:'Feb', 3:'Mar', 4:'Apr', 5:'May', 6:'Jun', 7:'Jul',
8:'Aug', 9:'Sep', 10:'Oct', 11:'Nov', 12:'Dec'}
class CallLater(object):
"""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.
"""
__slots__ = ('_delay', '_target', '_args', '_kwargs', '_errback',
'_repush', 'timeout', 'cancelled')
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; a special
'_errback' parameter can be passed: it is a callable
called in case target function raises an exception.
"""
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
self._errback = kwargs.pop('_errback', None)
self._repush = False
# seconds from the epoch at which to call the function
self.timeout = time.time() + self._delay
self.cancelled = False
_scheduler.register(self)
def __lt__(self, other):
return self.timeout < other.timeout
def __le__(self, other):
return self.timeout <= other.timeout
def _post_call(self, exc):
if not self.cancelled:
self.cancel()
def call(self):
"""Call this scheduled function."""
assert not self.cancelled, "Already cancelled"
exc = None
try:
try:
self._target(*self._args, **self._kwargs)
except (KeyboardInterrupt, SystemExit, asyncore.ExitNow):
raise
except Exception, exc:
if self._errback is not None:
self._errback()
else:
raise
finally:
self._post_call(exc)
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
_scheduler.reheapify()
def cancel(self):
"""Unschedule this call."""
assert not self.cancelled, "Already cancelled"
self.cancelled = True
del self._target, self._args, self._kwargs, self._errback
_scheduler.unregister(self)
class CallEvery(CallLater):
"""Calls a function every x seconds.
It accepts the same arguments as CallLater and shares the same API.
"""
def _post_call(self, exc):
if not self.cancelled:
if exc:
self.cancel()
else:
self.timeout = time.time() + self._delay
_scheduler.register(self)
# --- library defined exceptions
class Error(Exception):
"""Base class for module exceptions."""
class AuthorizerError(Error):
"""Base class for authorizer exceptions."""
class _FileReadWriteError(OSError):
"""Exception raised when reading or writing a file during a transfer."""
# --- 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(object):
"""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 = "adfmwM"
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, SIZE, MDTM 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)
- "M" = change file mode (SITE CHMOD command)
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 ValueError('user "%s" already exists' % username)
if not os.path.isdir(homedir):
raise ValueError('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 ("adfmwM") 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 ValueError('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 ValueError("can't override home directory permissions")
if not self._issubpath(directory, home):
raise ValueError("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, username):
"""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:
"elradfmwM".
"""
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 ValueError('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(object, 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.
"""
self.cmd_channel = cmd_channel
self.log = cmd_channel.log
self.log_exception = cmd_channel.log_exception
self._closed = False
asyncore.dispatcher.__init__(self)
if self.timeout:
self._idler = CallLater(self.timeout, self.handle_timeout,
_errback=self.handle_error)
else:
self._idler = None
local_ip = self.cmd_channel.socket.getsockname()[0]
if local_ip in self.cmd_channel.masquerade_address_map:
masqueraded_ip = self.cmd_channel.masquerade_address_map[local_ip]
elif self.cmd_channel.masquerade_address:
masqueraded_ip = self.cmd_channel.masquerade_address
else:
masqueraded_ip = None
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((local_ip, 0))
else:
ports = list(self.cmd_channel.passive_ports)
while ports:
port = ports.pop(random.randint(0, len(ports) -1))
self.set_reuse_addr()
try:
self.bind((local_ip, port))
except socket.error, err:
if err.args[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((local_ip, 0))
self.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:
ip = masqueraded_ip or local_ip
if ip.startswith('::ffff:'):
# In this scenario, the server has an IPv6 socket, but
# the remote client is using IPv4 and its address is
# represented as an IPv4-mapped IPv6 address which
# looks like this ::ffff:151.12.5.65, see:
# http://en.wikipedia.org/wiki/IPv6#IPv4-mapped_addresses
# http://tools.ietf.org/html/rfc3493.html#section-3.7
# We truncate the first bytes to make it look like a
# common IPv4 address.
ip = ip[7:]
# 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)
def set_reuse_addr(self):
# overridden for convenience; avoid to reuse address on Windows
if (os.name in ('nt', 'ce')) or (sys.platform == 'cygwin'):
return
asyncore.dispatcher.set_reuse_addr(self)
# --- connection / overridden
def handle_accept(self):
"""Called when remote client initiates a connection."""
if not self.cmd_channel.connected:
return self.close()
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.args[0] != errno.ECONNABORTED:
self.log_exception(self)
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.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.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
if self.cmd_channel.connected:
handler = self.cmd_channel.dtp_handler(sock, self.cmd_channel)
if handler.connected:
self.cmd_channel.data_channel = handler
self.cmd_channel._on_dtp_connection()
def handle_timeout(self):
if self.cmd_channel.connected:
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):
if not self._closed:
self._closed = True
asyncore.dispatcher.close(self)
if self._idler is not None and not self._idler.cancelled:
self._idler.cancel()
class ActiveDTP(object, 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.
"""
self.cmd_channel = cmd_channel
self.log = cmd_channel.log
self.log_exception = cmd_channel.log_exception
self._closed = True
asyncore.dispatcher.__init__(self)
if self.timeout:
self._idler = CallLater(self.timeout, self.handle_timeout,
_errback=self.handle_error)
else:
self._idler = None
if ip.count('.') == 4:
self._cmd = "PORT"
self._normalized_addr = "%s:%s" % (ip, port)
else:
self._cmd = "EPRT"
self._normalized_addr = "[%s]:%s" % (ip, port)
self.create_socket(self.cmd_channel._af, socket.SOCK_STREAM)
# Have the active connection come from the same IP address
# as the command channel, see:
# http://code.google.com/p/pyftpdlib/issues/detail?id=123
source_ip = self.cmd_channel.socket.getsockname()[0]
self.bind((source_ip, 0))
try:
self.connect((ip, port))
except (socket.gaierror, socket.error):
self.handle_expt()
# 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()
if not self.cmd_channel.connected:
return self.close()
# fix for asyncore on python < 2.6, meaning we aren't
# actually connected.
# test_active_conn_error tests this condition
err = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
if err != 0:
raise socket.error(err)
#
msg = 'Active data connection established.'
self.cmd_channel.respond('200 ' + msg)
self.cmd_channel.log_cmd(self._cmd, self._normalized_addr, 200, msg)
#
if not self.cmd_channel.connected:
return self.close()
# 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()
# Can't close right now as the handler would have the socket
# object disconnected. This class will be "closed" once the
# data transfer is completed or the client disconnects.
#self.close()
def handle_timeout(self):
if self.cmd_channel.connected:
msg = "Active data channel timed out."
self.cmd_channel.respond("421 " + msg)
self.cmd_channel.log_cmd(self._cmd, self._normalized_addr, 421, msg)
self.close()
def handle_expt(self):
if self.cmd_channel.connected:
msg = "Can't connect to specified address."
self.cmd_channel.respond("425 " + msg)
self.cmd_channel.log_cmd(self._cmd, self._normalized_addr, 425, msg)
self.close()
def handle_error(self):
"""Called to handle any uncaught exceptions."""
try:
raise
except (KeyboardInterrupt, SystemExit, asyncore.ExitNow):
raise
except (socket.gaierror, socket.error):
pass
except:
self.log_exception(self)
self.handle_expt()
def close(self):
if not self._closed:
self._closed = True
asyncore.dispatcher.close(self)
if self._idler is not None and not self._idler.cancelled:
self._idler.cancel()
class DTPHandler(object, 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.
"""
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.cmd = None
self.log = cmd_channel.log
self.log_exception = cmd_channel.log_exception
self._data_wrapper = lambda x: x
self._lastdata = 0
self._closed = False
self._had_cr = False
self._start_time = time.time()
self._resp = None
self._offset = None
self._filefd = None
if self.timeout:
self._idler = CallEvery(self.timeout, self.handle_timeout,