382
def put(self, relpath, f, mode=None):
345
def put(self, relpath, f):
384
347
Copy the file-like or string object into the location.
386
349
:param relpath: Location to put the contents, relative to base.
387
350
:param f: File-like or string object.
388
:param mode: The final mode for the file
390
final_path = self._remote_path(relpath)
391
self._put(final_path, f, mode=mode)
393
def _put(self, abspath, f, mode=None):
394
"""Helper function so both put() and copy_abspaths can reuse the code"""
395
tmp_abspath = '%s.tmp.%.9f.%d.%d' % (abspath, time.time(),
352
final_path = self._abspath(relpath)
353
tmp_relpath = '%s.tmp.%.9f.%d.%d' % (relpath, time.time(),
396
354
os.getpid(), random.randint(0,0x7FFFFFFF))
397
fout = self._sftp_open_exclusive(tmp_abspath, mode=mode)
355
tmp_abspath = self._abspath(tmp_relpath)
356
fout = self._sftp_open_exclusive(tmp_relpath)
401
fout.set_pipelined(True)
402
360
self._pump(f, fout)
403
except (IOError, paramiko.SSHException), e:
404
self._translate_io_exception(e, tmp_abspath)
406
self._sftp.chmod(tmp_abspath, mode)
409
self._rename(tmp_abspath, abspath)
361
except (paramiko.SSHException, IOError), e:
362
self._translate_io_exception(e, relpath, ': unable to write')
410
363
except Exception, e:
411
364
# If we fail, try to clean up the temporary file
412
365
# before we throw the exception
413
366
# but don't let another exception mess things up
414
# Write out the traceback, because otherwise
415
# the catch and throw destroys it
417
mutter(traceback.format_exc())
421
369
self._sftp.remove(tmp_abspath)
423
# raise the saved except
425
# raise the original with its traceback if we can.
374
# sftp rename doesn't allow overwriting, so play tricks:
375
tmp_safety = 'bzr.tmp.%.9f.%d.%d' % (time.time(), os.getpid(), random.randint(0, 0x7FFFFFFF))
376
tmp_safety = self._abspath(tmp_safety)
378
self._sftp.rename(final_path, tmp_safety)
385
self._sftp.rename(tmp_abspath, final_path)
386
except (paramiko.SSHException, IOError), e:
387
self._translate_io_exception(e, relpath, ': unable to rename')
393
self._sftp.unlink(tmp_safety)
395
self._sftp.rename(tmp_safety, final_path)
428
397
def iter_files_recursive(self):
429
398
"""Walk the relative paths of all files in this transport."""
533
497
total = self._get_total(relpaths)
535
499
for path in relpaths:
536
path_from = self._remote_path(relpath)
537
path_to = other._remote_path(relpath)
500
path_from = self._abspath(relpath)
501
path_to = other._abspath(relpath)
538
502
self._update_pb(pb, 'copy-to', count, total)
539
self._copy_abspaths(path_from, path_to, mode=mode)
503
self._copy_abspaths(path_from, path_to)
543
return super(SFTPTransport, self).copy_to(relpaths, other, mode=mode, pb=pb)
545
def _rename(self, abs_from, abs_to):
546
"""Do a fancy rename on the remote server.
548
Using the implementation provided by osutils.
551
fancy_rename(abs_from, abs_to,
552
rename_func=self._sftp.rename,
553
unlink_func=self._sftp.remove)
554
except (IOError, paramiko.SSHException), e:
555
self._translate_io_exception(e, abs_from, ': unable to rename to %r' % (abs_to))
507
return super(SFTPTransport, self).copy_to(relpaths, other, pb=pb)
509
# The dummy implementation just does a simple get + put
510
def copy_entry(path):
511
other.put(path, self.get(path))
513
return self._iterate_over(relpaths, copy_entry, pb, 'copy_to', expand=False)
557
515
def move(self, rel_from, rel_to):
558
516
"""Move the item at rel_from to the location at rel_to"""
559
path_from = self._remote_path(rel_from)
560
path_to = self._remote_path(rel_to)
561
self._rename(path_from, path_to)
517
path_from = self._abspath(rel_from)
518
path_to = self._abspath(rel_to)
520
self._sftp.rename(path_from, path_to)
521
except (IOError, paramiko.SSHException), e:
522
self._translate_io_exception(e, path_from, ': unable to move to: %r' % path_to)
563
524
def delete(self, relpath):
564
525
"""Delete the item at relpath"""
565
path = self._remote_path(relpath)
526
path = self._abspath(relpath)
567
528
self._sftp.remove(path)
568
529
except (IOError, paramiko.SSHException), e:
833
787
WARNING: This breaks the SFTPClient abstraction, so it
834
788
could easily break against an updated version of paramiko.
836
:param abspath: The remote absolute path where the file should be opened
837
:param mode: The mode permissions bits for the new file
790
:param relpath: The relative path, where the file should be opened
839
path = self._sftp._adjust_cwd(abspath)
792
path = self._sftp._adjust_cwd(self._abspath(relpath))
840
793
attr = SFTPAttributes()
843
omode = (SFTP_FLAG_WRITE | SFTP_FLAG_CREATE
794
mode = (SFTP_FLAG_WRITE | SFTP_FLAG_CREATE
844
795
| SFTP_FLAG_TRUNC | SFTP_FLAG_EXCL)
846
t, msg = self._sftp._request(CMD_OPEN, path, omode, attr)
797
t, msg = self._sftp._request(CMD_OPEN, path, mode, attr)
847
798
if t != CMD_HANDLE:
848
799
raise TransportError('Expected an SFTP handle')
849
800
handle = msg.get_string()
850
return SFTPFile(self._sftp, handle, 'wb', -1)
801
return SFTPFile(self._sftp, handle, 'w', -1)
851
802
except (paramiko.SSHException, IOError), e:
852
self._translate_io_exception(e, abspath, ': unable to open',
803
self._translate_io_exception(e, relpath, ': unable to open',
853
804
failure_exc=FileExists)
856
# ------------- server test implementation --------------
860
from bzrlib.tests.stub_sftp import StubServer, StubSFTPServer
862
STUB_SERVER_KEY = """
863
-----BEGIN RSA PRIVATE KEY-----
864
MIICWgIBAAKBgQDTj1bqB4WmayWNPB+8jVSYpZYk80Ujvj680pOTh2bORBjbIAyz
865
oWGW+GUjzKxTiiPvVmxFgx5wdsFvF03v34lEVVhMpouqPAYQ15N37K/ir5XY+9m/
866
d8ufMCkjeXsQkKqFbAlQcnWMCRnOoPHS3I4vi6hmnDDeeYTSRvfLbW0fhwIBIwKB
867
gBIiOqZYaoqbeD9OS9z2K9KR2atlTxGxOJPXiP4ESqP3NVScWNwyZ3NXHpyrJLa0
868
EbVtzsQhLn6rF+TzXnOlcipFvjsem3iYzCpuChfGQ6SovTcOjHV9z+hnpXvQ/fon
869
soVRZY65wKnF7IAoUwTmJS9opqgrN6kRgCd3DASAMd1bAkEA96SBVWFt/fJBNJ9H
870
tYnBKZGw0VeHOYmVYbvMSstssn8un+pQpUm9vlG/bp7Oxd/m+b9KWEh2xPfv6zqU
871
avNwHwJBANqzGZa/EpzF4J8pGti7oIAPUIDGMtfIcmqNXVMckrmzQ2vTfqtkEZsA
872
4rE1IERRyiJQx6EJsz21wJmGV9WJQ5kCQQDwkS0uXqVdFzgHO6S++tjmjYcxwr3g
873
H0CoFYSgbddOT6miqRskOQF3DZVkJT3kyuBgU2zKygz52ukQZMqxCb1fAkASvuTv
874
qfpH87Qq5kQhNKdbbwbmd2NxlNabazPijWuphGTdW0VfJdWfklyS2Kr+iqrs/5wV
875
HhathJt636Eg7oIjAkA8ht3MQ+XSl9yIJIS8gVpbPxSw5OMfw0PjVE7tBdQruiSc
876
nvuQES5C9BMHjF39LZiGH1iLQy7FgdHyoP+eodI7
877
-----END RSA PRIVATE KEY-----
881
class SingleListener(threading.Thread):
883
def __init__(self, callback):
884
threading.Thread.__init__(self)
885
self._callback = callback
886
self._socket = socket.socket()
887
self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
888
self._socket.bind(('localhost', 0))
889
self._socket.listen(1)
890
self.port = self._socket.getsockname()[1]
891
self.stop_event = threading.Event()
894
s, _ = self._socket.accept()
895
# now close the listen socket
898
self._callback(s, self.stop_event)
900
pass #Ignore socket errors
902
# probably a failed test
903
warning('Exception from within unit test server thread: %r' % x)
906
self.stop_event.set()
907
# use a timeout here, because if the test fails, the server thread may
908
# never notice the stop_event.
912
class SFTPServer(Server):
913
"""Common code for SFTP server facilities."""
916
self._original_vendor = None
918
self._server_homedir = None
919
self._listener = None
921
self._vendor = 'none'
925
def _get_sftp_url(self, path):
926
"""Calculate an sftp url to this server for path."""
927
return 'sftp://foo:bar@localhost:%d/%s' % (self._listener.port, path)
929
def log(self, message):
930
"""StubServer uses this to log when a new server is created."""
931
self.logs.append(message)
933
def _run_server(self, s, stop_event):
934
ssh_server = paramiko.Transport(s)
935
key_file = os.path.join(self._homedir, 'test_rsa.key')
936
file(key_file, 'w').write(STUB_SERVER_KEY)
937
host_key = paramiko.RSAKey.from_private_key_file(key_file)
938
ssh_server.add_server_key(host_key)
939
server = StubServer(self)
940
ssh_server.set_subsystem_handler('sftp', paramiko.SFTPServer,
941
StubSFTPServer, root=self._root,
942
home=self._server_homedir)
943
event = threading.Event()
944
ssh_server.start_server(event, server)
946
stop_event.wait(30.0)
950
self._original_vendor = _ssh_vendor
951
_ssh_vendor = self._vendor
952
self._homedir = os.getcwdu()
953
if self._server_homedir is None:
954
self._server_homedir = self._homedir
956
# FIXME WINDOWS: _root should be _server_homedir[0]:/
957
self._listener = SingleListener(self._run_server)
958
self._listener.setDaemon(True)
959
self._listener.start()
962
"""See bzrlib.transport.Server.tearDown."""
964
self._listener.stop()
965
_ssh_vendor = self._original_vendor
968
class SFTPServerWithoutSSH(SFTPServer):
970
Common code for an SFTP server over a clear TCP loopback socket,
971
instead of over an SSH secured socket.
975
super(SFTPServerWithoutSSH, self).__init__()
976
self._vendor = 'loopback'
978
def _run_server(self, sock, stop_event):
979
class FakeChannel(object):
980
def get_transport(self):
982
def get_log_channel(self):
986
def get_hexdump(self):
989
server = paramiko.SFTPServer(FakeChannel(), 'sftp', StubServer(self), StubSFTPServer,
990
root=self._root, home=self._server_homedir)
991
server.start_subsystem('sftp', None, sock)
992
server.finish_subsystem()
995
class SFTPAbsoluteServer(SFTPServerWithoutSSH):
996
"""A test server for sftp transports, using absolute urls."""
999
"""See bzrlib.transport.Server.get_url."""
1000
return self._get_sftp_url(urlescape(self._homedir[1:]))
1003
class SFTPHomeDirServer(SFTPServerWithoutSSH):
1004
"""A test server for sftp transports, using homedir relative urls."""
1007
"""See bzrlib.transport.Server.get_url."""
1008
return self._get_sftp_url("~/")
1011
class SFTPSiblingAbsoluteServer(SFTPAbsoluteServer):
1012
"""A test servere for sftp transports, using absolute urls to non-home."""
1015
self._server_homedir = '/dev/noone/runs/tests/here'
1016
super(SFTPSiblingAbsoluteServer, self).setUp()
1019
def get_test_permutations():
1020
"""Return the permutations to be used in testing."""
1021
return [(SFTPTransport, SFTPAbsoluteServer),
1022
(SFTPTransport, SFTPHomeDirServer),
1023
(SFTPTransport, SFTPSiblingAbsoluteServer),