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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  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. @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(final Repository local, final URIish uri) {
  126. super(local, uri);
  127. }
  128. @Override
  129. public FetchConnection openFetch() throws TransportException {
  130. final SftpObjectDB c = new SftpObjectDB(uri.getPath());
  131. final WalkFetchConnection r = new WalkFetchConnection(this, c);
  132. r.available(c.readAdvertisedRefs());
  133. return r;
  134. }
  135. @Override
  136. public PushConnection openPush() throws TransportException {
  137. final SftpObjectDB c = new SftpObjectDB(uri.getPath());
  138. final WalkPushConnection r = new WalkPushConnection(this, c);
  139. r.available(c.readAdvertisedRefs());
  140. return r;
  141. }
  142. ChannelSftp newSftp() throws TransportException {
  143. final int tms = getTimeout() > 0 ? getTimeout() * 1000 : 0;
  144. try {
  145. // @TODO: Fix so that this operation is generic and casting to
  146. // JschSession is no longer necessary.
  147. final Channel channel = ((JschSession) getSession())
  148. .getSftpChannel();
  149. channel.connect(tms);
  150. return (ChannelSftp) channel;
  151. } catch (JSchException je) {
  152. throw new TransportException(uri, je.getMessage(), je);
  153. }
  154. }
  155. class SftpObjectDB extends WalkRemoteObjectDatabase {
  156. private final String objectsPath;
  157. private ChannelSftp ftp;
  158. SftpObjectDB(String path) throws TransportException {
  159. if (path.startsWith("/~")) //$NON-NLS-1$
  160. path = path.substring(1);
  161. if (path.startsWith("~/")) //$NON-NLS-1$
  162. path = path.substring(2);
  163. try {
  164. ftp = newSftp();
  165. ftp.cd(path);
  166. ftp.cd("objects"); //$NON-NLS-1$
  167. objectsPath = ftp.pwd();
  168. } catch (TransportException err) {
  169. close();
  170. throw err;
  171. } catch (SftpException je) {
  172. throw new TransportException(MessageFormat.format(
  173. JGitText.get().cannotEnterObjectsPath, path,
  174. je.getMessage()), je);
  175. }
  176. }
  177. SftpObjectDB(final SftpObjectDB parent, final String p)
  178. throws TransportException {
  179. try {
  180. ftp = newSftp();
  181. ftp.cd(parent.objectsPath);
  182. ftp.cd(p);
  183. objectsPath = ftp.pwd();
  184. } catch (TransportException err) {
  185. close();
  186. throw err;
  187. } catch (SftpException je) {
  188. throw new TransportException(MessageFormat.format(
  189. JGitText.get().cannotEnterPathFromParent, p,
  190. parent.objectsPath, je.getMessage()), je);
  191. }
  192. }
  193. @Override
  194. URIish getURI() {
  195. return uri.setPath(objectsPath);
  196. }
  197. @Override
  198. Collection<WalkRemoteObjectDatabase> getAlternates() throws IOException {
  199. try {
  200. return readAlternates(INFO_ALTERNATES);
  201. } catch (FileNotFoundException err) {
  202. return null;
  203. }
  204. }
  205. @Override
  206. WalkRemoteObjectDatabase openAlternate(final String location)
  207. throws IOException {
  208. return new SftpObjectDB(this, location);
  209. }
  210. @Override
  211. Collection<String> getPackNames() throws IOException {
  212. final List<String> packs = new ArrayList<>();
  213. try {
  214. @SuppressWarnings("unchecked")
  215. final Collection<ChannelSftp.LsEntry> list = ftp.ls("pack"); //$NON-NLS-1$
  216. final HashMap<String, ChannelSftp.LsEntry> files;
  217. final HashMap<String, Integer> mtimes;
  218. files = new HashMap<>();
  219. mtimes = new HashMap<>();
  220. for (final ChannelSftp.LsEntry ent : list)
  221. files.put(ent.getFilename(), ent);
  222. for (final ChannelSftp.LsEntry ent : list) {
  223. final String n = ent.getFilename();
  224. if (!n.startsWith("pack-") || !n.endsWith(".pack")) //$NON-NLS-1$ //$NON-NLS-2$
  225. continue;
  226. final String in = n.substring(0, n.length() - 5) + ".idx"; //$NON-NLS-1$
  227. if (!files.containsKey(in))
  228. continue;
  229. mtimes.put(n, Integer.valueOf(ent.getAttrs().getMTime()));
  230. packs.add(n);
  231. }
  232. Collections.sort(packs, new Comparator<String>() {
  233. @Override
  234. public int compare(final String o1, final String o2) {
  235. return mtimes.get(o2).intValue()
  236. - mtimes.get(o1).intValue();
  237. }
  238. });
  239. } catch (SftpException je) {
  240. throw new TransportException(
  241. MessageFormat.format(JGitText.get().cannotListPackPath,
  242. objectsPath, je.getMessage()),
  243. je);
  244. }
  245. return packs;
  246. }
  247. @Override
  248. FileStream open(final String path) throws IOException {
  249. try {
  250. final SftpATTRS a = ftp.lstat(path);
  251. return new FileStream(ftp.get(path), a.getSize());
  252. } catch (SftpException je) {
  253. if (je.id == ChannelSftp.SSH_FX_NO_SUCH_FILE)
  254. throw new FileNotFoundException(path);
  255. throw new TransportException(MessageFormat.format(
  256. JGitText.get().cannotGetObjectsPath, objectsPath, path,
  257. je.getMessage()), je);
  258. }
  259. }
  260. @Override
  261. void deleteFile(final String path) throws IOException {
  262. try {
  263. ftp.rm(path);
  264. } catch (SftpException je) {
  265. if (je.id == ChannelSftp.SSH_FX_NO_SUCH_FILE)
  266. return;
  267. throw new TransportException(MessageFormat.format(
  268. JGitText.get().cannotDeleteObjectsPath, objectsPath,
  269. path, je.getMessage()), je);
  270. }
  271. // Prune any now empty directories.
  272. //
  273. String dir = path;
  274. int s = dir.lastIndexOf('/');
  275. while (s > 0) {
  276. try {
  277. dir = dir.substring(0, s);
  278. ftp.rmdir(dir);
  279. s = dir.lastIndexOf('/');
  280. } catch (SftpException je) {
  281. // If we cannot delete it, leave it alone. It may have
  282. // entries still in it, or maybe we lack write access on
  283. // the parent. Either way it isn't a fatal error.
  284. //
  285. break;
  286. }
  287. }
  288. }
  289. @Override
  290. OutputStream writeFile(final String path,
  291. final ProgressMonitor monitor, final String monitorTask)
  292. throws IOException {
  293. try {
  294. return ftp.put(path);
  295. } catch (SftpException je) {
  296. if (je.id == ChannelSftp.SSH_FX_NO_SUCH_FILE) {
  297. mkdir_p(path);
  298. try {
  299. return ftp.put(path);
  300. } catch (SftpException je2) {
  301. je = je2;
  302. }
  303. }
  304. throw new TransportException(MessageFormat.format(
  305. JGitText.get().cannotWriteObjectsPath, objectsPath,
  306. path, je.getMessage()), je);
  307. }
  308. }
  309. @Override
  310. void writeFile(final String path, final byte[] data) throws IOException {
  311. final String lock = path + ".lock"; //$NON-NLS-1$
  312. try {
  313. super.writeFile(lock, data);
  314. try {
  315. ftp.rename(lock, path);
  316. } catch (SftpException je) {
  317. throw new TransportException(MessageFormat.format(
  318. JGitText.get().cannotWriteObjectsPath, objectsPath,
  319. path, je.getMessage()), je);
  320. }
  321. } catch (IOException err) {
  322. try {
  323. ftp.rm(lock);
  324. } catch (SftpException e) {
  325. // Ignore deletion failure, we are already
  326. // failing anyway.
  327. }
  328. throw err;
  329. }
  330. }
  331. private void mkdir_p(String path) throws IOException {
  332. final int s = path.lastIndexOf('/');
  333. if (s <= 0)
  334. return;
  335. path = path.substring(0, s);
  336. try {
  337. ftp.mkdir(path);
  338. } catch (SftpException je) {
  339. if (je.id == ChannelSftp.SSH_FX_NO_SUCH_FILE) {
  340. mkdir_p(path);
  341. try {
  342. ftp.mkdir(path);
  343. return;
  344. } catch (SftpException je2) {
  345. je = je2;
  346. }
  347. }
  348. throw new TransportException(MessageFormat.format(
  349. JGitText.get().cannotMkdirObjectPath, objectsPath, path,
  350. je.getMessage()), je);
  351. }
  352. }
  353. Map<String, Ref> readAdvertisedRefs() throws TransportException {
  354. final TreeMap<String, Ref> avail = new TreeMap<>();
  355. readPackedRefs(avail);
  356. readRef(avail, ROOT_DIR + Constants.HEAD, Constants.HEAD);
  357. readLooseRefs(avail, ROOT_DIR + "refs", "refs/"); //$NON-NLS-1$ //$NON-NLS-2$
  358. return avail;
  359. }
  360. @SuppressWarnings("unchecked")
  361. private void readLooseRefs(final TreeMap<String, Ref> avail,
  362. final String dir, final String prefix)
  363. throws TransportException {
  364. final Collection<ChannelSftp.LsEntry> list;
  365. try {
  366. list = ftp.ls(dir);
  367. } catch (SftpException je) {
  368. throw new TransportException(MessageFormat.format(
  369. JGitText.get().cannotListObjectsPath, objectsPath, dir,
  370. je.getMessage()), je);
  371. }
  372. for (final ChannelSftp.LsEntry ent : list) {
  373. final String n = ent.getFilename();
  374. if (".".equals(n) || "..".equals(n)) //$NON-NLS-1$ //$NON-NLS-2$
  375. continue;
  376. final String nPath = dir + "/" + n; //$NON-NLS-1$
  377. if (ent.getAttrs().isDir())
  378. readLooseRefs(avail, nPath, prefix + n + "/"); //$NON-NLS-1$
  379. else
  380. readRef(avail, nPath, prefix + n);
  381. }
  382. }
  383. private Ref readRef(final TreeMap<String, Ref> avail,
  384. final String path, final String name) throws TransportException {
  385. final String line;
  386. try {
  387. final BufferedReader br = openReader(path);
  388. try {
  389. line = br.readLine();
  390. } finally {
  391. br.close();
  392. }
  393. } catch (FileNotFoundException noRef) {
  394. return null;
  395. } catch (IOException err) {
  396. throw new TransportException(MessageFormat.format(
  397. JGitText.get().cannotReadObjectsPath, objectsPath, path,
  398. err.getMessage()), err);
  399. }
  400. if (line == null)
  401. throw new TransportException(
  402. MessageFormat.format(JGitText.get().emptyRef, name));
  403. if (line.startsWith("ref: ")) { //$NON-NLS-1$
  404. final String target = line.substring("ref: ".length()); //$NON-NLS-1$
  405. Ref r = avail.get(target);
  406. if (r == null)
  407. r = readRef(avail, ROOT_DIR + target, target);
  408. if (r == null)
  409. r = new ObjectIdRef.Unpeeled(Ref.Storage.NEW, target, null);
  410. r = new SymbolicRef(name, r);
  411. avail.put(r.getName(), r);
  412. return r;
  413. }
  414. if (ObjectId.isId(line)) {
  415. final Ref r = new ObjectIdRef.Unpeeled(loose(avail.get(name)),
  416. name, ObjectId.fromString(line));
  417. avail.put(r.getName(), r);
  418. return r;
  419. }
  420. throw new TransportException(
  421. MessageFormat.format(JGitText.get().badRef, name, line));
  422. }
  423. private Storage loose(final Ref r) {
  424. if (r != null && r.getStorage() == Storage.PACKED)
  425. return Storage.LOOSE_PACKED;
  426. return Storage.LOOSE;
  427. }
  428. @Override
  429. void close() {
  430. if (ftp != null) {
  431. try {
  432. if (ftp.isConnected())
  433. ftp.disconnect();
  434. } finally {
  435. ftp = null;
  436. }
  437. }
  438. }
  439. }
  440. }