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