You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

TransportSftp.java 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  1. /*
  2. * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org>
  3. * and other copyright owners as documented in the project's IP log.
  4. *
  5. * This program and the accompanying materials are made available
  6. * under the terms of the Eclipse Distribution License v1.0 which
  7. * accompanies this distribution, is reproduced below, and is
  8. * available at http://www.eclipse.org/org/documents/edl-v10.php
  9. *
  10. * All rights reserved.
  11. *
  12. * Redistribution and use in source and binary forms, with or
  13. * without modification, are permitted provided that the following
  14. * conditions are met:
  15. *
  16. * - Redistributions of source code must retain the above copyright
  17. * notice, this list of conditions and the following disclaimer.
  18. *
  19. * - Redistributions in binary form must reproduce the above
  20. * copyright notice, this list of conditions and the following
  21. * disclaimer in the documentation and/or other materials provided
  22. * with the distribution.
  23. *
  24. * - Neither the name of the Eclipse Foundation, Inc. nor the
  25. * names of its contributors may be used to endorse or promote
  26. * products derived from this software without specific prior
  27. * written permission.
  28. *
  29. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  30. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  31. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  32. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  33. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  34. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  35. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  36. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  37. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  38. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  39. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  40. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  41. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  42. */
  43. package org.eclipse.jgit.transport;
  44. import java.io.BufferedReader;
  45. import java.io.FileNotFoundException;
  46. import java.io.IOException;
  47. import java.io.OutputStream;
  48. import java.text.MessageFormat;
  49. import java.util.ArrayList;
  50. import java.util.Collection;
  51. import java.util.Collections;
  52. import java.util.Comparator;
  53. import java.util.EnumSet;
  54. import java.util.HashMap;
  55. import java.util.List;
  56. import java.util.Map;
  57. import java.util.Set;
  58. import java.util.TreeMap;
  59. import org.eclipse.jgit.errors.NotSupportedException;
  60. import org.eclipse.jgit.errors.TransportException;
  61. import org.eclipse.jgit.internal.JGitText;
  62. import org.eclipse.jgit.lib.Constants;
  63. import org.eclipse.jgit.lib.ObjectId;
  64. import org.eclipse.jgit.lib.ObjectIdRef;
  65. import org.eclipse.jgit.lib.ProgressMonitor;
  66. import org.eclipse.jgit.lib.Ref;
  67. import org.eclipse.jgit.lib.Ref.Storage;
  68. import org.eclipse.jgit.lib.Repository;
  69. import org.eclipse.jgit.lib.SymbolicRef;
  70. import com.jcraft.jsch.Channel;
  71. import com.jcraft.jsch.ChannelSftp;
  72. import com.jcraft.jsch.JSchException;
  73. import com.jcraft.jsch.SftpATTRS;
  74. import com.jcraft.jsch.SftpException;
  75. /**
  76. * Transport over the non-Git aware SFTP (SSH based FTP) protocol.
  77. * <p>
  78. * The SFTP transport does not require any specialized Git support on the remote
  79. * (server side) repository. Object files are retrieved directly through secure
  80. * shell's FTP protocol, making it possible to copy objects from a remote
  81. * repository that is available over SSH, but whose remote host does not have
  82. * Git installed.
  83. * <p>
  84. * Unlike the HTTP variant (see {@link TransportHttp}) we rely upon being able
  85. * to list files in directories, as the SFTP protocol supports this function. By
  86. * listing files through SFTP we can avoid needing to have current
  87. * <code>objects/info/packs</code> or <code>info/refs</code> files on the
  88. * remote repository and access the data directly, much as Git itself would.
  89. * <p>
  90. * Concurrent pushing over this transport is not supported. Multiple concurrent
  91. * push operations may cause confusion in the repository state.
  92. *
  93. * @see WalkFetchConnection
  94. */
  95. public class TransportSftp extends SshTransport implements WalkTransport {
  96. static final TransportProtocol PROTO_SFTP = new TransportProtocol() {
  97. public String getName() {
  98. return JGitText.get().transportProtoSFTP;
  99. }
  100. public Set<String> getSchemes() {
  101. return Collections.singleton("sftp"); //$NON-NLS-1$
  102. }
  103. public Set<URIishField> getRequiredFields() {
  104. return Collections.unmodifiableSet(EnumSet.of(URIishField.HOST,
  105. URIishField.PATH));
  106. }
  107. public Set<URIishField> getOptionalFields() {
  108. return Collections.unmodifiableSet(EnumSet.of(URIishField.USER,
  109. URIishField.PASS, URIishField.PORT));
  110. }
  111. public int getDefaultPort() {
  112. return 22;
  113. }
  114. public Transport open(URIish uri, Repository local, String remoteName)
  115. throws NotSupportedException {
  116. return new TransportSftp(local, uri);
  117. }
  118. };
  119. TransportSftp(final Repository local, final URIish uri) {
  120. super(local, uri);
  121. }
  122. @Override
  123. public FetchConnection openFetch() throws TransportException {
  124. final SftpObjectDB c = new SftpObjectDB(uri.getPath());
  125. final WalkFetchConnection r = new WalkFetchConnection(this, c);
  126. r.available(c.readAdvertisedRefs());
  127. return r;
  128. }
  129. @Override
  130. public PushConnection openPush() throws TransportException {
  131. final SftpObjectDB c = new SftpObjectDB(uri.getPath());
  132. final WalkPushConnection r = new WalkPushConnection(this, c);
  133. r.available(c.readAdvertisedRefs());
  134. return r;
  135. }
  136. ChannelSftp newSftp() throws TransportException {
  137. final int tms = getTimeout() > 0 ? getTimeout() * 1000 : 0;
  138. try {
  139. // @TODO: Fix so that this operation is generic and casting to
  140. // JschSession is no longer necessary.
  141. final Channel channel = ((JschSession) getSession())
  142. .getSftpChannel();
  143. channel.connect(tms);
  144. return (ChannelSftp) channel;
  145. } catch (JSchException je) {
  146. throw new TransportException(uri, je.getMessage(), je);
  147. }
  148. }
  149. class SftpObjectDB extends WalkRemoteObjectDatabase {
  150. private final String objectsPath;
  151. private ChannelSftp ftp;
  152. SftpObjectDB(String path) throws TransportException {
  153. if (path.startsWith("/~")) //$NON-NLS-1$
  154. path = path.substring(1);
  155. if (path.startsWith("~/")) //$NON-NLS-1$
  156. path = path.substring(2);
  157. try {
  158. ftp = newSftp();
  159. ftp.cd(path);
  160. ftp.cd("objects"); //$NON-NLS-1$
  161. objectsPath = ftp.pwd();
  162. } catch (TransportException err) {
  163. close();
  164. throw err;
  165. } catch (SftpException je) {
  166. throw new TransportException(MessageFormat.format(
  167. JGitText.get().cannotEnterObjectsPath, path,
  168. je.getMessage()), je);
  169. }
  170. }
  171. SftpObjectDB(final SftpObjectDB parent, final String p)
  172. throws TransportException {
  173. try {
  174. ftp = newSftp();
  175. ftp.cd(parent.objectsPath);
  176. ftp.cd(p);
  177. objectsPath = ftp.pwd();
  178. } catch (TransportException err) {
  179. close();
  180. throw err;
  181. } catch (SftpException je) {
  182. throw new TransportException(MessageFormat.format(
  183. JGitText.get().cannotEnterPathFromParent, p,
  184. parent.objectsPath, je.getMessage()), je);
  185. }
  186. }
  187. @Override
  188. URIish getURI() {
  189. return uri.setPath(objectsPath);
  190. }
  191. @Override
  192. Collection<WalkRemoteObjectDatabase> getAlternates() throws IOException {
  193. try {
  194. return readAlternates(INFO_ALTERNATES);
  195. } catch (FileNotFoundException err) {
  196. return null;
  197. }
  198. }
  199. @Override
  200. WalkRemoteObjectDatabase openAlternate(final String location)
  201. throws IOException {
  202. return new SftpObjectDB(this, location);
  203. }
  204. @Override
  205. Collection<String> getPackNames() throws IOException {
  206. final List<String> packs = new ArrayList<String>();
  207. try {
  208. final Collection<ChannelSftp.LsEntry> list = ftp.ls("pack"); //$NON-NLS-1$
  209. final HashMap<String, ChannelSftp.LsEntry> files;
  210. final HashMap<String, Integer> mtimes;
  211. files = new HashMap<String, ChannelSftp.LsEntry>();
  212. mtimes = new HashMap<String, Integer>();
  213. for (final ChannelSftp.LsEntry ent : list)
  214. files.put(ent.getFilename(), ent);
  215. for (final ChannelSftp.LsEntry ent : list) {
  216. final String n = ent.getFilename();
  217. if (!n.startsWith("pack-") || !n.endsWith(".pack")) //$NON-NLS-1$ //$NON-NLS-2$
  218. continue;
  219. final String in = n.substring(0, n.length() - 5) + ".idx"; //$NON-NLS-1$
  220. if (!files.containsKey(in))
  221. continue;
  222. mtimes.put(n, Integer.valueOf(ent.getAttrs().getMTime()));
  223. packs.add(n);
  224. }
  225. Collections.sort(packs, new Comparator<String>() {
  226. public int compare(final String o1, final String o2) {
  227. return mtimes.get(o2).intValue()
  228. - mtimes.get(o1).intValue();
  229. }
  230. });
  231. } catch (SftpException je) {
  232. throw new TransportException(
  233. MessageFormat.format(JGitText.get().cannotListPackPath,
  234. objectsPath, je.getMessage()),
  235. je);
  236. }
  237. return packs;
  238. }
  239. @Override
  240. FileStream open(final String path) throws IOException {
  241. try {
  242. final SftpATTRS a = ftp.lstat(path);
  243. return new FileStream(ftp.get(path), a.getSize());
  244. } catch (SftpException je) {
  245. if (je.id == ChannelSftp.SSH_FX_NO_SUCH_FILE)
  246. throw new FileNotFoundException(path);
  247. throw new TransportException(MessageFormat.format(
  248. JGitText.get().cannotGetObjectsPath, objectsPath, path,
  249. je.getMessage()), je);
  250. }
  251. }
  252. @Override
  253. void deleteFile(final String path) throws IOException {
  254. try {
  255. ftp.rm(path);
  256. } catch (SftpException je) {
  257. if (je.id == ChannelSftp.SSH_FX_NO_SUCH_FILE)
  258. return;
  259. throw new TransportException(MessageFormat.format(
  260. JGitText.get().cannotDeleteObjectsPath, objectsPath,
  261. path, je.getMessage()), je);
  262. }
  263. // Prune any now empty directories.
  264. //
  265. String dir = path;
  266. int s = dir.lastIndexOf('/');
  267. while (s > 0) {
  268. try {
  269. dir = dir.substring(0, s);
  270. ftp.rmdir(dir);
  271. s = dir.lastIndexOf('/');
  272. } catch (SftpException je) {
  273. // If we cannot delete it, leave it alone. It may have
  274. // entries still in it, or maybe we lack write access on
  275. // the parent. Either way it isn't a fatal error.
  276. //
  277. break;
  278. }
  279. }
  280. }
  281. @Override
  282. OutputStream writeFile(final String path,
  283. final ProgressMonitor monitor, final String monitorTask)
  284. throws IOException {
  285. try {
  286. return ftp.put(path);
  287. } catch (SftpException je) {
  288. if (je.id == ChannelSftp.SSH_FX_NO_SUCH_FILE) {
  289. mkdir_p(path);
  290. try {
  291. return ftp.put(path);
  292. } catch (SftpException je2) {
  293. je = je2;
  294. }
  295. }
  296. throw new TransportException(MessageFormat.format(
  297. JGitText.get().cannotWriteObjectsPath, objectsPath,
  298. path, je.getMessage()), je);
  299. }
  300. }
  301. @Override
  302. void writeFile(final String path, final byte[] data) throws IOException {
  303. final String lock = path + ".lock"; //$NON-NLS-1$
  304. try {
  305. super.writeFile(lock, data);
  306. try {
  307. ftp.rename(lock, path);
  308. } catch (SftpException je) {
  309. throw new TransportException(MessageFormat.format(
  310. JGitText.get().cannotWriteObjectsPath, objectsPath,
  311. path, je.getMessage()), je);
  312. }
  313. } catch (IOException err) {
  314. try {
  315. ftp.rm(lock);
  316. } catch (SftpException e) {
  317. // Ignore deletion failure, we are already
  318. // failing anyway.
  319. }
  320. throw err;
  321. }
  322. }
  323. private void mkdir_p(String path) throws IOException {
  324. final int s = path.lastIndexOf('/');
  325. if (s <= 0)
  326. return;
  327. path = path.substring(0, s);
  328. try {
  329. ftp.mkdir(path);
  330. } catch (SftpException je) {
  331. if (je.id == ChannelSftp.SSH_FX_NO_SUCH_FILE) {
  332. mkdir_p(path);
  333. try {
  334. ftp.mkdir(path);
  335. return;
  336. } catch (SftpException je2) {
  337. je = je2;
  338. }
  339. }
  340. throw new TransportException(MessageFormat.format(
  341. JGitText.get().cannotMkdirObjectPath, objectsPath, path,
  342. je.getMessage()), je);
  343. }
  344. }
  345. Map<String, Ref> readAdvertisedRefs() throws TransportException {
  346. final TreeMap<String, Ref> avail = new TreeMap<String, Ref>();
  347. readPackedRefs(avail);
  348. readRef(avail, ROOT_DIR + Constants.HEAD, Constants.HEAD);
  349. readLooseRefs(avail, ROOT_DIR + "refs", "refs/"); //$NON-NLS-1$ //$NON-NLS-2$
  350. return avail;
  351. }
  352. @SuppressWarnings("unchecked")
  353. private void readLooseRefs(final TreeMap<String, Ref> avail,
  354. final String dir, final String prefix)
  355. throws TransportException {
  356. final Collection<ChannelSftp.LsEntry> list;
  357. try {
  358. list = ftp.ls(dir);
  359. } catch (SftpException je) {
  360. throw new TransportException(MessageFormat.format(
  361. JGitText.get().cannotListObjectsPath, objectsPath, dir,
  362. je.getMessage()), je);
  363. }
  364. for (final ChannelSftp.LsEntry ent : list) {
  365. final String n = ent.getFilename();
  366. if (".".equals(n) || "..".equals(n)) //$NON-NLS-1$ //$NON-NLS-2$
  367. continue;
  368. final String nPath = dir + "/" + n; //$NON-NLS-1$
  369. if (ent.getAttrs().isDir())
  370. readLooseRefs(avail, nPath, prefix + n + "/"); //$NON-NLS-1$
  371. else
  372. readRef(avail, nPath, prefix + n);
  373. }
  374. }
  375. private Ref readRef(final TreeMap<String, Ref> avail,
  376. final String path, final String name) throws TransportException {
  377. final String line;
  378. try {
  379. final BufferedReader br = openReader(path);
  380. try {
  381. line = br.readLine();
  382. } finally {
  383. br.close();
  384. }
  385. } catch (FileNotFoundException noRef) {
  386. return null;
  387. } catch (IOException err) {
  388. throw new TransportException(MessageFormat.format(
  389. JGitText.get().cannotReadObjectsPath, objectsPath, path,
  390. err.getMessage()), err);
  391. }
  392. if (line == null)
  393. throw new TransportException(
  394. MessageFormat.format(JGitText.get().emptyRef, name));
  395. if (line.startsWith("ref: ")) { //$NON-NLS-1$
  396. final String target = line.substring("ref: ".length()); //$NON-NLS-1$
  397. Ref r = avail.get(target);
  398. if (r == null)
  399. r = readRef(avail, ROOT_DIR + target, target);
  400. if (r == null)
  401. r = new ObjectIdRef.Unpeeled(Ref.Storage.NEW, target, null);
  402. r = new SymbolicRef(name, r);
  403. avail.put(r.getName(), r);
  404. return r;
  405. }
  406. if (ObjectId.isId(line)) {
  407. final Ref r = new ObjectIdRef.Unpeeled(loose(avail.get(name)),
  408. name, ObjectId.fromString(line));
  409. avail.put(r.getName(), r);
  410. return r;
  411. }
  412. throw new TransportException(
  413. MessageFormat.format(JGitText.get().badRef, name, line));
  414. }
  415. private Storage loose(final Ref r) {
  416. if (r != null && r.getStorage() == Storage.PACKED)
  417. return Storage.LOOSE_PACKED;
  418. return Storage.LOOSE;
  419. }
  420. @Override
  421. void close() {
  422. if (ftp != null) {
  423. try {
  424. if (ftp.isConnected())
  425. ftp.disconnect();
  426. } finally {
  427. ftp = null;
  428. }
  429. }
  430. }
  431. }
  432. }