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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  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 static org.eclipse.jgit.lib.Constants.LOCK_SUFFIX;
  45. import java.io.BufferedReader;
  46. import java.io.FileNotFoundException;
  47. import java.io.IOException;
  48. import java.io.OutputStream;
  49. import java.text.MessageFormat;
  50. import java.util.ArrayList;
  51. import java.util.Collection;
  52. import java.util.Collections;
  53. import java.util.Comparator;
  54. import java.util.EnumSet;
  55. import java.util.HashMap;
  56. import java.util.List;
  57. import java.util.Map;
  58. import java.util.Set;
  59. import java.util.TreeMap;
  60. import org.eclipse.jgit.errors.NotSupportedException;
  61. import org.eclipse.jgit.errors.TransportException;
  62. import org.eclipse.jgit.internal.JGitText;
  63. import org.eclipse.jgit.lib.Constants;
  64. import org.eclipse.jgit.lib.ObjectId;
  65. import org.eclipse.jgit.lib.ObjectIdRef;
  66. import org.eclipse.jgit.lib.ProgressMonitor;
  67. import org.eclipse.jgit.lib.Ref;
  68. import org.eclipse.jgit.lib.Ref.Storage;
  69. import org.eclipse.jgit.lib.Repository;
  70. import org.eclipse.jgit.lib.SymbolicRef;
  71. import com.jcraft.jsch.Channel;
  72. import com.jcraft.jsch.ChannelSftp;
  73. import com.jcraft.jsch.JSchException;
  74. import com.jcraft.jsch.SftpATTRS;
  75. import com.jcraft.jsch.SftpException;
  76. /**
  77. * Transport over the non-Git aware SFTP (SSH based FTP) protocol.
  78. * <p>
  79. * The SFTP transport does not require any specialized Git support on the remote
  80. * (server side) repository. Object files are retrieved directly through secure
  81. * shell's FTP protocol, making it possible to copy objects from a remote
  82. * repository that is available over SSH, but whose remote host does not have
  83. * Git installed.
  84. * <p>
  85. * Unlike the HTTP variant (see
  86. * {@link org.eclipse.jgit.transport.TransportHttp}) we rely upon being able to
  87. * list files in directories, as the SFTP protocol supports this function. By
  88. * listing files through SFTP we can avoid needing to have current
  89. * <code>objects/info/packs</code> or <code>info/refs</code> files on the remote
  90. * repository and access the data directly, much as Git itself would.
  91. * <p>
  92. * Concurrent pushing over this transport is not supported. Multiple concurrent
  93. * push operations may cause confusion in the repository state.
  94. *
  95. * @see WalkFetchConnection
  96. */
  97. public class TransportSftp extends SshTransport implements WalkTransport {
  98. static final TransportProtocol PROTO_SFTP = new TransportProtocol() {
  99. @Override
  100. public String getName() {
  101. return JGitText.get().transportProtoSFTP;
  102. }
  103. @Override
  104. public Set<String> getSchemes() {
  105. return Collections.singleton("sftp"); //$NON-NLS-1$
  106. }
  107. @Override
  108. public Set<URIishField> getRequiredFields() {
  109. return Collections.unmodifiableSet(EnumSet.of(URIishField.HOST,
  110. URIishField.PATH));
  111. }
  112. @Override
  113. public Set<URIishField> getOptionalFields() {
  114. return Collections.unmodifiableSet(EnumSet.of(URIishField.USER,
  115. URIishField.PASS, URIishField.PORT));
  116. }
  117. @Override
  118. public int getDefaultPort() {
  119. return 22;
  120. }
  121. @Override
  122. public Transport open(URIish uri, Repository local, String remoteName)
  123. throws NotSupportedException {
  124. return new TransportSftp(local, uri);
  125. }
  126. };
  127. TransportSftp(final Repository local, final URIish uri) {
  128. super(local, uri);
  129. }
  130. /** {@inheritDoc} */
  131. @Override
  132. public FetchConnection openFetch() throws TransportException {
  133. final SftpObjectDB c = new SftpObjectDB(uri.getPath());
  134. final WalkFetchConnection r = new WalkFetchConnection(this, c);
  135. r.available(c.readAdvertisedRefs());
  136. return r;
  137. }
  138. /** {@inheritDoc} */
  139. @Override
  140. public PushConnection openPush() throws TransportException {
  141. final SftpObjectDB c = new SftpObjectDB(uri.getPath());
  142. final WalkPushConnection r = new WalkPushConnection(this, c);
  143. r.available(c.readAdvertisedRefs());
  144. return r;
  145. }
  146. ChannelSftp newSftp() throws TransportException {
  147. final int tms = getTimeout() > 0 ? getTimeout() * 1000 : 0;
  148. try {
  149. // @TODO: Fix so that this operation is generic and casting to
  150. // JschSession is no longer necessary.
  151. final Channel channel = ((JschSession) getSession())
  152. .getSftpChannel();
  153. channel.connect(tms);
  154. return (ChannelSftp) channel;
  155. } catch (JSchException je) {
  156. throw new TransportException(uri, je.getMessage(), je);
  157. }
  158. }
  159. class SftpObjectDB extends WalkRemoteObjectDatabase {
  160. private final String objectsPath;
  161. private ChannelSftp ftp;
  162. SftpObjectDB(String path) throws TransportException {
  163. if (path.startsWith("/~")) //$NON-NLS-1$
  164. path = path.substring(1);
  165. if (path.startsWith("~/")) //$NON-NLS-1$
  166. path = path.substring(2);
  167. try {
  168. ftp = newSftp();
  169. ftp.cd(path);
  170. ftp.cd("objects"); //$NON-NLS-1$
  171. objectsPath = ftp.pwd();
  172. } catch (TransportException err) {
  173. close();
  174. throw err;
  175. } catch (SftpException je) {
  176. throw new TransportException(MessageFormat.format(
  177. JGitText.get().cannotEnterObjectsPath, path,
  178. je.getMessage()), je);
  179. }
  180. }
  181. SftpObjectDB(final SftpObjectDB parent, final String p)
  182. throws TransportException {
  183. try {
  184. ftp = newSftp();
  185. ftp.cd(parent.objectsPath);
  186. ftp.cd(p);
  187. objectsPath = ftp.pwd();
  188. } catch (TransportException err) {
  189. close();
  190. throw err;
  191. } catch (SftpException je) {
  192. throw new TransportException(MessageFormat.format(
  193. JGitText.get().cannotEnterPathFromParent, p,
  194. parent.objectsPath, je.getMessage()), je);
  195. }
  196. }
  197. @Override
  198. URIish getURI() {
  199. return uri.setPath(objectsPath);
  200. }
  201. @Override
  202. Collection<WalkRemoteObjectDatabase> getAlternates() throws IOException {
  203. try {
  204. return readAlternates(INFO_ALTERNATES);
  205. } catch (FileNotFoundException err) {
  206. return null;
  207. }
  208. }
  209. @Override
  210. WalkRemoteObjectDatabase openAlternate(final String location)
  211. throws IOException {
  212. return new SftpObjectDB(this, location);
  213. }
  214. @Override
  215. Collection<String> getPackNames() throws IOException {
  216. final List<String> packs = new ArrayList<>();
  217. try {
  218. @SuppressWarnings("unchecked")
  219. final Collection<ChannelSftp.LsEntry> list = ftp.ls("pack"); //$NON-NLS-1$
  220. final HashMap<String, ChannelSftp.LsEntry> files;
  221. final HashMap<String, Integer> mtimes;
  222. files = new HashMap<>();
  223. mtimes = new HashMap<>();
  224. for (final ChannelSftp.LsEntry ent : list)
  225. files.put(ent.getFilename(), ent);
  226. for (final ChannelSftp.LsEntry ent : list) {
  227. final String n = ent.getFilename();
  228. if (!n.startsWith("pack-") || !n.endsWith(".pack")) //$NON-NLS-1$ //$NON-NLS-2$
  229. continue;
  230. final String in = n.substring(0, n.length() - 5) + ".idx"; //$NON-NLS-1$
  231. if (!files.containsKey(in))
  232. continue;
  233. mtimes.put(n, Integer.valueOf(ent.getAttrs().getMTime()));
  234. packs.add(n);
  235. }
  236. Collections.sort(packs, new Comparator<String>() {
  237. @Override
  238. public int compare(final String o1, final String o2) {
  239. return mtimes.get(o2).intValue()
  240. - mtimes.get(o1).intValue();
  241. }
  242. });
  243. } catch (SftpException je) {
  244. throw new TransportException(
  245. MessageFormat.format(JGitText.get().cannotListPackPath,
  246. objectsPath, je.getMessage()),
  247. je);
  248. }
  249. return packs;
  250. }
  251. @Override
  252. FileStream open(final String path) throws IOException {
  253. try {
  254. final SftpATTRS a = ftp.lstat(path);
  255. return new FileStream(ftp.get(path), a.getSize());
  256. } catch (SftpException je) {
  257. if (je.id == ChannelSftp.SSH_FX_NO_SUCH_FILE)
  258. throw new FileNotFoundException(path);
  259. throw new TransportException(MessageFormat.format(
  260. JGitText.get().cannotGetObjectsPath, objectsPath, path,
  261. je.getMessage()), je);
  262. }
  263. }
  264. @Override
  265. void deleteFile(final String path) throws IOException {
  266. try {
  267. ftp.rm(path);
  268. } catch (SftpException je) {
  269. if (je.id == ChannelSftp.SSH_FX_NO_SUCH_FILE)
  270. return;
  271. throw new TransportException(MessageFormat.format(
  272. JGitText.get().cannotDeleteObjectsPath, objectsPath,
  273. path, je.getMessage()), je);
  274. }
  275. // Prune any now empty directories.
  276. //
  277. String dir = path;
  278. int s = dir.lastIndexOf('/');
  279. while (s > 0) {
  280. try {
  281. dir = dir.substring(0, s);
  282. ftp.rmdir(dir);
  283. s = dir.lastIndexOf('/');
  284. } catch (SftpException je) {
  285. // If we cannot delete it, leave it alone. It may have
  286. // entries still in it, or maybe we lack write access on
  287. // the parent. Either way it isn't a fatal error.
  288. //
  289. break;
  290. }
  291. }
  292. }
  293. @Override
  294. OutputStream writeFile(final String path,
  295. final ProgressMonitor monitor, final String monitorTask)
  296. throws IOException {
  297. try {
  298. return ftp.put(path);
  299. } catch (SftpException je) {
  300. if (je.id == ChannelSftp.SSH_FX_NO_SUCH_FILE) {
  301. mkdir_p(path);
  302. try {
  303. return ftp.put(path);
  304. } catch (SftpException je2) {
  305. je = je2;
  306. }
  307. }
  308. throw new TransportException(MessageFormat.format(
  309. JGitText.get().cannotWriteObjectsPath, objectsPath,
  310. path, je.getMessage()), je);
  311. }
  312. }
  313. @Override
  314. void writeFile(final String path, final byte[] data) throws IOException {
  315. final String lock = path + LOCK_SUFFIX;
  316. try {
  317. super.writeFile(lock, data);
  318. try {
  319. ftp.rename(lock, path);
  320. } catch (SftpException je) {
  321. throw new TransportException(MessageFormat.format(
  322. JGitText.get().cannotWriteObjectsPath, objectsPath,
  323. path, je.getMessage()), je);
  324. }
  325. } catch (IOException err) {
  326. try {
  327. ftp.rm(lock);
  328. } catch (SftpException e) {
  329. // Ignore deletion failure, we are already
  330. // failing anyway.
  331. }
  332. throw err;
  333. }
  334. }
  335. private void mkdir_p(String path) throws IOException {
  336. final int s = path.lastIndexOf('/');
  337. if (s <= 0)
  338. return;
  339. path = path.substring(0, s);
  340. try {
  341. ftp.mkdir(path);
  342. } catch (SftpException je) {
  343. if (je.id == ChannelSftp.SSH_FX_NO_SUCH_FILE) {
  344. mkdir_p(path);
  345. try {
  346. ftp.mkdir(path);
  347. return;
  348. } catch (SftpException je2) {
  349. je = je2;
  350. }
  351. }
  352. throw new TransportException(MessageFormat.format(
  353. JGitText.get().cannotMkdirObjectPath, objectsPath, path,
  354. je.getMessage()), je);
  355. }
  356. }
  357. Map<String, Ref> readAdvertisedRefs() throws TransportException {
  358. final TreeMap<String, Ref> avail = new TreeMap<>();
  359. readPackedRefs(avail);
  360. readRef(avail, ROOT_DIR + Constants.HEAD, Constants.HEAD);
  361. readLooseRefs(avail, ROOT_DIR + "refs", "refs/"); //$NON-NLS-1$ //$NON-NLS-2$
  362. return avail;
  363. }
  364. @SuppressWarnings("unchecked")
  365. private void readLooseRefs(final TreeMap<String, Ref> avail,
  366. final String dir, final String prefix)
  367. throws TransportException {
  368. final Collection<ChannelSftp.LsEntry> list;
  369. try {
  370. list = ftp.ls(dir);
  371. } catch (SftpException je) {
  372. throw new TransportException(MessageFormat.format(
  373. JGitText.get().cannotListObjectsPath, objectsPath, dir,
  374. je.getMessage()), je);
  375. }
  376. for (final ChannelSftp.LsEntry ent : list) {
  377. final String n = ent.getFilename();
  378. if (".".equals(n) || "..".equals(n)) //$NON-NLS-1$ //$NON-NLS-2$
  379. continue;
  380. final String nPath = dir + "/" + n; //$NON-NLS-1$
  381. if (ent.getAttrs().isDir())
  382. readLooseRefs(avail, nPath, prefix + n + "/"); //$NON-NLS-1$
  383. else
  384. readRef(avail, nPath, prefix + n);
  385. }
  386. }
  387. private Ref readRef(final TreeMap<String, Ref> avail,
  388. final String path, final String name) throws TransportException {
  389. final String line;
  390. try {
  391. final BufferedReader br = openReader(path);
  392. try {
  393. line = br.readLine();
  394. } finally {
  395. br.close();
  396. }
  397. } catch (FileNotFoundException noRef) {
  398. return null;
  399. } catch (IOException err) {
  400. throw new TransportException(MessageFormat.format(
  401. JGitText.get().cannotReadObjectsPath, objectsPath, path,
  402. err.getMessage()), err);
  403. }
  404. if (line == null)
  405. throw new TransportException(
  406. MessageFormat.format(JGitText.get().emptyRef, name));
  407. if (line.startsWith("ref: ")) { //$NON-NLS-1$
  408. final String target = line.substring("ref: ".length()); //$NON-NLS-1$
  409. Ref r = avail.get(target);
  410. if (r == null)
  411. r = readRef(avail, ROOT_DIR + target, target);
  412. if (r == null)
  413. r = new ObjectIdRef.Unpeeled(Ref.Storage.NEW, target, null);
  414. r = new SymbolicRef(name, r);
  415. avail.put(r.getName(), r);
  416. return r;
  417. }
  418. if (ObjectId.isId(line)) {
  419. final Ref r = new ObjectIdRef.Unpeeled(loose(avail.get(name)),
  420. name, ObjectId.fromString(line));
  421. avail.put(r.getName(), r);
  422. return r;
  423. }
  424. throw new TransportException(
  425. MessageFormat.format(JGitText.get().badRef, name, line));
  426. }
  427. private Storage loose(final Ref r) {
  428. if (r != null && r.getStorage() == Storage.PACKED)
  429. return Storage.LOOSE_PACKED;
  430. return Storage.LOOSE;
  431. }
  432. @Override
  433. void close() {
  434. if (ftp != null) {
  435. try {
  436. if (ftp.isConnected())
  437. ftp.disconnect();
  438. } finally {
  439. ftp = null;
  440. }
  441. }
  442. }
  443. }
  444. }