23
23
from paramiko import ServerInterface, SFTPServerInterface, SFTPServer, SFTPAttributes, \
24
24
SFTPHandle, SFTP_OK, AUTH_SUCCESSFUL, OPEN_SUCCEEDED
26
27
from bzrlib.osutils import pathjoin
27
28
from bzrlib.trace import mutter
65
66
def __init__(self, server, root, home=None):
66
67
SFTPServerInterface.__init__(self, server)
68
# All paths are actually relative to 'root'.
69
# this is like implementing chroot().
74
assert home.startswith(self.root), \
75
"home must be a subdirectory of root (%s vs %s)" \
71
77
self.home = home[len(self.root):]
72
if (len(self.home) > 0) and (self.home[0] == '/'):
78
if self.home.startswith('/'):
73
79
self.home = self.home[1:]
74
80
server._test_case.log('sftpserver - new connection')
76
82
def _realpath(self, path):
83
# paths returned from self.canonicalize() always start with
84
# a path separator. So if 'root' is just '/', this would cause
85
# a double slash at the beginning '//home/dir'.
87
return self.canonicalize(path)
77
88
return self.root + self.canonicalize(path)
79
def canonicalize(self, path):
80
if os.path.isabs(path):
81
return os.path.normpath(path)
83
return os.path.normpath('/' + os.path.join(self.home, path))
90
if sys.platform == 'win32':
91
def canonicalize(self, path):
92
# Win32 sftp paths end up looking like
93
# sftp://host@foo/h:/foo/bar
94
# which means absolute paths look like:
96
# and relative paths stay the same:
98
# win32 needs to use the Unicode APIs. so we require the
99
# paths to be utf8 (Linux just uses bytestreams)
100
thispath = path.decode('utf8')
101
if path.startswith('/'):
103
return os.path.normpath(thispath[1:])
105
return os.path.normpath(os.path.join(self.home, thispath))
107
def canonicalize(self, path):
108
if os.path.isabs(path):
109
return os.path.normpath(path)
111
return os.path.normpath('/' + os.path.join(self.home, path))
85
113
def chattr(self, path, attr):
96
124
# TODO: win32 incorrectly lists paths with non-ascii if path is not
97
125
# unicode. However on Linux the server should only deal with
98
126
# bytestreams and posix.listdir does the right thing
99
flist = os.listdir(path)
127
if sys.platform == 'win32':
128
flist = [f.encode('utf8') for f in os.listdir(path)]
130
flist = os.listdir(path)
100
131
for fname in flist:
101
132
attr = SFTPAttributes.from_stat(os.stat(pathjoin(path, fname)))
102
133
attr.filename = fname